4

我得到String^which contains some Indian language characters in a callback from C# Component in my C++ WinRT Component in a Cocos2dx game for Windows Phone 8 project.

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

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

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

2 回答 2

5

编辑:请参阅此答案以获得更好的便携式解决方案。

问题是std::string它只保存 8 位字符数据,而您Platform::String^保存 Unicode 数据。Windows 提供函数WideCharToMultiByteMultiByteToWideChar来回转换:

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
}
于 2015-02-28T07:17:05.973 回答
2

使用 C++,您可以使用以下代码将 fromPlatform::String转换为:std::string

Platform::String^ fooRT = "aoeu";
std::wstring fooW(fooRT->Begin());
std::string fooA(fooW.begin(), fooW.end());

参考:如何将 Platform::String 转换为 char*?

于 2016-03-10T01:05:32.347 回答