都是WINAPI : MultiByteToWideChar的各种应用!
纯C++非MFC版:
/// <summary>
/// 字符串转换函数(ANSI-->Unicode)
/// </summary>
/// <param name="lpMultiByteStr"> 被转换的ANSI字符串 </param>
/// <param name="lpWideCharStr"> 接收Unicode字符串的地址,内部初始化 </param>
/// <returns>
/// The function returns 0 if it does not succeed.
/// Returns the number of characters written to the buffer indicated by lpWideCharStr if successful
/// </returns>
/// <remarks>
/// </remarks>
static int MByteToWChar(const char* lpMultiByteStr, std::unique_ptr<wchar_t>& lpWideCharStr)
{
// Get the required size of the buffer that receives the Unicode string.
// If the function succeeds(!=0) and cchWideChar is 0, the return value
// is the required size, in characters, for the buffer indicated by lpWideCharStr.
DWORD dwMinSize = MultiByteToWideChar (CP_ACP, 0, lpMultiByteStr, -1, NULL, 0);
if ( dwMinSize == 0 ){return 0;}
lpWideCharStr.reset( new wchar_t[dwMinSize] );
// Convert headers from ASCII to Unicode.
return MultiByteToWideChar (CP_ACP, 0, lpMultiByteStr, -1, lpWideCharStr.get(), dwMinSize);
}
MFC库源代码版:
int __stdcall CMFCControlContainer::UTF8ToString(LPCSTR lpSrc, CString& strDst, int nLength)
{
LPTSTR lpDst = NULL;
int count = ::MultiByteToWideChar(CP_UTF8, 0, lpSrc, nLength, NULL, 0);
if (count <= 0)
{
return 0;
}
LPWSTR lpWide = new WCHAR[count + 1];
memset(lpWide, 0, (count + 1) * sizeof(WCHAR));
::MultiByteToWideChar(CP_UTF8, 0, lpSrc, nLength, lpWide, count);
#ifdef _UNICODE
lpDst = lpWide;
#else
count = ::WideCharToMultiByte(::GetACP(), 0, lpWide, -1, NULL, 0, NULL, 0);
if (count > 0)
{
lpDst = new char[count + 1];
memset(lpDst, 0, count + 1);
::WideCharToMultiByte(::GetACP(), 0, lpWide, -1, lpDst, count, NULL, 0);
}
delete [] lpWide;
#endif
strDst = lpDst;
delete[] lpDst;
return count;
}
MFC版本:
char* p = "abc";
CString strW(p);