将 Platform::String 转换为 std::string [英] Convert Platform::String to std::string

查看:46
本文介绍了将 Platform::String 转换为 std::string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Windows Phone 8 项目的 Cocos2dx 游戏中从我的 C++ WinRT 组件中的 C# 组件回调中得到 String^ 包含一些印度语言字符.

I am getting 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 时,印地语和其他字符都会变成垃圾字符.我无法找到发生这种情况的原因.

Whenever I convert it to std::string the Hindi and other characters turn in to garbage characters. I'm not able to find why this is happening.

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

Here is a sample code and I have just defined Platform::String^ here but consider it's passed to C++ WinRT Component from C# Component

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

推荐答案

请参阅此答案以获得更好的便携性解决方案.

see this answer for a better portable solution.

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

The problem is that std::string only holds 8-bit character data and your Platform::String^ holds Unicode data. Windows provides functions WideCharToMultiByte and MultiByteToWideChar to convert back and forth:

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
}

这篇关于将 Platform::String 转换为 std::string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆