7

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
    I think you need another tag because String^ doesn't make much sense in C++. Commented Dec 5, 2012 at 7:21
  • This is managed c++ syntax. And your function isn't even valid, there is no identifier. Commented Dec 5, 2012 at 7:24
  • The problem is that this function is used to convert a value from C++ to C#/ I mean this function is called by C# program Commented Dec 5, 2012 at 7:24
  • @juanchopanza it also exists in WinRT, and probably should call .c_str(); on the std::string Commented Dec 5, 2012 at 7:24
  • @JoachimPileborg well, I'm sure there's a tag for that! Commented Dec 5, 2012 at 7:24

3 Answers 3

15

From MSDN:

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

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

http://msdn.microsoft.com/en-us/library/ms235219.aspx

Sign up to request clarification or add additional context in comments.

Comments

11

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.

1 Comment

This no longer compiles.
2

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 https://bytes.com/topic/c-sharp/answers/725734-utf-8-std-string-system-string 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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.