【问题标题】:DLLImport C++ To .NET - char* (Pointer to string)DLLImport C++ To .NET - char*(指向字符串的指针)
【发布时间】:2019-11-22 15:29:14
【问题描述】:

我正在使用 .NET (C#) 中使用 c++ 构建的 dll。 我遇到了指向字符串 (char*) 的指针的问题

这是 C++ 中的函数声明

EXPORT char* Read_Signal(char *Name)
{
     char* Info = (char*)malloc(50 * sizeof(char));
     //more code
     return Info;
}

我以这些方式尝试了 DLLImport。

[DllImport("Com.dll", CallingConvertion = CallingConvertion.Cdecl)]
public static extern StringBuilder Read_Signal(StringBuilder Name);  => Not Working (crash)


[DllImport("Com.dll", CallingConvertion = CallingConvertion.Cdecl)]
public static extern string Read_Signal(string Name);  => Not Working (crash), I am not able to see the fail because no exception or message is shown, the application simply crashes. 


[DllImport("Com.dll", CallingConvertion = CallingConvertion.Cdecl)]
public static extern long Read_Signal(StreamBuilder Name);  => Works but the return long var is not useful (with int, char the call works but the response is obviously not useful).

关于在返回值 char* 中正确转换的任何想法?

提前致谢。 问候。

【问题讨论】:

  • 更好的方法是让 C# 代码创建缓冲区,而您的函数所做的就是填充缓冲区。然后内存分配从 C++ 代码转移到 C# 客户端。那么返回码不必是char *,但可能是 TRUE 或 FALSE 或某个值。
  • 谢谢保罗。这是我一直在做的方式,但不幸的是,我无法访问 C++ 中的代码来以适当的方式修改 DLL。我尝试了很多转换,因为在 LabVIEW 中导入这个 DLL 效果很好。伤心:(

标签: c++ casting char


【解决方案1】:

Paul 是正确的 - 构造 C->C# 字符串返回的常用方法是使用 StringBuilder 或其他类型的缓冲区。我用来通过 hwnd 拉取窗口标题的这个小 sn-p 可以方便地用作如何构建 C API 和 C# 包装器的示例:

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int GetWindowTextLength(IntPtr hwnd);

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern long GetWindowText(IntPtr hwnd, StringBuilder lpString, long cch);

public static string GetWindowCaption(IntPtr hwnd) {
    var len = GetWindowTextLength(hwnd);
    var sb = new StringBuilder(len + 1); // (count for \0 terminator)
    GetWindowText(hwnd, sb, len + 1);
    return sb.ToString();
}

【讨论】:

    猜你喜欢
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 2020-09-28
    • 2021-11-26
    • 2019-01-15
    • 1970-01-01
    相关资源
    最近更新 更多