#include "lang.h" #include <assert.h> #include <new> using namespace std; LPWSTR Utf8ToUnicode(LPSTR lpszUtf8, DWORD& dwBufLen) { assert(lpszUtf8); LPWSTR lpwBuf = NULL; try { //得到转换后的字符串长度 dwBufLen = MultiByteToWideChar(CP_UTF8, 0, lpszUtf8, -1, NULL, NULL); //new buffer lpwBuf = new(nothrow) wchar_t[dwBufLen]; if (NULL == lpwBuf) { return NULL; } memset(lpwBuf, 0, dwBufLen * sizeof(wchar_t)); MultiByteToWideChar(CP_UTF8, 0, lpszUtf8, -1, lpwBuf, dwBufLen); } catch (...) { return NULL; } return lpwBuf; } LPSTR UnicodeToUtf8(LPWSTR lpwBuf, DWORD& dwBufLen) { assert(lpwBuf); LPSTR lpszUtf8 = NULL; try { //得到转换后的字符串长度 dwBufLen = WideCharToMultiByte(CP_UTF8, 0, lpwBuf, -1, NULL, 0, NULL, NULL); lpszUtf8 = new(nothrow) char[dwBufLen]; if (NULL == lpszUtf8) { return lpszUtf8; } memset(lpszUtf8, 0, dwBufLen); WideCharToMultiByte(CP_UTF8, 0, lpwBuf, -1, lpszUtf8, dwBufLen, NULL, NULL); } catch (...) { return NULL; } return lpszUtf8; } LPSTR UnicodeToAnsi(LPWSTR lpwBuf, DWORD& dwBufLen) { assert(lpwBuf); LPSTR lpszBuf = NULL; try { //得到转换后的字符串长度 dwBufLen = WideCharToMultiByte(CP_ACP, 0, lpwBuf, -1, NULL, 0, NULL, NULL); lpszBuf = new(nothrow) char[dwBufLen]; if (NULL == lpszBuf) { return lpszBuf; } memset(lpszBuf, 0, dwBufLen); WideCharToMultiByte(CP_ACP, 0, lpwBuf, -1, lpszBuf, dwBufLen, NULL, NULL); } catch (...) { return NULL; } return lpszBuf; } LPWSTR AnsiToUnicode(LPSTR lpszBuf, DWORD& dwBufLen) { assert(lpszBuf); LPWSTR lpwBuf = NULL; try { dwBufLen = MultiByteToWideChar(CP_ACP, 0, lpszBuf, -1, NULL, 0); //new buffer lpwBuf = new(nothrow) wchar_t[dwBufLen]; if (NULL == lpwBuf) { return NULL; } memset(lpwBuf, 0, dwBufLen * sizeof(wchar_t)); MultiByteToWideChar(CP_ACP, 0, lpszBuf, -1, lpwBuf, dwBufLen); } catch (...) { return NULL; } return lpwBuf; } LPSTR AnsiToUtf8(LPSTR lpszBuf, DWORD& dwBufLen) { assert(lpszBuf); LPSTR lpszUtf8 = NULL; try { LPWSTR lpwBuf = AnsiToUnicode(lpszBuf, dwBufLen); if (NULL == lpwBuf) { return NULL; } lpszUtf8 = UnicodeToUtf8(lpwBuf, dwBufLen); //release delete[] lpwBuf; lpwBuf = NULL; } catch (...) { return NULL; } return lpszUtf8; } LPSTR Utf8ToAnsi(LPSTR lpszUtf8, DWORD& dwBufLen) { assert(lpszUtf8); LPSTR lpszBuf = NULL; try { LPWSTR lpwBuf = Utf8ToUnicode(lpszUtf8, dwBufLen); if (NULL == lpwBuf) { return NULL; } lpszBuf = UnicodeToAnsi(lpwBuf, dwBufLen); //release buff delete[] lpwBuf; lpwBuf = NULL; } catch (...) { return NULL; } return lpszBuf; }