在程序开发中,往往需要进行编码转换。中国的汉字采用的是GBK编码,往往需要转换为utf-8编码。因此,这里给出windows和linux的通用转换方案。接口和实现已经写好,编译出来是个动态库。如有不对地方,请大家指正。
//CCharacter.h file
#ifndef CCHARACTER_H
#define CCHARACTER_H
#include
#ifdef _WIN32
# ifdef EXPORT_CHARACTER
# define CCONVERSION_API extern "C" __declspec( dllexport )
# else
# define CCONVERSION_API extern "C" __declspec( dllimport )
# endif
#else
# define CCONVERSION_API extern "C"
#endif
CCONVERSION_API int GbkToUtf8(char *inbuf,size_t inlen,char *outbuf,size_t outlen);
CCONVERSION_API int Utf8ToGbk(char *inbuf,size_t inlen,char *outbuf,size_t outlen);
#endif // CCHARACTER_H
//CCharacter.cpp file
#include "CCharacter.h"
# ifdef WIN32
#include
#endif
#include
#include
#ifdef _LINUX
#include
#endif
CCONVERSION_API int Utf8ToGbk(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
if( inlen > outlen )
return -1;
#ifdef _LINUX
iconv_t cd;
char **pin = &inbuf;
char **pout = &outbuf;
cd = iconv_open("gb2312","utf-8");
if (cd == 0)
return -1;
memset(outbuf,0,outlen);
if (iconv(cd,pin,&inlen,pout,&outlen) == -1)
return -1;
iconv_close(cd);
return 0;
#endif
#ifdef WIN32
int len = MultiByteToWideChar(CP_UTF8, 0, inbuf, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len+1];
memset(wstr, 0, len+1);
MultiByteToWideChar(CP_UTF8, 0, inbuf, -1, wstr, len);
len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_ACP, 0, wstr, -1, outbuf, len, NULL, NULL);
if(wstr) delete[] wstr;
return 0;
#endif
}
CCONVERSION_API int GbkToUtf8(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
if( inlen > outlen )
return -1;
#ifdef _LINUX
iconv_t cd;
char **pin = &inbuf;
char **pout = &outbuf;
cd = iconv_open("utf-8","gb2312");
if (cd == 0)
return -1;
memset(outbuf,0,outlen);
if (iconv(cd,pin,&inlen,pout,&outlen) == -1)
return -1;
iconv_close(cd);
return 0;
#endif
#ifdef WIN32
int len = MultiByteToWideChar(CP_ACP, 0, inbuf, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len+1];
memset(wstr, 0, len+1);
MultiByteToWideChar(CP_ACP, 0, inbuf, -1, wstr, len);
len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, outbuf, len, NULL, NULL);
if(wstr) delete[] wstr;
return 0;
#endif
}