很多时候,我们的程序需要支持两种字符集,Multi-Byte与Unicode。
这时就需要进行字符串转换,以及两套API之间的切换。
对两种字符集的统一支持,本文做了一些简单总结。
1、常用转换函数
以下四个函数为Multibyte/Unicode转化基本函数,已处理内存泄露问题。
其他转换可以在这四个基本函数基础上操作。1.1. Ansi转化为Unicode
static wstring AnsiToUnicode(const string& str)
{int unicodeLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);if (unicodeLen <= 0){return L"";}wchar_t* pUnicode = new wchar_t[unicodeLen+1];memset(pUnicode, 0, (unicodeLen+1)*sizeof(wchar_t));::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, (LPWSTR)pUnicode, unicodeLen);wstring rt = pUnicode;delete[] pUnicode;pUnicode = NULL;return rt;
}
1.2. Unicode转化为Ansi
static