代码之家  ›  专栏  ›  技术社区  ›  Vikas Patidar

将Platform::String转换为std::String

  •  4
  • Vikas Patidar  · 技术社区  · 11 年前

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

    每当我将其转换为 std::string 印地语和其他字符变成垃圾字符。我不知道为什么会这样。

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

    String^ str = L"विकास, વિકાસ, ਵਿਕਾਸ, Vikas";
    std::wstring wsstr(str->Data());
    std::string res(wsstr.begin(), wsstr.end());
    
    2 回复  |  直到 11 年前
        1
  •  5
  •   Community Mohan Dere    9 年前

    编辑:请参见 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
    }
    
        2
  •  2
  •   Community Mohan Dere    9 年前

    使用C++,您可以从 Platform::String std::string 具有以下代码:

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

    参考: How to convert Platform::String to char*?