DllIImport函数抛出堆栈异常

时间:2013-03-26 15:22:37

标签: c# dllimport

我试图在这个h文件中调用函数getFirstAvailableTSSComPort

http://sourceforge.net/p/yeicapi/code/11/tree/trunk/include/yei_threespace_api.h

从h文件中获取的相关结构和枚举(并转换为C#代码)

private enum TSS_Type
{
    TSS_BTL = 0,
    TSS_USB = 1,
    TSS_DNG = 2,
    TSS_WL = 3, //wireless wired (connected to PC)
    TSS_WL_W = 4, //wireless wireless
    TSS_EM = 5,
    TSS_DL = 6,
    TSS_BT = 7,
    TSS_UNKNOWN = 8
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private struct Comport
{
    [MarshalAs(UnmanagedType.LPStr, SizeConst = 64)]
    public string Port;
    [MarshalAs(UnmanagedType.LPStr, SizeConst = 256)]
    public string FriendlyName;
    public TSS_Type Type;
}

DllImport

[DllImport("ThreeSpace_API.dll")]
private static extern int getFirstAvailableTSSComPort([Out, MarshalAs(UnmanagedType.Struct)] out Comport port, int filter);

调用

Comport port;
var error = getFirstAvailableTSSComPort(out port, 0);

我得到了

  

调用PInvoke函数   'YEi3!YEi3.Program :: getFirstAvailableTSSComPort'失衡了   堆。这可能是因为托管的PInvoke签名没有   匹配非托管目标签名。检查是否正在通话   PInvoke签名的约定和参数与目标匹配   非托管签名。

1 个答案:

答案 0 :(得分:3)

C代码使用cdecl调用约定,但您的C#代码使用stdcall。这就是您收到p / invoke堆栈不平衡消息的原因。

更改DllImport以指定调用约定:

[DllImport("ThreeSpace_API.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int getFirstAvailableTSSComPort(
    out Comport port, 
    int filter
);

请注意,参数的默认编组已足够。

此更改将解决堆栈不平衡问题,但您的代码仍然无法正常工作。那是因为结构被错误地翻译了。内联字符串需要编组为ByValTStr

[StructLayoutAttribute(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct ComPort {
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst=64)]
    public string com_port;
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst=256)]
    public string friendly_name;
    public TSS_Type sensor_type;
}