C ++ / CLI字符串转换

问题描述

| 我发现这段非常不错的代码字符串转换
System:String^
,如下所示:
System::String^ rtn = gcnew String(move.c_str());  // \'move\' here is the string
我正在将rtn传递回C#程序。无论如何,在存在该代码函数中,我传入了
System::String^
。我还找到了一些代码,可以使用以下代码将“ 0”转换为字符串:
pin_ptr<const wchar_t> wch = PtrToStringChars(cmd);  // \'cmd\' here is the System:String          
size_t convertedChars = 0;
size_t  sizeInBytes = ((cmd->Length + 1) * 2);
errno_t err = 0;
char *ch = (char *)malloc(sizeInBytes);

err = wcstombs_s(&convertedChars,ch,sizeInBytes,wch,sizeInBytes);
现在,我可以使用\'ch \'作为字符串。 但是,与使用ѭ5进行另一种转换相比,这似乎要花费更多的工作。所以,最后我的问题是,是否有某种东西可以像使用gcnew一样将
System::String^
转换为字符串?     

解决方法

        使用VC ++的封送处理库:C ++中的封送处理概述
#include <msclr/marshal_cppstd.h>

// given System::String^ mstr
std::string nstr = msclr::interop::marshal_as<std::string>(mstr);
    ,        这可能是有用的:
wchar_t *str = \"Hi StackOverflow\"; //native
String^ mstr= Marshal::PtrToStringAnsi((IntPtr)str); // native to safe managed
wchar_t* A=( wchar_t* )Marshal::StringToHGlobalAnsi(mstr).ToPointer(); // return back to native 
别忘了
using namespace System::Runtime::InteropServices;