我必须从我的 C# 程序中调用 C++ DLL。 我正在尝试使用 PInvoke 来完成此操作 - 在 VS2005\2008 中一切正常,但在迁移到 VS 2010 后,出现此异常:
PInvokeStackImbalance was detected Message: A call to PInvoke function 'sampleFunc' 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++ 原型(prototype):
typedef struct {
unsigned short field1;
unsigned short field2;
} sInfo;
_declspec(dllexport) int sampleFunc(sInfo *info, char *txt);
这是 C# 代码:
[StructLayout(LayoutKind.Sequential)]
struct SInfo
{
//[MarshalAs(UnmanagedType.U1)] //also tried with the MarshalAs attr. Didn't help.
public ushort field1;
//[MarshalAs(UnmanagedType.U1)]
public ushort field2;
};
[DllImport("sampleModule.dll", CharSet=CharSet.Ansi)]
public static extern int sampleFunc(ref SInfo info, [MarshalAs(UnmanagedType.LPStr)] string txt);
我也尝试过使用 IntPtr 而不是 ref SInfo,但得到了相同的结果......
任何帮助将不胜感激,
谢谢大家!
最佳答案
很难看出这在以前是如何运作的。 C++ 声明不声明调用约定,默认值为 __cdecl,除非在 C++ 项目中使用/Gz 编译选项覆盖。您必须告诉 P/Invoke 编码器:
[DllImport("sampleModule.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int sampleFunc(ref SInfo info, string txt);
关于c# - VS2010中的Marshal结构体指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2999338/