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

makc
  • 2,569
  • 1
  • 18
  • 28
user2381422
  • 5,645
  • 14
  • 42
  • 56
  • 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? – Tom Blodget Jul 22 '13 at 16:51

1 Answers1

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;  
}
makc
  • 2,569
  • 1
  • 18
  • 28
  • 1
    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 Jul 22 '13 at 14:19
  • 1
    @user2381422 this is what i use in vs2010. in vs2012 you can definitely use marshall_as just go over this overview (http://msdn.microsoft.com/en-us/library/bb384865.aspx) – makc Jul 22 '13 at 14:24
  • 1
    See also http://support.microsoft.com/kb/311259/en-us (How to convert from System::String* to Char* in Visual C++). – Oberon Jul 22 '13 at 14:53