Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a String^ to wstring C++

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!

like image 466
Kipcak08 Avatar asked Dec 26 '12 23:12

Kipcak08


People also ask

How do you store string in Wstring?

Code: #include <string> #include <algorithm> //... std::string str = "Hello"; std::wstring str2(str. length(), L' '); // Make room for characters // Copy string to wstring.

How do I convert Wstring to Wchar?

There is no way to convert wstring to wchar_t* but you can convert it to const wchar_t* which is what answer by K. Kirsz says. This is by design because you can access a const pointer but you shouldn't manipulate the pointer. See a related question and its answers.

How do you convert Wstring to Lpcwstr?

This LPCWSTR is Microsoft defined. So to use them we have to include Windows. h header file into our program. To convert std::wstring to wide character array type string, we can use the function called c_str() to make it C like string and point to wide character string.


1 Answers

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.

like image 128
Ben Voigt Avatar answered Sep 21 '22 13:09

Ben Voigt