【问题标题】:Converting managed System::String to std::string in C++/CLI [duplicate]在 C++/CLI 中将托管 System::String 转换为 std::string [重复]
【发布时间】:2013-08-18 13:56:59
【问题描述】:

在 C++/CLI 中将托管 System::String 转换为 std::string 时遇到问题。 这段代码不起作用,我不明白为什么:

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

谢谢

【问题讨论】:

  • A System::String 是 UTF-16 代码单元的计数序列。即字符集为Unicode,编码为UTF-16。 std::string 是 char 大小的值的计数序列,没有任何特定的字符集或编码。在做任何事情之前,您必须决定使用什么目标字符集和编码。 (线程的默认 ANSI 代码页是一种选择。但是,坚持使用 Unicode 并使用 UTF-8 越来越普遍——这就是 System::IO::StreamWriter 所做的。)你的选择是什么?

标签: c++ c++-cli


【解决方案1】:

试试这个:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-12
相关资源
最近更新 更多