注意的是,我们在内部释放了Ansi占用的内存
#include <iostream>
#include <string>
#include <fstream>
using std::string;
using namespace std;
wchar_t* AnsiToUnicode(char *sAnsi)
{
//ansi to unicode
int sLen = MultiByteToWideChar(CP_ACP, NULL, sAnsi, -1, NULL, 0);
wchar_t* sUnicode = new wchar_t[sLen];
//wchar_t* sUnicode = (wchar_t*)malloc(sLen*sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, NULL, sAnsi, -1, sUnicode, sLen);
return sUnicode;
//delete[] sUnicode;
//sUnicode =NULL;
//free(sUnicode);
}
char *UnicodeToUtf8(wchar_t *sUnicode)
{
int sLen = WideCharToMultiByte(CP_UTF8, NULL, sUnicode, -1, NULL, 0, NULL, NULL);
//UTF8虽然是Unicode的压缩形式,但也是多字节字符串,所以可以以char的形式保存
char* sUtf8 = new char[sLen];
//unicode版对应的strlen是wcslen
WideCharToMultiByte(CP_UTF8, NULL, sUnicode, -1, sUtf8, sLen, NULL, NULL);
printf("");
return sUtf8;
/*delete[] sUtf8;
sUtf8 =NULL; */
}
//ansi转换为utf-8
char *AnsiToUtf8(char *sAnsi){
wchar_t *unicode = AnsiToUnicode(sAnsi);
free(sAnsi);
if(unicode != NULL){
/*setlocale(LC_ALL,"chs");
wprintf(L"%s\n",unicode);*/
char *utf_8 = UnicodeToUtf8(unicode);
if(utf_8){
free(unicode);
return utf_8;
}
else{
free(unicode);
return NULL;
}
}else
return NULL;
}