Convert a String^ to wstring C++

僤鯓⒐⒋嵵緔 提交于 2019-11-29 08:07:30

It should be as simple as:

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>

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

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.

I flagged this as a duplicate, but here's the answer on how to get from System.String^ to a std::string.

String^ test = L"I am a .Net string of type System::String";
IntPtr ptrToNativeString = Marshal::StringToHGlobalAnsi(test);
char* nativeString = static_cast<char*>(ptrToNativeString.ToPointer());

The trick is make sure you use Interop and marshalling, because you have to cross the boundary from managed code to non-managed code.

My version is:

Platform::String^ str = L"my text";

std::wstring wstring = str->Data();

With Visual Studio 2015, just do this:

String^ s = "Bonjour!";

C++/CLI

#include <vcclr.h>
pin_ptr<const wchar_t> ptr = PtrToStringChars(s);

C++/CX

const wchart_t* ptr = s->Data();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!