【问题标题】:Marshalling my C++ .dll in C# with "const char*" and "const int"在 C# 中使用“const char*”和“const int”编组我的 C++ .dll
【发布时间】:2016-05-26 10:35:20
【问题描述】:

使用 C++:

extern "C" MY_API int connect(const char* pcHost,const int nPort, ConnectionId_T *pConId);

存在:

  • pcHost一个IP
  • nPort一个端口
  • pConId 一个常数 (-1)

我的尝试是:

[DllImport("my.dll", CharSet = CharSet.Ansi)]
public static extern int connect(StringBuilder pcHost, int nPort, ConnectionId_T pConId);

但是当我尝试连接时:

StringBuilder ip = new System.Text.StringBuilder();
ip.Append("1.1.1.1");
int nPort = 1111;
ConnectionId_T nConId = MY_NCONID // This is defined previously as -1 (public const int MY_NCONID = -1)
connect(ip, nPort, nConId))

我在 connect 行收到 AccesViolationException。我的元帅错了吗?

PS:ConectionId_T 定义为using ConnectionId_T = System.Int32;

提前致谢。

【问题讨论】:

  • @codroipo 我也试过[MarshalAs(UnmanagedType.LPStr)],我得到了同样的错误。
  • 您还必须将属性添加到您的方法定义[DllImport("yourdll.dll", CharSet = CharSet.Ansi)]
  • @MujahidDaudKhan 这已包含在原始帖子中。

标签: c# c++ marshalling


【解决方案1】:
PS: ConectionId_T is defined as using ConnectionId_T = System.Int32;

基于此,如果我假设 ConnectionId_T 在 C++ 世界中只不过是 int,那么您需要将函数导入更改为:

[DllImport("my.dll", CharSet = CharSet.Ansi)]
public static extern int connect(StringBuilder pcHost, int nPort, IntPtr pConId);

或如:

[DllImport("my.dll", CharSet = CharSet.Ansi)]
public static extern int connect(StringBuilder pcHost, int nPort, ref int pConId);

【讨论】:

    【解决方案2】:
    [DllImport("my.dll", CharSet = CharSet.Ansi,CallingConvention=CallingConvention.Cdecl)]
    public static extern int connect(IntPtr pcHost, int nPort, ref ConnectionId_T pConId);
    

    并使用Intptr pcHost = Marshal.StringToHGlobalAnsi(pcHostString))

    【讨论】:

    • pConId 原来是int,为什么要改成int
    • 有什么不同吗?
    • 如何将 IP 字符串转换为 IntPtr 以便使其工作?
    • 通过上述方法调用Marshal.StringToHGlobalAnsi(string s)
    • 它通过在pConId 之前添加out 起作用,因为.dll 返回该变量的值。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2021-06-21
    • 2017-08-09
    • 2022-08-11
    • 2012-04-19
    • 1970-01-01
    相关资源
    最近更新 更多