簡體   English   中英

將Platform :: String轉換為std :: string

[英]Convert Platform::String to std::string

我在Windows Phone 8項目的Cocos2dx游戲中從C#WinRT組件中的C#組件的回調中獲取String^ ,其中包含一些印度語言字符。

每當我將其轉換為std::string印地語時,其他字符就會變成垃圾字符。 我無法找到原因。

這是一個示例代碼,我在這里剛剛定義了Platform::String^ ,但考慮它已從C#組件傳遞到C++ WinRT Component

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

編輯:請參閱此答案以獲得更好的便攜式解決方案。

問題在於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
}

使用C ++,可以使用以下代碼將Platform::String轉換為std::string

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

參考: 如何將Platform :: String轉換為char *?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM