Convert between wchar_t* and char*

This tutorial will show you some code snippets that perform conversion between wchar_t* and char* using WideCharToMultiByte and MultiByteToWideChar

#include <windows.h>

Convert from wchar_t* to char*

char* wchar2char(wchar_t* wname)
{
	char* cname = NULL;
	int len_wname, len_cname;
	len_wname = wcslen(myFileName->Data());
	len_cname = WideCharToMultiByte(CP_ACP, 0, wname, len_wname, NULL, 0, NULL, FALSE);

	if(len_cname > 0)
	{
        cname = (char*)malloc(sizeof(char) * (len_cname+1));
		WideCharToMultiByte(CP_ACP, 0, wname, len_wname, cname, len_cname, NULL, FALSE);
	}

	cname[len_cname] = 0;

	return cname;
}

Convert from char* to wchar_t*

wchar_t* char2wchar(char* cname)
{
	wchar_t* wname = NULL;
	int len_wname, len_cname;

	len_cname = strlen(cname);
	len_wname = MultiByteToWideChar(CP_ACP, 0, cname, len_cname, NULL, 0);

	if(len_wname > 0)
	{
		wname = (wchar_t*)malloc(sizeof(wchar_t) * (len_wname+1));
		MultiByteToWideChar(CP_ACP, 0, cname, len_cname, wname, len_wname);
	}

	wname[len_wname] = 0;

	return wname;
}

1,807 total views, 11 views today