C++ - Convert ANSI to UNICODE

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

C++ - Convert ANSI to UNICODE

Postby Spikey on Thu Mar 12, 2009 5:49 pm

This little snippet saved me this morning. I needed a way to display char* in win32 message boxes, but message boxes can only display LPCWSTR. I pass my char* and it returns compatible data for the message boxes. The source link has other conversions and snippets too. I encapsulated this snippet into a function.

Code: Select all
#include <windows.h>

Function:      Convert ANSI to UNICODE
Author:      Gabriel Fleseriu
Source:      http://www.codeguru.com/forum/showthread.php?t=231165
BSTR   ConvertANSItoUNICODE( char * ansistr ) {

   int lenA = lstrlenA(ansistr);
   int lenW;
   BSTR unicodestr;

   lenW = ::MultiByteToWideChar(CP_ACP, 0, ansistr, lenA, 0, 0);
   if (lenW > 0)
     // Check whether conversion was successful
     unicodestr = ::SysAllocStringLen(0, lenW);
     ::MultiByteToWideChar(CP_ACP, 0, ansistr, lenA, unicodestr, lenW);
     // handle the error....
     return NULL;

   //// when done, free the BSTR

   return unicodestr;
User avatar
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 98
Joined: Sat Dec 13, 2008 8:39 am
Location: Ottawa, Canada

Return to Programming Discussion

Who is online

Users browsing this forum: No registered users and 1 guest