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?
You must call
MultiByteToWideChartwice:The first call to
MultiByteToWideCharis used to find the buffer size you need for the wide string. Look at Microsoft’s documentation; it states:Thus, to make
MultiByteToWideChargive you the required size, pass 0 as the value of the last parameter,cchWideChar. You should also passNULLas the one before it,lpWideCharStr.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:
Also, note the use of -1 as the
cbMultiByteargument. This will make the resulting string null-terminated, saving you from dealing with them.