将Platform::String转换为std::String
Convert Platform::String to std::string
我得到了String^
,它在Windows Phone 8项目的Cocos2dx游戏中,在我的C++WinRT组件中的C#组件的回调中包含一些印度语言字符。
每当我把它转换成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提供了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
}
使用C++,您可以使用以下代码从Platform::String
转换为std::string
:
Platform::String^ fooRT = "aoeu";
std::wstring fooW(fooRT->Begin());
std::string fooA(fooW.begin(), fooW.end());
参考:如何将Platform::String转换为char*?
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- C++:考虑C++ std::string 中双引号 (") 的字面含义,而不使用反斜杠 (\)
- 'int main(int, int, std::__cxx11::string, std::__cxx11::string)'只需要零或两个参数 [-Wmain]
- C++ 在列表和列表之间选择返回类型<<string>std::p air<string,string>>
- std::string, std::wstring and UTF8
- uan inplace replacement of std::string/std::wstring?
- #define Glib::string std:wstring
- 从 std::string & std::wstring 中获取 char 整数值
- BSTR转换为std::string(std::wstring),反之亦然