DLImport c# 控制台应用程序导入 c++ DLL
DLImport c# console application imports c++ DLL
我无法让它工作。我使用 c++ DLL 项目、c++ ConsoleApplication 和 c# ConsoleApplication 创建了一个测试解决方案 (VS2015)。
两个控制台应用程序都在其主要方法中调用 DLL 函数并将结果打印到控制台。所有项目都构建到同一目录。
这在 c++ ConsoleApplication 中工作正常,因为我只是添加了对 DLL-Project 的引用并包含了 header.
在 c# ConsoleApplication 中,我无法让它工作。我知道它的非托管代码并且我需要使用 DLLImport。
当我尝试 运行 c# 应用程序时,它会在调用 test() 时引发 System.EntryPointNotFoundException。并说找不到入口点 "test"。
那我做错了什么?
DLL.h
#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
DLL_API int test(void);
DLL.cpp
#include "DLL.h"
// This is an example of an exported function.
DLL_API int test(void)
{
return 42;
}
编译为 DLL.dll。
Programm.cs
using System;
using System.Runtime.InteropServices;
namespace DLLTestCSharp
{
class Program
{
[DllImport("DLL.dll")]
public static extern int test();
static void Main(string[] args)
{
Console.WriteLine(test());
Console.Read();
}
}
}
编译为 DLLTestCSharp.exe。
我认为你的问题是,当我们在c/c++中编译代码并导出函数时,根据我们使用的调用约定,export table中有@Test0等名称.我说你下载 CffExplorer 并查看你的 dll 导出 table。然后尝试使用正确的名称导入。
由于 C++ 名称的混淆,找不到入口点。它以一种特殊的独特方式对方法名称进行编码以支持重载和模板。
要禁用此行为并按原样导出方法名称,您需要使用 extern "C"
标记您的方法(或放入 extern "C" { }
块),或添加一个带有导出名称的 .def 文件到您的 dll 项目。
通常在头文件中完成:
#ifdef __cplusplus
extern "C" {
#endif
DLL_API int test();
// other functions
#ifdef __cplusplus
}
#endif
这适用于所有平台。
Def 文件,另一方面,主要是 Windows 方法。你添加一个 ProjectName.def 到你的解决方案并放在那里 exports list:
LIBRARY <libraryname>
EXPORTS
test
更多关于MSDN
我无法让它工作。我使用 c++ DLL 项目、c++ ConsoleApplication 和 c# ConsoleApplication 创建了一个测试解决方案 (VS2015)。 两个控制台应用程序都在其主要方法中调用 DLL 函数并将结果打印到控制台。所有项目都构建到同一目录。
这在 c++ ConsoleApplication 中工作正常,因为我只是添加了对 DLL-Project 的引用并包含了 header.
在 c# ConsoleApplication 中,我无法让它工作。我知道它的非托管代码并且我需要使用 DLLImport。
当我尝试 运行 c# 应用程序时,它会在调用 test() 时引发 System.EntryPointNotFoundException。并说找不到入口点 "test"。
那我做错了什么?
DLL.h
#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
DLL_API int test(void);
DLL.cpp
#include "DLL.h"
// This is an example of an exported function.
DLL_API int test(void)
{
return 42;
}
编译为 DLL.dll。
Programm.cs
using System;
using System.Runtime.InteropServices;
namespace DLLTestCSharp
{
class Program
{
[DllImport("DLL.dll")]
public static extern int test();
static void Main(string[] args)
{
Console.WriteLine(test());
Console.Read();
}
}
}
编译为 DLLTestCSharp.exe。
我认为你的问题是,当我们在c/c++中编译代码并导出函数时,根据我们使用的调用约定,export table中有@Test0等名称.我说你下载 CffExplorer 并查看你的 dll 导出 table。然后尝试使用正确的名称导入。
由于 C++ 名称的混淆,找不到入口点。它以一种特殊的独特方式对方法名称进行编码以支持重载和模板。
要禁用此行为并按原样导出方法名称,您需要使用 extern "C"
标记您的方法(或放入 extern "C" { }
块),或添加一个带有导出名称的 .def 文件到您的 dll 项目。
通常在头文件中完成:
#ifdef __cplusplus
extern "C" {
#endif
DLL_API int test();
// other functions
#ifdef __cplusplus
}
#endif
这适用于所有平台。
Def 文件,另一方面,主要是 Windows 方法。你添加一个 ProjectName.def 到你的解决方案并放在那里 exports list:
LIBRARY <libraryname>
EXPORTS
test
更多关于MSDN