Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get "PInvokeStackImbalance was detected" for this simple example?

Tags:

I'm creating a very simple PInvoke sample:

extern "C" __declspec(dllexport) int Add(int a, int b)
{
    return a + b;
}

[DllImport("CommonNativeLib.dll")]
extern public static int Add(int a, int b);

return NativeMethods.Add(a, b);

But whenever I call the above NativeMethods.Add method I get the following managed debug assistant:

PInvokeStackImbalance was detected Message: A call to PInvoke function 'CommonManagedLib!CommonManagedLib.NativeMethods::Add' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

The call then completes with the expected return value, but having the MDA message appear is both annoying and worrying - I don't fully understand PInvoke yet, but from what I've read I'm pretty sure that my signature is correct - what am I doing wrong?

This is all on a 32-bit OS.

like image 945
Justin Avatar asked Apr 09 '11 03:04

Justin


2 Answers

You need to instead use either

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

or

extern "C" __declspec(dllexport) int __stdcall Add(int a, int b) ...

because regular C functions work differently than the Windows API functions; their "calling conventions" are different, meaning how they pass around parameters is different. (This was hinted at in the error.)

like image 195
user541686 Avatar answered Nov 08 '22 14:11

user541686


The Stack Imbalance reasons are either the signature is not matching else Calling Convention by default calling convention is stdcall. When your calling convention is stdcall callee cleans the stack if you want caller to clean the stack us cdecl calling convention. you can find more Here

But if you are facing because of signature, just go through above link Solve Signature based Stack Imbalance issues using PInvoke extension

like image 27
AirCode One Avatar answered Nov 08 '22 13:11

AirCode One