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

Justin picture Justin · Apr 9, 2011 · Viewed 23k times · Source

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.

Answer

user541686 picture user541686 · Apr 9, 2011

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.)