当我尝试执行非托管代码时,为什么会出现 PInvokeStackImbalance

Why do I get PInvoceStackImbalance when I try to execute umanaged code

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

[DllImport("IOLUSBIF20.dll", CallingConvention = CallingConvention.StdCall)]
public static extern long IOL_SetTransparentModeExt(long Handle, UInt32 Port, ref TTransparentParameters pTransparentParameters);

我收到以下错误:

"PInvokeStackImbalance" : "A call to PInvoke function 'IO-Link Device Interface!IO_Link_Device_Interface.IOLUSBIF20Wrapper::IOL_SetTransparentModeExt' 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."

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

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


typedef struct TTransparentParametersStruct
{
  BYTE StartPattern[16];    /**< starting pattern */
  BYTE ReturnPattern[32];   /**< returning pattern */
} TTransparentParameters;

我作为参数传递的结构如下所示:

[StructLayout(LayoutKind.Sequential)]
    public struct TTransparentParameters
    {
        public Byte[] StartPattern;    /**< starting pattern */
        public Byte[] ReturnPattern;   /**< returning pattern */
    }

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

组成
BYTE StartPattern[16];    /**< starting pattern */
BYTE ReturnPattern[32];   /**< returning pattern */

占用 48 个字节,而您对这些字段的托管解释大小错误。如果您指定封送拆收器的大小,您的堆栈应该是平衡的:

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public Byte[] StartPattern;    /**< starting pattern */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public Byte[] ReturnPattern;   /**< returning pattern */