After switching to VS2010, the managed debug assistant is displaying an error about an unbalanced stack from a call to an unmanaged C++ function from a C# application.
<It's good.I update function define as follow:
[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
It works well.
As mentioned in Dane Rose's comment, you can either use __stdcall
on your C++ function or declare CallingConvention = CallingConvention.Cdecl
on your DllImport
.
You specify no padding in your C# declaration of the struct, but not in the C++ version. Since you are mixing char arrays that are not all multiples of four and an odd number of 2 byte shorts, the compiler is probably inserting padding within the struct and add the end.
Try wrapping the struct in a #pragma pack
to ensure no padding.
#pragma pack(push)
#pragma pack(1)
// The struct
#pragma pack(pop)
Had the same problem as described - unmanaged C++ app that has worked perfectly for years. When we upgraded to VS2010, we started getting PInvokeStackUnbalanced messages.
adding "__stdcall" to the C++ signature as described above made the issue go away.
You specify stdcall in C# but not in C++, a mismatch here will lead to both the function and the caller popping arguments off of the stack.
On the other hand there is a compiler switch that will turn on stdcall as the default calling convention, (-Gz) are you using that?
Or try this in your C++
short __stdcall SuperSpecialOpenFileFunc(SuperSpecialStruct * stuff);