文《关于c++与java中文乱码问题分析与解决》中一个bug分析
DionysosLai(906391500@qq.com) 2014/10/21
在前几篇一博客《关于c++与java中文乱码问题分析与解决》,地址如下:http://blog.csdn.net/dionysos_lai/article/details/38389765。文中详细介绍了c++与java数据传递时,为何会出现中文乱码的原因,并提出了适当的解决方法。方法如下:
int CCDirector::GBKToUTF8(std::string &gbkStr)
{
iconv_t iconvH;
iconvH = iconv_open("utf-8","gb2312");
if(iconvH == 0){
return -1;
}
const char* strChar = gbkStr.c_str();
const char** pin = &strChar;
size_t strLength = gbkStr.length();
char* outbuf = (char*)malloc(strLength*4);
char* pBuff = outbuf;
memset(outbuf,0,strLength*4);
size_t outLength = strLength*4;
<span style="color:#ff6666;"><strong>#if(CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
if(-1 == iconv(iconvH,pin,&strLength,&outbuf,&outLength)){
iconv_close(iconvH);
return -1;
}
#else
if(-1 == iconv(iconvH,(char **)pin,&strLength,&outbuf,&outLength)){
iconv_close(iconvH);
return -1;
}
#endif</strong></span>
gbkStr = pBuff;
iconv_close(iconvH);
return 0;
}
这个方法,在这两个月的项目中,经过了多个游戏的检测,没有大的问题。不够后来,在传递一个特殊字符串时,发现了一个严重的bug。这个特殊的字符串就是空字符,即””。这时,传递过来的就是乱码了。不管在Win32和Android平台,均是这样情况。
问题,是出现在以下一段代码中:
size_t strLength = gbkStr.length();
char* outbuf = (char*)malloc(strLength*4);
char* pBuff = outbuf;
当我们传递的是空字符(””)时,strLength值为0,那么下面的内存赋值,明显会出现错误。因此对于空字符””,要做进一步的处理了。处理后的代码如下所示:
int XtcUtils::GBKToUTF8(std::string &gbkStr)
{
iconv_t iconvH;
iconvH = iconv_open("utf-8","gb2312");
if(iconvH == 0){
return -1;
}
const char* strChar = gbkStr.c_str();
const char** pin = &strChar;
size_t strLength = gbkStr.length();
if (0 == strLength) ///< 特殊情况下,gbkStr为"",strLength = 0时,转码会有乱码
{
gbkStr = "";
}
else
{
char* outbuf = (char*)malloc(strLength*4);
char* pBuff = outbuf;
memset(outbuf,0,strLength*4);
size_t outLength = strLength*4;
#if(CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
if(-1 == iconv(iconvH,pin,&strLength,&outbuf,&outLength)){
iconv_close(iconvH);
return -1;
}
#else
if(-1 == iconv(iconvH,(char **)pin,&strLength,&outbuf,&outLength)){
iconv_close(iconvH);
return -1;
}
#endif
gbkStr = pBuff;
}
iconv_close(iconvH);
return 0;
}
以上就是详实的代码了,有摘抄前文代码的同学们,希望改正下,不要出现严重的bug。