【问题标题】:How can I return a string from a C++/CLI method back to unmanaged C++ that calls it如何将 C++/CLI 方法中的字符串返回给调用它的非托管 C++
【发布时间】:2020-03-21 06:05:39
【问题描述】:

我试图弄清楚如何将字符串值从 C++/CLI 方法返回给调用它的非托管 C++。在我当前的实现中,我有一个字符串存储在(托管)C++/CLI 方法中的本地 String ^ 变量中,我希望该方法返回给调用它的非托管 C++ 程序。如果使用 String ^ 变量不是一个好的选择,那么哪种构造/类型会更好?请注意,我省略了 C# 方法将字符串值返回给 C++/CLI 方法的部分,因为这不是问题。

我正在使用 VS2017。

代码示例 - 为简单起见,代码已减少。

非托管 C++ ------------------

_declspec(dllexport) void GetMyString();

int main()
{
    GetMyString();
}

(托管)C++/CLI -------------------------

__declspec(dllexport) String GetMyString()
{
    String ^ sValue = "Return this string";
    return (sValue);
}

非常感谢任何帮助。提前谢谢。

【问题讨论】:

  • 我认为你不能在非托管 c++ 中使用String^。使用std::stringstd::wstring。可能您必须在 c++/cli 中将 String^ 转换为标准字符串。

标签: c# c++ unmanaged managed bridge


【解决方案1】:

我最终在托管 C++ 方法中将 System::String^ 转换为 std::string,然后将后者返回给非托管 C++ 调用者。


托管 C++ 文件摘录:

#include <msclr\marshal_cppstd.h>

__declspec(dllexport) std::string MyManagedCppFn()
{
    System::String^ managed = "test";
    std::string unmanaged2 = msclr::interop::marshal_as<std::string>(managed);
    return unmanaged2;
}

非托管 C++ 文件摘录:

_declspec(dllexport) std::string MyMangedCppFn();

std::string jjj = MyMangedCppFn();    // call Managed C++ fn

归功于answer/edittragomaskhalosJuozas Kontvainis 到一个stackoverflow 问题,询问如何将System::String^ 转换为std::string。

【讨论】:

    【解决方案2】:

    您不能将String ^ 返回给 c++,因为它不会识别它。虽然有一些使用 InteropServices 的转换。来自microsoft

    using namespace System;
    
    void MarshalString ( String ^ s, std::string& os ) {
       using namespace Runtime::InteropServices;
       const char* chars =
          (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
       os = chars;
       Marshal::FreeHGlobal(IntPtr((void*)chars));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 2018-03-08
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多