Convert a String^ to wstring C++

Kipcak08 picture Kipcak08 · Dec 27, 2012 · Viewed 9.7k times · Source

I programmed a little Application in C++. There is a ListBox in the UI. And I want to use the selected Item of ListBox for an Algorithm where I can use only wstrings.

All in all I have two questions: -how can I convert my

    String^ curItem = listBox2->SelectedItem->ToString();

to a wstring test?

-What means the ^ in the code?

Thanks a lot!

Answer

Ben Voigt picture Ben Voigt · Dec 27, 2012

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.