Cocos2d-x程序Windows下VC中文乱码的解决(用MultiByteToWideChar进行转换,VC2010有非常厉害的execution_character_set)

Cocos2d-x默认字符串常量编码都是UTF8的,而Windows中的VC默认都是跟系统相同,比如简体Windows是GB2312或者GBK.繁体就是BIG5编码.
而我们大多数中国人用VC编译出来的字符串常量也就是GBK编码的字符串.
在Cocos2d-x界面上绘制的时候它是不知道的,只会认为这个是UTF8字符串,结果就出现了乱码.
解决方式也很简单.找个头文件加入下面的代码

#ifdef WIN32
 
inline std::wstring AnsiToUnicode(const char* buf)
{
    int len = ::MultiByteToWideChar(CP_ACP, 0, buf, -1, NULL, 0);
    if (len == 0) return L"";
 
    std::wstring unicode;
    unicode.resize(len);
    ::MultiByteToWideChar(CP_ACP, 0, buf, -1, &unicode[0], len);
 
    return unicode;
}
 
inline std::string UnicodeToUtf8(const wchar_t* buf)
{
    int len = ::WideCharToMultiByte(CP_UTF8, 0, buf, -1, NULL, 0, NULL, NULL);
    if (len == 0) return "";
 
    std::string utf8;
    utf8.resize(len);
    ::WideCharToMultiByte(CP_UTF8, 0, buf, -1, &utf8[0], len, NULL, NULL);
 
    return utf8;
}
 
inline
std::string AnsioUTF8(const char *strChar)
{
    return UnicodeToUtf8(AnsiToUnicode(strChar).c_str());
}
//Windows中做编码转换,
#define UTEXT(str) AnsioUTF8(str)
#else
//Android/iOS中不处理.
#define UTEXT(str) str
#endif

需要用到中文字符串的时候

CCLOG(UTEXT("这是中文字符串!"));
Text* txt = Text::create();
txt->setString(UTEXT("文本中的中文字符正常的!"));

补充,在这篇博客发表后两天发现有更直接的方法.

#ifdef WIN32
#pragma execution_character_set("utf-8")
#endif

这样VC编译器就会把字符串常量按UTF8编码.

http://www.raysoftware.cn/?p=535

原文地址:https://www.cnblogs.com/findumars/p/4931016.html