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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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