Reputation: 7043
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.
My C# code:
[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:
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. Using dependency walker, I can see that all necessary DLLs to load SimpleDLL.dll are present.
Upvotes: 2
Views: 525
Reputation: 7043
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).
Thanks for the tip to check the exception type, it was a badimageformatexception.
Sorry - total C# newbie!
Upvotes: 0
Reputation: 8706
C# uses "stdcall" calling convention by default. You've specified "C". You need to either specify
[DllImport("SimpleDLL.dll",CallingConvention=CallingConvention.Cdecl)]
or change your c code to:
int _declspec(dllexport) stdcall mymean(int x, int y, int z)
Upvotes: 6