将 C 字符串返回到 C# 程序
我有一个 C++ dll,它有一个返回 ac 字符串的函数,我有一个 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”等于“”。
数据怎么了?
I have a C++ dll that has a function that returns a c string and I have a C# program that calls this function and returns the data to a C# string. Here's what I mean
__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();
}
And here's the C# code
[DllImport("MyDLL.dll")]
public static extern string function(string data);
string blah = function("blah");
Console.WriteLine(blah); // doesn't print anything...
When I look into the locals it says variable 'blah' is equal to "".
What happened to the data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 C++ 代码已损坏。您正在返回一个指向局部变量的指针。函数返回后它就不再存在。这在 C++ 程序中往往会偶然发生,但却是很强的未定义行为。它不可能在互操作场景中工作,pinvoke 封送拆收器对堆栈的使用将覆盖字符串。
一种可行的声明:
在 [DllImport] 声明中为 output 参数使用 StringBuilder,并传递一个具有足够容量的初始化字符串。
Your C++ code is broken. You are returning a pointer to a local variable. It no longer exists after the function returns. This tends to work by accident in a C++ program but is strong Undefined Behavior. It cannot possibly work in an interop scenario, the pinvoke marshaler's use of the stack will overwrite the string.
A declaration that could work:
Use a StringBuilder in the [DllImport] declaration for the output argument and pass an initialized one with sufficient Capacity.