我有一个 C++ dll,它有一个返回 C 字符串的函数,并且我有一个 C# 程序,它调用该函数并将数据返回到 C# 字符串。这就是我的意思
__declspec(dllexport) const char* function (const char* str) {
std::string stdString( str );
std::cout << stdString.c_str() << std::endl; // this prints fine, no data loss
return stdString.c_str();
}
这是 C# 代码
[DllImport("MyDLL.dll")]
public static extern string function(string data);
string blah = function("blah");
Console.WriteLine(blah); // doesn't print anything...
当我查看本地人时,它说变量“blah”等于“”。
数据发生了什么?
最佳答案
您的 C++ 代码已损坏。您正在返回一个指向局部变量的指针。函数返回后它就不再存在。这在 C++ 程序中往往会偶然发生,但却是很强的未定义行为。它不可能在互操作场景中工作,pinvoke 编码(marshal)拆收器对堆栈的使用将覆盖字符串。
可行的声明:
void function (const char* str, char* output, size_t outputLength)
在 [DllImport] 声明中使用 StringBuilder 作为输出参数,并传递一个具有足够容量的初始化字符串。
关于c# - 将 C 字符串返回到 C# 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8409499/