编程语言
首页 > 编程语言> > c# – 将Platform :: String转换为std :: string

c# – 将Platform :: String转换为std :: string

作者:互联网

我正在获取String ^,其中包含一些印度语言字符,这些字符来自我在Windows Phone 8项目的Cocos2dx游戏中的C WinRT组件中的C#组件.

每当我将它转换为std :: string时,印地语和其他字符就会变成垃圾字符.我无法找到为什么会这样.

这是一个示例代码,我刚刚在这里定义了Platform :: String ^,但考虑从C#Component传递给C WinRT组件

String^ str = L"विकास, વિકાસ, ਵਿਕਾਸ, Vikas";
std::wstring wsstr(str->Data());
std::string res(wsstr.begin(), wsstr.end());

解决方法:

编辑:请参阅this answer以获得更好的便携式解决方案.

问题是std :: string只保存8位字符数据,而Platform :: String ^保存Unicode数据. Windows提供功能WideCharToMultiByte和MultiByteToWideChar来回转换:

std::string make_string(const std::wstring& wstring)
{
  auto wideData = wstring.c_str();
  int bufferSize = WideCharToMultiByte(CP_UTF8, 0, wideData, -1, nullptr, 0, NULL, NULL);
  auto utf8 = std::make_unique<char[]>(bufferSize);
  if (0 == WideCharToMultiByte(CP_UTF8, 0, wideData, -1, utf8.get(), bufferSize, NULL, NULL))
    throw std::exception("Can't convert string to UTF8");

  return std::string(utf8.get());
}

std::wstring make_wstring(const std::string& string)
{
  auto utf8Data = string.c_str();
  int bufferSize = MultiByteToWideChar(CP_UTF8, 0, utf8Data, -1, nullptr, 0);
  auto wide = std::make_unique<wchar_t[]>(bufferSize);
  if (0 == MultiByteToWideChar(CP_UTF8, 0, utf8Data, -1, wide.get(), bufferSize))
    throw std::exception("Can't convert string to Unicode");

  return std::wstring(wide.get());
}

void Test()
{
  Platform::String^ str = L"विकास, વિકાસ, ਵਿਕਾਸ, Vikas";
  std::wstring wsstr(str->Data());
  auto utf8Str = make_string(wsstr); // UTF8-encoded text
  wsstr = make_wstring(utf8Str); // same as original text
}

标签:cocos2d-x,c,windows-phone-8,c-2,winrt-component
来源: https://codeday.me/bug/20191007/1866237.html