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

发布于 2024-12-19 22:12:16 字数 602 浏览 1 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天冷不及心凉 2024-12-26 22:12:16

您的 C++ 代码已损坏。您正在返回一个指向局部变量的指针。函数返回后它就不再存在。这在 C++ 程序中往往会偶然发生,但却是很强的未定义行为。它不可能在互操作场景中工作,pinvoke 封送拆收器对堆栈的使用将覆盖字符串。

一种可行的声明:

 void function (const char* str, char* output, size_t outputLength)

在 [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:

 void function (const char* str, char* output, size_t outputLength)

Use a StringBuilder in the [DllImport] declaration for the output argument and pass an initialized one with sufficient Capacity.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文