Sunday, April 1, 2012

PInvokeStackImbalance was detected Message

Today I was getting the following error, when I was trying to implement mouse movements with a functions, implemented in user32.dll. 
PInvokeStackImbalance was detected Message: A call to PInvoke function ...::mouse_event' 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 interesting thing was - I was getting error in .net 4.0. When I was changing project platform to .net 3.5, all was working fine. After some googling I found this:
In the .NET Framework version 3.5, the pInvokeStackImbalance MDA is disabled by default. When you use the .NET Framework version 3.5 with Visual Studio 2005, thepInvokeStackImbalance MDA will appear in the Managed Debugging Assistants list in the Exceptions dialog box (which is displayed when you click Exceptions on theDebug menu). However, selecting or clearing the Thrown check box for pInvokeStackImbalance does not enable or disable the MDA; it only controls whether Visual Studio throws an exception when the MDA is activated.
My problem was, that I was using DllImport  decleratino incorrectly: 
private static extern void mouse_event(long dwFlags,  long  dx,  long  dy,  long  cButtons,  long  dwExtraInfo);
Instead of 
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo); 


And the problem existed in both .net 3.5 and 4.0, but with a difference, that in .net 3.5 notification was disabled. 
Hope, this will help you to save time.


Happy coding.
Vahagn

No comments:

Post a Comment