【问题标题】:Why do I get PInvoceStackImbalance when I try to execute umanaged code当我尝试执行托管代码时,为什么会出现 PInvokeStackImbalance
【发布时间】:2019-07-07 12:30:29
【问题描述】:

我从 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" : "调用 PInvoke 函数 'IO-Link Device Interface!IO_Link_Device_Interface.IOLUSBIF20Wrapper::IOL_SetTransparentModeExt' 使堆栈不平衡。这可能是因为托管 PInvoke 签名与非托管目标签名不匹配。检查PInvoke 签名的调用约定和参数与目标非托管签名匹配。"

在 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 */
    }

【问题讨论】:

    标签: c# dll struct stack unmanaged


    【解决方案1】:

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

    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 */
    

    【讨论】:

    • 您好,感谢您的快速回答!我还必须在我的方法参数中将“长句柄”切换为“uint 句柄”。我猜是因为 c 中的 long 是 32 位数据类型,而在 c# 中它是 64 位
    • 是的,我不再看到您的部分答案,但请记住,您的程序集应该使用正确的字节序进行编译,因为您可能对 32 位和 62 位有不同的 pinvoke 签名。重新考虑 long 的大小,看看这个 answer 可能会有所帮助。
    猜你喜欢
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 2016-04-08
    相关资源
    最近更新 更多