How to solve error A call to PInvoke function MyMethod has unbalanced the stack.

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:

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.

From

[DllImport(@”mydll.dll”)]

to

[DllImport(@”mydll.dll, CallingConvention = CallingConvention.Cdecl)]

For more information, you can check this page.

Please, try my games, play free on-line games on my site, tweet this post url and share it on facebook, google+ and other social medias.

This entry was posted in development and tagged , , , . Bookmark the permalink.
  • xZel

    This is great. Totally solved the problem I was having.

  • Gong

    Very nice. Did the trick for me. Thanks.

  • Randoms

    Thank you good sir 🙂

  • farrukh

    Thanks dear, i spent two days but could not find any solution. but now i resolve my issue. thanks for sharing

  • Levan Gvelukashvili

    love you