DLLImport C++;到.NET-char*(指向字符串的指针) 我使用了.NET中的C++构建的DLL(C语言)。 我面临一个指向字符串(char*)的指针问题

DLLImport C++;到.NET-char*(指向字符串的指针) 我使用了.NET中的C++构建的DLL(C语言)。 我面临一个指向字符串(char*)的指针问题,c++,casting,char,C++,Casting,Char,这是C中的函数声明++ EXPORT char* Read_Signal(char *Name) { char* Info = (char*)malloc(50 * sizeof(char)); //more code return Info; } 我用这些方法尝试了德林波特 [DllImport("Com.dll", CallingConvertion = CallingConvertion.Cdecl)] public static extern String

这是C中的函数声明++

EXPORT char* Read_Signal(char *Name)
{
     char* Info = (char*)malloc(50 * sizeof(char));
     //more code
     return Info;
}
我用这些方法尝试了德林波特

[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*中的正确强制转换有什么想法吗

提前谢谢。
注意。

Paul是正确的-构造C->C#字符串返回的常用方法是使用StringBuilder或其他类型的缓冲区。我用这个小片段通过hwnd方便地提取窗口标题,作为如何构造C API和C#wrapper的示例:


更好的方法是让C#代码创建缓冲区,而函数所做的就是填充缓冲区。然后,内存分配从C++代码转移到C客户端。那么返回的代码不必是字符*,而可以是真或假或某些值。谢谢Paul。这是我一直在做的方式,但不幸的是,我无法访问C++中的代码来以适当的方式修改DLL。我已经尝试了很多转换,因为在LabVIEW中导入这个DLL非常有效。悲哀的:(
[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();
}