【问题标题】:.Net c# marshalling of char *.Net c# char 编组 *
【发布时间】:2012-09-07 17:14:26
【问题描述】:

我正在尝试使用 System.Runtime.InteropServices 从 C# 应用程序调用现有的 C dll,但在匹配 PInvoke 函数和 Target 函数之间的签名时遇到了困难。

目标函数是

__declspec(dllexport) DWORD GetSomeString(char* strOut);

我的 PInvoke 函数是

[DllImport("Existing.dll")]
public static extern uint GetSomeString([MarshalAs(UnmanagedType.LPWStr)]
                            string strDisplay);

我调用函数

string tempStr = "My Output String";
uint retVal = GetSomeString(tempStr);

但我收到了消息

托管调试助手“PInvokeStackImbalance”检测到问题... ...对 PInvoke 函数“GetSomeString”的调用使堆栈不平衡。这可能是因为托管 PInvoke 签名与非托管目标签名不匹配。检查 PInvoke 签名的调用约定和参数是否与目标非托管签名匹配。

我也尝试过将 PInvoke 函数实现为

[DllImport("Existing.dll")]
public static extern uint GetSomeString([MarshalAs(UnmanagedType.LPWStr)]
                            StringBuilder strDisplay);

但无济于事。

有没有人知道我做错了什么?

如果需要更多信息或我的问题不清楚,请告诉我。

提前致谢。

【问题讨论】:

    标签: c# marshalling cstring


    【解决方案1】:

    您需要指定calling convention。默认情况下,PInvoke 使用StdCall,但您的方法(可能)是Cdecl

    [DllImport("Existing.dll", CallingConvention=CallingConvention.Cdecl)]
    

    【讨论】:

      【解决方案2】:

      除了 Reed Copsey 提到的错误调用约定之外,char* 的匹配类型是 UnmanagedType.LPStr

      【讨论】:

        猜你喜欢
        • 2011-04-29
        • 2013-09-13
        • 2021-08-20
        • 1970-01-01
        • 2017-10-30
        • 1970-01-01
        • 1970-01-01
        • 2016-03-11
        • 1970-01-01
        相关资源
        最近更新 更多