int code_convert(const char *from_charset, const char *to_charset, char *inbuf, uint32_t inlen, char *outbuf, uint32_t outlen)
{
iconv_t iconvH;
iconvH = iconv_open(to_charset, from_charset);
if (!iconvH) return 0;
memset(outbuf, 0, outlen);
#if(CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
const char *temp = inbuf;
const char **pin = &temp;
if (!iconv(iconvH, pin, &inlen, &outbuf, &outlen))
{
iconv_close(iconvH);
return 0;
}
#elif(CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
size_t tmpInLen = inlen, tmpOutLen = outlen;
if (!iconv(iconvH, &inbuf, &tmpInLen, &outbuf, &tmpOutLen))
{
iconv_close(iconvH);
return 0;
}
#elif(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
if (!iconv(iconvH, &inbuf, &inlen, &outbuf, &outlen))
{
iconv_close(iconvH);
return 0;
}
#endif
iconv_close(iconvH);
return 0;
}
string StringWithCoding(const char* inBuf, const char* srcCode, const char* dstCode)
{
if (inBuf == NULL || strlen(inBuf) == 0)
return "";
uint32_t inlen = (uint32_t)strlen(inBuf);
char * outbuf = new char[(inlen + 1) * 4];
string strRet;
char* tempStr = new char[inlen + 1];
strcpy(tempStr, inBuf);
if (code_convert(srcCode, dstCode, tempStr, inlen, outbuf, (inlen + 1) * 4) == 0)
{
strRet = outbuf;
}
delete[] tempStr;
delete[] outbuf;
return strRet;
}
string UTF8TOGBK(const char *inbuf)
{
return StringWithCoding(inbuf, "utf-8", "gbk");
}
string GBKTOUTF8(const char *inbuf)
{
return StringWithCoding(inbuf, "gbk", "utf-8");
}
调用UTF8TOGBK,返回一个string类型值
例如:label-》setString(GBKTOUTF8("中国").c_str());