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!
Code: #include <string> #include <algorithm> //... std::string str = "Hello"; std::wstring str2(str. length(), L' '); // Make room for characters // Copy string to wstring.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With