0

I am having problem with converting managed System::String to std::string in C++/CLI. This code does not work, I can't understand why:

string SolvingUnitWrapper::getName(String ^name)
{
    pin_ptr<const wchar_t> wstr = PtrToStringChars(name);
    ostringstream oss;
    oss << wstr; 
    return oss.str();
}

Thanks

1
  • 1
    A System::String is a counted sequence of UTF-16 code units. That is, the character set is Unicode and the encoding is UTF-16. std::string is a counted sequence of char-sized values, without any specific character set or encoding. Before doing anything, you have to decide what target character set and encoding to use. (The thread's default ANSI code page is one option. But, sticking with Unicode and using UTF-8 is increasingly common—that's what System::IO::StreamWriter does.) What's your choice? Commented Jul 22, 2013 at 16:51

1 Answer 1

5

try this:

std::string managedStrToNative(System::String^ sysstr)
{
  using System::IntPtr;
  using System::Runtime::InteropServices::Marshal;

  IntPtr ip = Marshal::StringToHGlobalAnsi(sysstr);
  std::string outString = static_cast<const char*>(ip.ToPointer());
  Marshal::FreeHGlobal(ip);
  return outString;  
}
Sign up to request clarification or add additional context in comments.

3 Comments

That is the same as in MSDN for visual studio 2005. I think the marshall_as is the new method I should use for visual studio 2012.
@user2381422 this is what i use in vs2010. in vs2012 you can definitely use marshall_as just go over this overview (msdn.microsoft.com/en-us/library/bb384865.aspx)
See also support.microsoft.com/kb/311259/en-us (How to convert from System::String* to Char* in Visual C++).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.