Is there a simple way (one line of code would be cool) to convert à std::string to a Platform::String^ in C++/CX ?
I found how to do it the other way(String^ to string) but nothing for this one.
Something like :
std::string str = "Hello World";
Platform::String^ p_str = convertFromString(str);
(In the example it's pointless but when you were working with std::string in c++ and you want to send it to some C# code it makes more sense)
The method works for me
Platform::String ^ convertFromString(const std::string & input)
{
std::wstring w_str = std::wstring(input.begin(), input.end());
const wchar_t* w_chars = w_str.c_str();
return (ref new Platform::String(w_chars));
}
There is no direct std::string
to std::wstring
conversion currently possible.
However, we can do a roundabout conversion from std::string
to std::wstring
, then from std::wstring
to Platform::String
as follows:
#include <locale>
#include <codecvt>
#include <string>
Platform::String^ stringToPlatformString(std::string inputString) {
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
std::wstring intermediateForm = converter.from_bytes(inputString);
Platform::String^ retVal = ref new Platform::String(intermediateForm.c_str());
return retVal;
}
See this question for more information on std::string
to std::wstring
conversion.
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