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



我试图弄清楚如何将字符串值从 C++/CLI 方法返回到调用它的非托管C++。 在我当前的实现中,我有一个字符串存储在(托管的(C++/CLI 方法中的本地 String ^ 变量中,我喜欢该方法返回到调用它的非托管C++程序。 如果使用 String ^ 变量不是一个好的选择,那么什么构造/类型 w/be 更好? 请注意,我省略了 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);
}

任何帮助将不胜感激。 提前谢谢。

您不能将String ^返回到 c++,因为它无法识别它。不过,使用互操作服务进行了一些转换。来自微软

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));
}

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


托管C++文件摘录:

#include <msclrmarshal_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

功劳归于tragomaskhalos和Juozas Kontvainis的答案/编辑,这是一个堆栈溢出问题,询问如何将System::String^转换为std::string。

最新更新