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?
Maps a character string to a UTF-16 (wide character) string. The character string is not necessarily from a multibyte character set.
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.
You must call MultiByteToWideChar
twice:
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With