在数据库中获取的数据时utf-8编码,放到mfc中就是unicode编码了,需要进行转码
一、//utf8转unicode
wchar_t* CExonDlg::Utf_8ToUnicode(char* szU8)
{
int wcsLen = ::MultiByteToWideChar(CP_UTF8, NULL,szU8, strlen(szU8),NULL, 0);
wchar_t* wszString = new wchar_t[wcsLen + 1];
::MultiByteToWideChar(CP_UTF8, NULL, szU8, strlen(szU8), wszString, wcsLen);
wszString[wcsLen] = '\0';
return wszString;
}
二、//unicode转utf8
char* CExonDlg::UnicodeToUTF_8First(CString str)
{
int u8Len =WideCharToMultiByte(CP_UTF8, NULL,CStringW(str),str.GetLength(), NULL, 0, NULL, NULL);
char* szU8 = new char[u8Len + 1];
WideCharToMultiByte(CP_UTF8, NULL, CStringW(str), str.GetLength(), szU8, u8Len, NULL, NULL);
szU8[u8Len] = '\0';
return szU8;
}
uncode转utf-8的时候。第四个参数设置为-1,则会自动计算长度。
uniocde转utf-8,当传入的和传出的参数均为cstring时。
CString CExonDlg::UnicodeToUTF_8First(CString str)
{
CStringW strWide = CT2CW(str); // 将T字符转换成宽字符
WCHAR *buffer = new WCHAR[str.GetLength()+1];
buffer[str.GetLength()] = 0;
buffer = strWide.GetBuffer(str.GetLength()); // 获取CString内部缓存,并保证缓存长度是STR_LEN
int u8Len =WideCharToMultiByte(CP_UTF8, NULL,buffer, wcslen(buffer), NULL, 0, NULL, FALSE);
char* szU8 = new char[u8Len + 1];
WideCharToMultiByte(CP_UTF8,NULL,buffer, wcslen(buffer), szU8, u8Len, NULL, FALSE);
szU8[u8Len] = '\0';
CString str_utf(szU8);
delete []szU8;
return str_utf;
}