如何将字符串从C ++ / CLI方法返回到调用它的非托管C ++中

问题描述 投票:0回答:2

我试图弄清楚如何从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# c++ unmanaged managed bridge
2个回答
0
投票

您无法将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));
}

0
投票

我最终在托管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/edittragomaskhalos转到Juozas Kontvainis到一个堆栈溢出问题,询问如何将System :: String ^转换为std :: string。

© www.soinside.com 2019 - 2024. All rights reserved.