关于cocos2d-x移植到WP8之上的中文乱码问题

Hi,大家好。

因一些需求,项目需要升级到windows phone8.1 universal app。当前项目是3D的,查看cocos2d-x 3.5版本里面有universal C++的工程,故首先升级了引擎。

移植过程不多说了。

在移植上去之后,游戏跑起来后,发现部分自己写的中文字符无法解析,一堆乱码。期初是在模拟器上调试。后来使用两个方法解决了之,归根结底是字符编码问题。

提供两个方法。GBK转UTF8,UTF8转GBK。

string GBKToUTF8(const std::string& strGBK)
{  
string strOutUTF8 = "";  
WCHAR * str1;  
int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);  
str1 = new WCHAR[n];  
MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);  
n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);  
char * str2 = new char[n];  
WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);  
strOutUTF8 = str2;  
delete[]str1;  
str1 = NULL;  
delete[]str2;  
str2 = NULL;  
return strOutUTF8;  
}  

string UTF8ToGBK(const std::string& strUTF8)
{  
int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, NULL, 0);  
unsigned short * wszGBK = new unsigned short[len + 1];  
memset(wszGBK, 0, len * 2 + 2);  
MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)strUTF8.c_str(), -1, (LPWSTR)wszGBK, len);  


len = WideCharToMultiByte(CP_ACP, 0, (LPWSTR)wszGBK, -1, NULL, 0, NULL, NULL);  
char *szGBK = new char[len + 1];  
memset(szGBK, 0, len + 1);  
WideCharToMultiByte(CP_ACP,0, (LPWSTR)wszGBK, -1, szGBK, len, NULL, NULL);  
//strUTF8 = szGBK;  
std::string strTemp(szGBK);  
delete[]szGBK;  
delete[]wszGBK;  
return strTemp;  
}

后面在模拟器上看,没有问题了。很高兴的结束了这个问题。

后来运行Release ARM的包到手机上的时候,发现字符又乱码了。,发现这个问题,整个人就不好了。

后来通过另外一个方法解决之,转UTF8方法。还要谢谢 梅颖广先生。

下面是解决方法以及调用方法:

调用:yourLabelObj->setString(WStrToUTF8(L"抱歉,本游戏停止运营。"))

std::string WStrToUTF8(const std::wstring& src)
{
std::string dest;
dest.clear();
for (size_t i = 0; i < src.size(); i++)
{
wchar_t w = src[i];
if (w <= 0x7f)
{
dest.push_back((char)w);
}
else if(w <= 0x7ff)
{
dest.push_back(0xc0 | ((w >> 6) & 0x1f));
dest.push_back(0x80 | (w & 0x3f));
}
else if(w <= 0xffff)
{
dest.push_back(0xe0 | ((w >> 12) & 0x0f));
dest.push_back(0x80 | ((w >> 6) & 0x3f));
dest.push_back(0x80 | (w & 0x3f));
}
else if(sizeof(wchar_t) > 2 && w <= 0x10ffff)
{
dest.push_back(0xf0 | ((w >> 18) & 0x07));
dest.push_back(0x80 | ((w >> 12) & 0x3f));
dest.push_back(0x80 | ((w >> 6) & 0x3f));
dest.push_back(0x80 | (w & 0x3f));
}
else
dest.push_back('?');
}
return dest;
}

文章结束,谢谢大家。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WhiteTian

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值