Fix PinvokeStackImbalance Exception in VS2010
The PinvokeStackImbalance exception, previously disabled by default in VS2008, has been enabled by default in VS2010. This exception is intended to alert developers to incorrect calling conventions in DllImport calls.
Problem Definition
When migrating a solution from VS2008 to VS2010, DllImport calls to a C DLL consistently throw the PinvokeStackImbalance exception, even though the DLL itself has not changed.
Resolution
The issue stems from an incorrect calling convention being used in the DllImport declaration. By default, DllImport uses CallingConvention.WinApi, which is equivalent to CallingConvention.StdCall for x86 desktop code. However, the underlying C function is declared as __cdecl, which requires CallingConvention.Cdecl.
Fix
Modify the DllImport declaration to explicitly specify the correct calling convention:
<code class="csharp">[DllImport("ImageOperations.dll", CallingConvention = CallingConvention.Cdecl)] static extern void FasterFunction( [MarshalAs(UnmanagedType.LPArray)]ushort[] inImage, //IntPtr inImage, [MarshalAs(UnmanagedType.LPArray)]byte[] outImage, //IntPtr outImage, int inTotalSize, int inWindow, int inLevel);</code>
Additional Notes
The above is the detailed content of How to Fix the PinvokeStackImbalance Exception in VS2010?. For more information, please follow other related articles on the PHP Chinese website!