C# 当我试图执行代码时,为什么会出现PinVocestackDistancert

C# 当我试图执行代码时,为什么会出现PinVocestackDistancert,c#,dll,struct,stack,unmanaged,C#,Dll,Struct,Stack,Unmanaged,我正在从C#中的非托管dll调用函数。我对这个dll的一个调用正在运行。但另一个有更高级的参数,当我在C#代码中执行FunkAction时: 我得到以下错误: “Pinvokestack不平衡”:“调用PInvoke函数‘IO链接设备接口’!IO_Link_Device_Interface.IOLUSBI20Wrapper::IOL_SetTransparentModeExt'使堆栈不平衡。这可能是因为托管PInvoke签名与非托管目标签名不匹配。检查PInvoke签名的调用约定和参数是否与目标

我正在从C#中的非托管dll调用函数。我对这个dll的一个调用正在运行。但另一个有更高级的参数,当我在C#代码中执行FunkAction时:

我得到以下错误:

“Pinvokestack不平衡”:“调用PInvoke函数‘IO链接设备接口’!IO_Link_Device_Interface.IOLUSBI20Wrapper::IOL_SetTransparentModeExt'使堆栈不平衡。这可能是因为托管PInvoke签名与非托管目标签名不匹配。检查PInvoke签名的调用约定和参数是否与目标非托管签名匹配。“

在标题中,函数(和结构)的签名定义如下:

LONG __stdcall IOL_SetTransparentModeExt(LONG Handle, DWORD Port, TTransparentParameters * pTransparentParameters);


typedef struct TTransparentParametersStruct
{
  BYTE StartPattern[16];    /**< starting pattern */
  BYTE ReturnPattern[32];   /**< returning pattern */
} TTransparentParameters;
LONG\uu stdcall IOL\u SetTransparentModeExt(长句柄、DWORD端口、tttransparentparameters*pttransparentparameters);
typedef结构TTTransparentParametersStruct
{
字节起始模式[16];/**<起始模式*/
字节返回模式[32];/**<返回模式*/
}t透明度参数;
我作为参数传递的结构如下所示:

[StructLayout(LayoutKind.Sequential)]
    public struct TTransparentParameters
    {
        public Byte[] StartPattern;    /**< starting pattern */
        public Byte[] ReturnPattern;   /**< returning pattern */
    }
[StructLayout(LayoutKind.Sequential)]
公共结构TTTransparentParameters
{
公共字节[]起始模式;/**<起始模式*/
公共字节[]返回模式;/**<返回模式*/
}

堆栈不平衡,因为非托管数据结构由

BYTE StartPattern[16];    /**< starting pattern */
BYTE ReturnPattern[32];   /**< returning pattern */
字节起始模式[16];/**<起始模式*/
字节返回模式[32];/**<返回模式*/
占用48字节,而这些字段的托管解释的大小不正确。如果指定封送拆收器的大小,则堆栈应平衡:

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public Byte[] StartPattern;    /**< starting pattern */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public Byte[] ReturnPattern;   /**< returning pattern */
[Marshallas(UnmanagedType.ByValArray,SizeConst=16)]
公共字节[]起始模式;/**<起始模式*/
[Marshallas(UnmanagedType.ByValArray,SizeConst=32)]
公共字节[]返回模式;/**<返回模式*/

您好,谢谢您的快速回答!我还必须将“长手柄”切换到“uint手柄”“在我的方法参数中。我想,因为c中的long是32位数据类型,而c中的long是64位是的,我不再看到您的答案的一部分,但请记住,您的程序集应该使用正确的endianess进行编译,因为32位和62位可能有不同的pinvoke签名。重新计算一条龙的大小,看看这条可能会有帮助。
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public Byte[] StartPattern;    /**< starting pattern */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public Byte[] ReturnPattern;   /**< returning pattern */