Converting managed System::String to std::string i

2019-09-05 06:58发布

问题:

This question already has an answer here:

  • C++/CLI Converting from System::String^ to std::string 10 answers

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:

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;  
}


标签: c++ c++-cli