Reputation: 2446
I'm writing a WPF app that needs to call some C++ code that exists in a dll I've written. I'm always getting PInvokeStackImbalance errors, even with the the most rudimentary test functions. Eg, in the C++ dll:
extern "C" __declspec(dllexport) void Test( int foo);
The function does nothing. The c# side looks like this:
[DllImport("myDll.dll", CharSet = CharSet.Auto)]
private static extern void Test( int foo);
And I call this c# function like so:
Test(1)
... and I get a PInvokeStackImbalance!! How can this be?
Thanks in advance...
Tom
Upvotes: 2
Views: 556
Reputation: 942207
Your [DllImport] declaration is missing the CallingConvention. Required, your Test function is Cdecl since you didn't use the __stdcall keyword. The difference between __cdecl and __stdcall is the way the stack gets cleaned up after the call. __cdecl is the default for most C++ compilers, including Microsoft's. To fix it on the C++ side, you'd declare it like this:
extern "C" __declspec(dllexport)
void __stdcall Test( int foo);
Upvotes: 3
Reputation: 33272
Try to specify CallingConvention.Cdecl. There is an example in the doc. The default calling convention is Winapi
on desktop windows; but your function is declared as extern C
.
Upvotes: 4