UTF-8、GBK等格式互相转换 [Windows/Linux 通用]
#ifdef WIN32
#include <windows.h>
#endif
#ifdef OS_UNIX
#include <iconv.h>
#endif
#if defined(WIN32)
void convert_encoding(const char *input, int from_codepage, int to_codepage, char *output)
{
int wlen = MultiByteToWideChar(from_codepage, 0, input, -1, NULL, 0);
if (0 == wlen)
return;
wchar_t *wbuf = (wchar_t *)malloc((wlen + 1) * sizeof(wchar_t));
MultiByteToWideChar(from_codepage, 0, input, -1, wbuf, wlen);
int len = WideCharToMultiByte(to_codepage, 0, wbuf, -1, NULL, 0, NULL, NULL);
if (0 == len)
{
free(wbuf);
return;
}
WideCharToMultiByte(to_codepage, 0, wbuf, -1, output, len, NULL, NULL);
free(wbuf);
}
#else
void convert_encoding(const char *input, const char *from_encoding, const char *to_encoding, char *output)
{
iconv_t cd = iconv_open(to_encoding, from_encoding);
if (cd == (iconv_t)-1)
return;
size_t in_len = strlen(input);
size_t out_len = in_len * 2; // 输出长度最多为输入长度的2倍
char *in_ptr = input, *out_ptr = output;
size_t ret = iconv(cd, &in_ptr, &in_len, &out_ptr, &out_len);
if (ret == (size_t)-1)
{
iconv_close(cd);
return; // 转换失败
}
*out_ptr = '\0'; // 添加字符串结尾
iconv_close(cd);
}
#endif
// 用法例:
// 从共享内存取到UTF-8格式的字符串res,转换为GBK格式字符串tmpstr
#ifdef WIN32
convert_encoding(res, CP_UTF8, CP_ACP, tmpstr);
#else
convert_encoding(res, "UTF-8", "GBK", tmpstr);
#endif