Reputation: 93
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)
Upvotes: 4
Views: 7139
Reputation: 11
If you in the conversion does not like to be limited to Basic Latin (Unicode block), like in my case the need for æøå, this works:
#include <sstream>
Platform::String^ StdStringToPlatformString(std::string str)
{
std::wstringstream wss;
wss << str.c_str();
return ref new Platform::String(wss.str().c_str());
}
Upvotes: 1
Reputation: 395
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));
}
Upvotes: 3
Reputation: 2440
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.
Upvotes: 2
Reputation: 93
So basically the answer is no : it's more complicated. You need to first convert the std::string in std::wstring and then use user1's answer (convert std::wstring to Platform::String^). For the string to wstring conversion you can check this other question (which doesn't work for me but whatever, I'll just have to go for a more in depth conversion).
(I had put some code but was told it was terrible to do it like this, since I just do it for debugging and wil delete it anyway I don't care but I don't want to give anti-advice so I deleted that code)
Upvotes: 0