This post shows you how to fix "Managed Debugging Assistant 'PInvokeStackImbalance' : 'A call to PInvoke function 'YourProjectName::memcpy' has unbalanced the stack." when working with c# unmanaged code.
Managed Debugging Assistant 'PInvokeStackImbalance' : 'A call to PInvoke function 'OBR::memcpy' 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.'
C# unmanaged code
[DllImport("ntdll.dll")]
public static extern unsafe byte* memcpy(byte* dst, byte* src, int count);
[DllImport("ntdll.dll")]
public static extern IntPtr memcpy(IntPtr dst, IntPtr src, int count);
You should understand the "PInvokeStackImbalance" is not an exception, but it's a managed debugging assistant
It was off by default in Visual Studio 2008, but a lot of people did not turn it on, so it's on by default in Visual Studio 2010. The MDA doesn't run in Release mode, so it won't trigger if you build the project for Release mode.
In the above case, calling convention is incorrect. DllImport defaults to CallingConvention.WinApi, which is identical to CallingConvention.StdCall for x86 desktop code. So it should be CallingConvention.Cdecl.
[DllImport("ntdll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern unsafe byte* memcpy(byte* dst, byte* src, int count);
[DllImport("ntdll.dll", CallingConvention = CallingConvention.Cdecl)]
This can be done by modifying your code as show above.