cococos 2 d-x Utf 8多言語符号化クラス

1458 ワード

//h
#pragma once
#include <string>
using namespace std;
class CMultiLang
{
public:
  static string iconvGbkToUtf8(const string& str);//Gbk GB2312 , 、 。
  // 
  //CCLabelTTF* pLabel = CCLabelTTF::create(CMultiLang::iconvGbkToUtf8("わだぅわ、 cocos2d-x!").c_str(), "Arial", TITLE_FONT_SIZE);
  //pLabel->setColor(ccc3(0, 255, 0));
  // 
  static bool iconvConvert(const char* from_charset, const char* to_charset, const char* inbuf, int inlen, char* outbuf, int outlen);
};
//ccp
#include "MultiLang.h"
#include "iconv/iconv.h"
// 
bool CMultiLang::iconvConvert(const char* from_charset, const char* to_charset, const char* inbuf, int inlen, char* outbuf, int outlen)
{
  iconv_t cd=iconv_open(to_charset, from_charset);
  if(cd==0)
    return false;
  const char** pin=&inbuf;
  char** pout=&outbuf;
  memset(outbuf, 0, outlen);
  size_t ret=iconv(cd, pin, (size_t*)&inlen, pout, (size_t*)&outlen);
  iconv_close(cd);
  return ret==(size_t)(-1)? false: true;
}
string CMultiLang::iconvGbkToUtf8(const string& str)
{
  const char* textIn=str.c_str();
  int inLen=str.length();
  int outLen=inLen*2+1;
  char* textOut=(char*)malloc(outLen);
    
  bool ret=false;
  if(textOut)
    ret=iconvConvert("gbk", "utf-8", textIn, inLen, textOut, outLen);
  string strOut=ret? string(textOut): string();
  free(textOut);
    
  return strOut;
}