简体   繁体   English

C#:加载C ++ DLL时出现问题

[英]C#: problem loading C++ DLL

In my code, I can load "MessageBoxA" from user32.dll and use it, but if I try to load and use a function from my DLL, I get a crash. 在我的代码中,我可以从user32.dll加载“ MessageBoxA”并使用它,但是如果我尝试从DLL加载并使用一个函数,则会崩溃。

My C# code: 我的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);

[...] [...]

this works 这有效

MessageBoxA(0, "Hello, World!", "This is called from a C# app!",  0);

this crashes 这崩溃

int mean = mymean(12, 14, 16);

And my C++ DLL code: SimpleDLL.cpp: 还有我的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

SimpleDLL.dll is copied to the same folder as the .exe I compile from C# code. 将SimpleDLL.dll复制到与我从C#代码编译的.exe相同的文件夹中。 Using dependency walker, I can see that all necessary DLLs to load SimpleDLL.dll are present. 使用依赖关系遍历器,我可以看到存在所有用于加载SimpleDLL.dll的必需DLL。

C# uses "stdcall" calling convention by default. 默认情况下,C#使用“ stdcall”调用约定。 You've specified "C". 您已指定“ C”。 You need to either specify 您需要指定

[DllImport("SimpleDLL.dll",CallingConvention=CallingConvention.Cdecl)]

or change your c code to: 或将您的C代码更改为:

int _declspec(dllexport) stdcall mymean(int x, int y, int z)

Turns out my C# app was 64-bit (which is C# visual studio default) and my C++ DLL was 32-bit (which is C++ visual studio default). 原来我的C#应用​​程序是64位(这是C#Visual Studio的默认设置),而我的C ++ DLL是32位(这是C ++ Visual Studio的默认设置)。

Thanks for the tip to check the exception type, it was a badimageformatexception. 感谢您提供检查异常类型的提示,它是badimageformatexception。

Sorry - total C# newbie! 抱歉-C#新手!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM