PInvokeStackImbalance C# call to unmanaged C++ function

佐手、 提交于 2019-11-27 18:43:57
Graviton

As mentioned in Dane Rose's comment, you can either use __stdcall on your C++ function or declare CallingConvention = CallingConvention.Cdecl on your DllImport.

This is the answer that solves my problem.

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);

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.

Vicky

It's good.I update function define as follow:

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

It works well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!