兼容VC与GCC的 宽字符 – 多字节字符 转换

std::wstring MBytesToWString(const char* lpcszString)
{
	if (lpcszString == NULL)
	{
		return L"";
	}

#ifdef _MSC_VER
	int len = strlen(lpcszString);
	int unicodeLen = ::MultiByteToWideChar(CP_ACP, 0, lpcszString, -1, NULL, 0);
	wchar_t* pUnicode = new wchar_t[unicodeLen + 1];
	memset(pUnicode, 0, (unicodeLen + 1) * sizeof(wchar_t));
	::MultiByteToWideChar(CP_ACP, 0, lpcszString, -1, (LPWSTR)pUnicode, unicodeLen);
	std::wstring wString = (wchar_t*)pUnicode;
	delete[] pUnicode;
	return wString;
#elif __GNUC__
	return boost::locale::conv::utf_to_utf<wchar_t>(lpcszString);
#endif
}

std::string WStringToMBytes(const wchar_t* lpwcszWString)
{
	if (lpwcszWString == NULL)
	{
		return "";
	}

#ifdef _MSC_VER
	char* pElementText;
	int iTextLen;
	// wide char to multi char
	iTextLen = ::WideCharToMultiByte(CP_ACP, 0, lpwcszWString, -1, NULL, 0, NULL, NULL);
	pElementText = new char[iTextLen + 1];
	memset((void*)pElementText, 0, (iTextLen + 1) * sizeof(char));
	::WideCharToMultiByte(CP_ACP, 0, lpwcszWString, -1, pElementText, iTextLen, NULL, NULL);
	std::string strReturn(pElementText);
	delete[] pElementText;
	return strReturn;
#elif __GNUC__
	return boost::locale::conv::utf_to_utf<char>(lpwcszWString);
#endif
}

std::string WStringToUTF8(const wchar_t* lpwcszWString)
{
#ifdef _MSC_VER
	char* pElementText;
	int iTextLen = ::WideCharToMultiByte(CP_UTF8, 0, (LPWSTR)lpwcszWString, -1, NULL, 0, NULL, NULL);
	pElementText = new char[iTextLen + 1];
	memset((void*)pElementText, 0, (iTextLen + 1) * sizeof(char));
	::WideCharToMultiByte(CP_UTF8, 0, (LPWSTR)lpwcszWString, -1, pElementText, iTextLen, NULL, NULL);
	std::string strReturn(pElementText);
	delete[] pElementText;
	return strReturn;
#elif __GNUC__
	return WStringToMBytes(lpwcszWString);
#endif
}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

10 − 4 =