#include "MyUtils.h"
#if(CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "../external/win32-specific/icon/include/iconv.h"
#else
#include "../iconv/include/iconv.h"
#endif
CMyUtils* CMyUtils::m_Instatce = nullptr;
CMyUtils* CMyUtils::getInstance()
{
if(m_Instatce == nullptr)
{
m_Instatce = new CMyUtils();
}
return m_Instatce;
}
void CMyUtils::release()
{
if (m_Instatce != nullptr)
{
delete m_Instatce;
m_Instatce = nullptr;
}
}
int CMyUtils::Convert(char* from_charset, char* to_charset, const char* inbuf, size_t inlen, char* outbuf, size_t outlen)
{
iconv_t cd = iconv_open(to_charset, from_charset);
if(cd == 0)
return -1;
memset(outbuf, 0, outlen);
#if(CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
const char* pTemp = inbuf;
const char** pIn = &pTemp;
char** pOut = &outbuf;
if(iconv(cd, pIn, &inlen, pOut, &outlen) == -1)
{
iconv_close(cd);
return -1;
}
#else
if(iconv(cd, &inbuf, &inlen, &outbuf, &outlen) == -1)
{
iconv_close(cd);
return -1;
}
#endif
iconv_close(cd);
return 0;
}
std::string CMyUtils::Gb2312ToUtf8(const char *inbuf)
{
size_t inleng = strlen(inbuf);
char* outbuf = new char[inleng * 2 + 2];
std::string strRet;
if( Convert("gb2312", "utf-8", inbuf, inleng, outbuf, inleng * 2 + 2) == 0 )
strRet = outbuf;
delete[] outbuf;
return strRet;
}
#ifndef __UTIL_H__
#define __UTIL_H__
#include <string>
class CMyUtils
{
private:
CMyUtils(){};
~CMyUtils(){};
public:
std::string Gb2312ToUtf8(const char *inbuf);
static CMyUtils* getInstance();
void release();
private:
int Convert(char* from_charset, char* to_charset, const char* inbuf, size_t inlen, char* outbuf, size_t outlen);
private:
static CMyUtils* m_Instatce;
};
#endif