Convert a String^ to wstring C++

2019-01-26 00:22发布

问题:

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!

回答1:

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.



回答2:

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.



回答3:

My version is:

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

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


回答4:

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