Wednesday, May 09, 2012

VS2010 PInvokeStackImbalance C# call to unmanaged C++ function

 
I just switched to vs2010 from vs2008. Exact same solution, except now every single call to a C++ dll yields a 'pinvokestackimbalance' exception.

First, understand that the code is wrong (and always has been). The "pInvokeStackImbalance" is not an exception per se, but a managed debugging assistant. It was off by default in VS2008, but a lot of people did not turn it on, so it's on by default in VS2010. The MDA does not run in Release mode, so it won't trigger if you build for release.
In your case, the calling convention is incorrect. DllImport defaults to CallingConvention.WinApi, which is identical to CallingConvention.StdCall for x86 desktop code. It should be CallingConvention.Cdecl.


1. declare CallingConvention = CallingConvention.Cdecl on your DllImport.
2. turn it off in VS2010:
  1. CTRL + ALT + E
  2. Under "Managed Debugging Assistants" uncheck PInvokeStackImbalance.

No comments:

Post a Comment