Page 1 of 1

C++ - Convert ANSI to UNICODE

Posted: Thu Mar 12, 2009 4:49 pm
by Spikey
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);
	}
	else
	{
	  // handle the error....
	  return NULL;
	}

	//// when done, free the BSTR
	::SysFreeString(unicodestr);

	return unicodestr;
}