我正在尝试学习 P/Invoke,所以我用 C++ 创建了一个简单的 dll
KingFucs.h:
namespace KingFuncs
{
class KingFuncs
{
public:
static __declspec(dllexport) int GiveMeNumber(int i);
};
}
KingFuns.cpp:
#include "KingFuncs.h"
#include <stdexcept>
using namespace std;
namespace KingFuncs
{
int KingFuncs::GiveMeNumber(int i)
{
return i;
}
}
所以它确实编译了,然后我将这个 dll 复制到我的 WPF 的调试文件夹中,代码:
[DllImport("KingFuncDll.dll", EntryPoint = "GiveMeNumber", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern int GiveMeNumber(
int i
);
并在按钮点击中调用它:
private void Button_Click(object sender, RoutedEventArgs e)
{
int num = GiveMeNumber(123);
}
但它给了我异常(exception):
Unable to find an entry point named 'GiveMeNumber' in DLL 'KingFuncDll.dll'.
真的....我做错了什么...它显然能够找到DLL,否则将是另一个异常。但是我的方法名是完全一样的……我想不出别的原因了。
最佳答案
您需要在导出函数时使用 extern "C"
以抑制 C++ 名称修改。而且您也不应该尝试对类(class)成员进行 p/invoke。改用自由函数:
extern "C" {
__declspec(dllexport) int GiveMeNumber(int i)
{
return i;
}
}
在托管方面,您的 DllImport
属性都是错误的。不要使用仅适用于 Win32 API 的 SetLastError
。如果没有文本参数,请不要设置 CharSet
。不需要ExactSpelling
。而且调用约定大概是Cdecl
。
[DllImport("KingFuncDll.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern int GiveMeNumber(int i);
关于c# - 在 C# 中调用 C++ dll 时找不到入口点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10109590/