Convert ANSI to UNICODE and vice versa

>> Thursday, October 15, 2009


You have an ANSI string, now we want to create a unicode string with the same content.

The API function used here is MultiByteToWideChar. Read here for the complete description of the function.
Here's the practical tip: create a wrapper function to use in conversion.

LPWSTR ProduceWFromA(UINT uiCodePage, LPCSTR psz)
{
  LPWSTR pszW;
  int cch;

  if (psz == NULL || psz == LPSTR_TEXTCALLBACKA)
    return (LPWSTR)psz;

  if (IsBadReadPtr(psz, 1))
    return NULL;

  // The function returns the required buffer size, in characters, including any //terminating null character, and makes no use of the lpWideCharStr buffer.
  cch = MultiByteToWideChar(uiCodePage, 0, psz,  - 1, NULL, 0);

  if (cch == 0)
    cch = 1;
  // Now we have the size. We create a buffer for UNICODE string.
  pszW = LocalAlloc(LMEM_FIXED, cch *sizeof(WCHAR));
  // and copy the ANSI string to that buffer.
  if (pszW != NULL)
  {
    if (MultiByteToWideChar(uiCodePage, MB_PRECOMPOSED, psz,  - 1, pszW, cch) 
== FALSE)
    {
      LocalFree(pszW);
      pszW = NULL;
    }
  }
  return pszW;
}



Now you can understand the vice-versa conversion ( UNICODE -> ANSI ) without comment in the following code.
LPSTR ProduceAFromW(UINT uiCodePage, LPCWSTR psz)
{
  LPSTR pszA;
  int cch;

  if (psz == NULL || psz == LPSTR_TEXTCALLBACKW)
    return (LPSTR)psz;

  cch = WideCharToMultiByte(uiCodePage, 0, psz,  - 1, NULL, 0, NULL, NULL);

  if (cch == 0)
    cch = 1;

  pszA = LocalAlloc(LMEM_FIXED, cch *sizeof(char));

  if (pszA != NULL)
  {
    if (WideCharToMultiByte(uiCodePage, 0, psz,  - 1, pszA, cch, NULL, NULL) ==
      FALSE)
    {
      LocalFree(pszA);
      pszA = NULL;
    }
  }
  return pszA;
}


0 comments: