c++windowsmsdnwstringmultibyte-functions

How to properly use MultiByteToWideChar


I am using MultiByteToWideChar to convert my string to a wstring. I am first trying to get the required size for my wstring. According to the documentation passing 0 as the last argument should accomplish this. Using MultiByteToWideChar(CP_UTF8, MB_COMPOSITE, str.c_str(), -1, nullptr, 0); returns 0 as the required size of the wstring buffer. I have verified that str is a non empty string as well. What am I doing wrong here?


Solution

  • From the MSDN documentation:

    For UTF-8 or code page 54936 (GB18030, starting with Windows Vista), dwFlags must be set to either 0 or MB_ERR_INVALID_CHARS. Otherwise, the function fails with ERROR_INVALID_FLAGS.

    You're using CP_UTF8 but also passing the MB_COMPOSITE flag, so that's why it's failing.