War*_*pin 2 c# c++ dll pinvoke
在我的代码中,我可以从user32.dll加载"MessageBoxA"并使用它,但如果我尝试加载并使用我的DLL中的函数,我会崩溃.
我的C#代码:
[DllImport("SimpleDLL.dll")]
static extern int mymean(int a, int b, int c);
[DllImport("user32.dll")]
static extern int MessageBoxA(int hWnd,
string msg,
string caption,
int type);
Run Code Online (Sandbox Code Playgroud)
[...]
这很有效
MessageBoxA(0, "Hello, World!", "This is called from a C# app!", 0);
Run Code Online (Sandbox Code Playgroud)
这次崩溃
int mean = mymean(12, 14, 16);
Run Code Online (Sandbox Code Playgroud)
我的C++ DLL代码:SimpleDLL.cpp:
extern "C" _declspec(dllexport) int mymean(int x, int y, int z)
{
return (x + y + z) / 3;
}
SimpleDLL.def:
LIBRARY "SimpleDLL"
mymean
Run Code Online (Sandbox Code Playgroud)
SimpleDLL.dll被复制到与我从C#代码编译的.exe相同的文件夹中.使用依赖性walker,我可以看到加载SimpleDLL.dll的所有必需的DLL都存在.
默认情况下,C#使用"stdcall"调用约定.你已经指定了"C".你需要指定
[DllImport("SimpleDLL.dll",CallingConvention=CallingConvention.Cdecl)]
或将您的c代码更改为:
int _declspec(dllexport) stdcall mymean(int x, int y, int z)