Thursday, November 19, 2009

char* to wchar_t* conversion

Say you have a const char* string and you need to convert it to wchar_t type so that it can be stored in wide character format, here is the piece of code that takes the const char* and returns the wchar string for you.
Note that it does not work without the setlocale funtion.

You need to include locale.h and wchar.h header files for this to work.


wchar_t* utf2wchar(const char *str) {
setlocale(LC_ALL, "en_US.UTF-8");
int size = strlen(str);
wchar_t uni[100]; //assuming that there wont be a 101+ charcter word
int ret = mbstowcs(uni,str,size);
if(ret<=0){cprintf("mbstowc failed, ret=%d",ret);}
return uni;
}

No comments:

Post a Comment