Here is a note for anybody using this function. ALWAYS check the return code, and do NOT use the content of lpMultiByteStr if the function returned 0.
As it turns out, WideCharToMultiByte() even fills the buffer lpMultiByteStr when it is too small to hold the converted wide string - however it does not zero-terminate it. I'm not sure why the function would fill the resulting string if it knows that it's too small and then not zero-terminate it. I can only assume it's because it converts byte after bye.
Consider this sample code:
wchar_t wstrTest[] = L"12345678";
char strTest[4] = { '\0' };
WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR) wstrTest, -1, strTest, sizeof(strTest), NULL, NULL);
printf("Converted: %s\n", strTest);
If you don't check the return value, then any subsequent string operation will go past the size of strTest.
Converted: 1234╠╠╠╠╠╠╠╠1
WideCharToMultiByte() returns 0 in this case, but still fills strTest.
In my opinion, WideCharToMultiByte() should either NOT fill the destination variable if it's too small, or terminate it with a 0 character.
If it is "ok" that the resulting multibyte string is smaller and that data might be lost (which can be the case when you work with a fixed output buffer), then it's better to call the function like this:
WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR) wstrTest, -1, strTest, (sizeof(strTest) - sizeof(char)), NULL, NULL);
... assuming that strTest has been zeroed-out first.