Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/CX : Convert std::string to Platform::String^

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)

like image 994
ashtrail Avatar asked Oct 20 '25 08:10

ashtrail


2 Answers

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));
}
like image 136
Heefan Avatar answered Oct 21 '25 23:10

Heefan


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.

like image 25
apnorton Avatar answered Oct 21 '25 23:10

apnorton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!