【发布时间】: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 效果很好。伤心:(