Convert from Std: :String to String^

Convert from Std: :String to String^

I have a function in C++ that have a value in std::string type and would like to convert it to String^.

void(String ^outValue)
{
   std::string str("Hello World");
   outValue = str;
}
9

3 Answers

Googling reveals marshal_as (untested):

// marshal_as_test.cpp
// compile with: /clr
#include <stdlib.h>
#include <string>
#include <msclr\marshal_cppstd.h>

using namespace System;
using namespace msclr::interop;

int main() {
   std::string message = "Test String to Marshal";
   String^ result;
   result = marshal_as<String^>( message );
   return 0;
}

Also see Overview of Marshaling.

0

From MSDN:

#include <string>
#include <iostream>
using namespace System;
using namespace std;

int main() {
   string str = "test";
   String^ newSystemString = gcnew String(str.c_str());
}

As far as I got it, at least the marshal_as approach (not sure about gcnew String) will lead to non ASCII UTF-8 characters in the std::string to be broken.

Based on what I've found on I've build this solution which seems to work for me at least with German diacritics:

System::String^ StdStringToUTF16(std::string s)
{

 cli::array<System::Byte>^ a = gcnew cli::array<System::Byte>(s.length());
 int i = s.length();
 while (i-- > 0)
 {
    a[i] = s[i];
 }

 return System::Text::Encoding::UTF8->GetString(a);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.