[英]Convert Platform::String to std::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. 我在Windows Phone 8项目的Cocos2dx游戏中从C#WinRT组件中的C#组件的回调中获取
String^
,其中包含一些印度语言字符。
Whenever I convert it to std::string
the Hindi and other characters turn in to garbage characters. 每当我将其转换为
std::string
印地语时,其他字符就会变成垃圾字符。 I'm not able to find why this is happening. 我无法找到原因。
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 这是一个示例代码,我在这里刚刚定义了
Platform::String^
,但考虑它已从C#组件传递到C++ WinRT Component
。
String^ str = L"विकास, વિકાસ, ਵਿਕਾਸ, Vikas";
std::wstring wsstr(str->Data());
std::string res(wsstr.begin(), wsstr.end());
Edit: see this answer for a better portable solution. 编辑:请参阅此答案以获得更好的便携式解决方案。
The problem is that std::string
only holds 8-bit character data and your Platform::String^
holds Unicode data. 问题在于
std::string
仅保存8位字符数据,而Platform::String^
保存Unicode数据。 Windows provides functions WideCharToMultiByte
and MultiByteToWideChar
to convert back and forth: 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
}
With C++, you can convert from Platform::String
to std::string
with the following code: 使用C ++,可以使用以下代码将
Platform::String
转换为std::string
:
Platform::String^ fooRT = "aoeu";
std::wstring fooW(fooRT->Begin());
std::string fooA(fooW.begin(), fooW.end());
Reference: How to convert Platform::String to char*? 参考: 如何将Platform :: String转换为char *?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.