WideCharToMultiByte and MultiByteToWideChar

bool UnicodeToAnsi(const wchar_t* lpString, char* szAnsi)//(in,out) 
{
 char* pWideCharStr;
 int nLenOfWideChar, nReturnlen;
 nLenOfWideChar = WideCharToMultiByte(CP_ACP, 0, lpString, -1, NULL, 0, NULL, NULL);
 //Header: Declared in Winnls.h; include Windows.h. 
 if (!nLenOfWideChar)
  return false;
 pWideCharStr = (char*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nLenOfWideChar + 1);
 nReturnlen = WideCharToMultiByte(CP_ACP, 0, lpString, -1, pWideCharStr, nLenOfWideChar, NULL, NULL);
 if (!nReturnlen)
 {
  HeapFree(GetProcessHeap(), 0, pWideCharStr);
  return false;
 }
 strcpy_s(szAnsi, nLenOfWideChar, pWideCharStr);
 HeapFree(GetProcessHeap(), 0, pWideCharStr);
 return true;
}

bool AnsiToUnicode(const char* lpString, wchar_t* szUnicode)//(in,out) 
{
 wchar_t* pWideCharStr;
    int nLenOfWideChar, nReturnlen;
    nLenOfWideChar = MultiByteToWideChar(CP_ACP, 0, lpString, -1, NULL, 0);
    //Header: Declared in Winnls.h; include Windows.h. 
    if (!nLenOfWideChar)
        return false;
    pWideCharStr = (wchar_t*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nLenOfWideChar * 2);
    nReturnlen = MultiByteToWideChar(CP_ACP, 0, lpString, -1, pWideCharStr, nLenOfWideChar);
    if (!nReturnlen)
    {
        HeapFree(GetProcessHeap(), 0, pWideCharStr);
        return false;
    }
    wcscpy_s(szUnicode, nLenOfWideChar, pWideCharStr);
    HeapFree(GetProcessHeap(), 0, pWideCharStr);
    return true;
}

posted on 2016-11-01 16:55  carekee  阅读(373)  评论(0编辑  收藏  举报