且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将String ^转换为wstring C ++

更新时间:2023-11-11 23:24:04

它应该像这样简单:

std::wstring result = msclr::interop::marshal_as<std::wstring>(curItem);

您还需要头文件来完成该工作:

You'll also need header files to make that work:

#include <msclr\marshal.h>
#include <msclr\marshal_cppstd.h>






这是什么 marshal_as 专业化看起来像是内部,出于好奇:


What this marshal_as specialization looks like inside, for the curious:

#include <vcclr.h>
pin_ptr<WCHAR> content = PtrToStringChars(curItem);
std::wstring result(content, curItem->Length);

之所以有效,是因为 System :: String 是内部存储为宽字符。如果您想使用 std :: string ,则必须执行Unicode转换,例如 WideCharToMultiByte 。方便地, marshal_as 会为您处理所有详细信息。

This works because System::String is stored as wide characters internally. If you wanted a std::string, you'd have to perform Unicode conversion with e.g. WideCharToMultiByte. Convenient that marshal_as handles all the details for you.