Today I upgraded a C# program from .NET 2.0 to .NET 4.0 and started debugging it.
I got the error message when pInvoke called a C++ function in one of my DLLs:
A call to PInvoke function 'MyMethod' 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.
Why? After some googling I found out that .NET 4.0 activates assistant an named pInvokeStackImbalance MDA (managed debugging assistant) when the CLR detects that the stack becomes unbalanced.
It happens when the DLL’s calling convention is not the same as expected by DllImportAttribute attribute as well as the declaration of the parameters in the managed signature don’t match.
The default value for the CallingConvention field is Winapi (in other words, StdCall convention).
Well, my DLL was using Cdecl calling convetion.
The solution is simple: change the DllImportAttribute line a little bit to instruct it to use Cdecl calling convention.
[DllImport(@”mydll.dll“, CallingConvention = CallingConvention.Cdecl)]
For more information, you can check this page.