C++/CLI字符串转换
我发现这非常好的一段代码,将一个字符串转换System:String^
如:C++/CLI字符串转换
System::String^ rtn = gcnew String(move.c_str()); // 'move' here is the string
我传递RTN回C#程序。无论如何,在这个代码存在的函数中,我传入一个System::String^
。我也发现了一些代码到System:String^
转换为字符串使用下面的代码:
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);
现在我可以用“频道”作为一个字符串。
然而,这似乎比使用gcnew
转换其他方式更多的工作。所以,最后我的问题是,有没有什么东西可以用gcnew的方式将System::String^
转换为字符串?
使用VC++的编组库:Overview of Marshaling in C++
#include <msclr/marshal_cppstd.h>
// given System::String^ mstr
std::string nstr = msclr::interop::marshal_as<std::string>(mstr);
圣洁的废话,多数民众赞成在甜。谢谢我给它一个。 – David 2011-05-30 18:17:31
工程就像一个魅力。非常感谢。 – David 2011-05-30 18:30:30
如何清理。根据链接“Marshaling仅在从托管数据类型到本地数据类型进行编组时才需要上下文,而要转换为的本机类型不具有自动清理的析构函数。” 说这个方法是从本地代码调用的,它会被清理吗? std :: string getItem(){ String^result =“Some val”; result + =“。”; return msclr :: interop :: marshal_as <:string>(result); } – harsha 2013-10-01 11:15:38
这可能是有用的:
wchar_t *str = "Hi *"; //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;
由于此方法分配字符串所需的非托管内存,因此请始终通过调用FreeHGlobal释放内存。 – 2011-06-09 15:56:47
他们让你做更多的工作,以故意做一些讨厌这样的。至少必须转换为utf8,UTF8Encoding :: GetBytes()。 – 2011-05-30 18:28:44