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

Post Reply
User avatar
Spikey
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 98
Joined: Sat Dec 13, 2008 6:39 am
Programming Language of Choice: C++
Location: Ottawa, Canada
Contact:

C++ - Convert ANSI to UNICODE

Post 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;
}
Post Reply