Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use MultiByteToWideChar?

I want to convert a normal string to a wstring. For this, I am trying to use the Windows API function MultiByteToWideChar. But it does not work for me.

Here is what I have done:

string x = "This is c++ not java"; wstring Wstring; MultiByteToWideChar( CP_UTF8 , 0 , x.c_str() , x.size() , &Wstring , 0 );  

The last line produces the compiler error:

'MultiByteToWideChar' : cannot convert parameter 5 from 'std::wstring *' to 'LPWSTR' 

How do I fix this error?

Also, what should be the value of the argument cchWideChar? Is 0 okay?

like image 773
Suhail Gupta Avatar asked Jul 14 '11 12:07

Suhail Gupta


People also ask

What is Multibytetowidechar?

Maps a character string to a UTF-16 (wide character) string. The character string is not necessarily from a multibyte character set.

What is Cp_acp?

CP_ACP represents the system Ansi codepage. You cannot change that on a per-process or per-thread basis. It is a system-wide setting. If the DLL really is dependant on CP_ACP internally, then you have no choice but to convert your from/to UTF-8 whenever you interact with the DLL.


1 Answers

You must call MultiByteToWideChar twice:

  1. The first call to MultiByteToWideChar is used to find the buffer size you need for the wide string. Look at Microsoft's documentation; it states:

    If the function succeeds and cchWideChar is 0, the return value is the required size, in characters, for the buffer indicated by lpWideCharStr.

    Thus, to make MultiByteToWideChar give you the required size, pass 0 as the value of the last parameter, cchWideChar. You should also pass NULL as the one before it, lpWideCharStr.

  2. Obtain a non-const buffer large enough to accommodate the wide string, using the buffer size from the previous step. Pass this buffer to another call to MultiByteToWideChar. And this time, the last argument should be the actual size of the buffer, not 0.

A sketchy example:

int wchars_num = MultiByteToWideChar( CP_UTF8 , 0 , x.c_str() , -1, NULL , 0 ); wchar_t* wstr = new wchar_t[wchars_num]; MultiByteToWideChar( CP_UTF8 , 0 , x.c_str() , -1, wstr , wchars_num ); // do whatever with wstr delete[] wstr; 

Also, note the use of -1 as the cbMultiByte argument. This will make the resulting string null-terminated, saving you from dealing with them.

like image 109
eran Avatar answered Sep 16 '22 19:09

eran