gpt4 book ai didi

c# - 将 Platform::String 转换为 std::string

转载 作者:行者123 更新时间:2023-11-30 14:53:38 25 4
gpt4 key购买 nike

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

每当我将其转换为 std::string 时,印地语和其他字符都会变成垃圾字符。我无法找到发生这种情况的原因。

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

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

最佳答案

编辑:参见 this answer以获得更好的可移植解决方案。

问题在于 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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28759212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com