c# - 将 C 字符串返回到 C# 程序

标签 c# c++ string dll export

我有一个 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/

相关文章:

c# - nhibernate 引号字符替换为\"

c# - 发送到远程 MSMQ 静默失败

c++ - 在 C++ 中为包含对象数组的对象数组释放内存的正确方法

javascript - 如何在 JavaScript 中替换特定索引处的字符?

c# - 如何在 C++ 运行时组件内的 Windows Phone 8.1 XAML 应用程序中使用 C++ dll

c# - 反转数组数组

c++ - 段错误多线程 C++ 11

c++ - 以四种格式打印日期

python - 使用 str.contains 将字符串的一部分替换为分隔符

c# - 如何获得定号之间的字符串中间部分?