Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you properly use WideCharToMultiByte

I've read the documentation on WideCharToMultiByte, but I'm stuck on this parameter:

lpMultiByteStr [out] Pointer to a buffer that receives the converted string. 

I'm not quite sure how to properly initialize the variable and feed it into the function

like image 717
Obediah Stane Avatar asked Oct 19 '08 03:10

Obediah Stane


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

Here's a couple of functions (based on Brian Bondy's example) that use WideCharToMultiByte and MultiByteToWideChar to convert between std::wstring and std::string using utf8 to not lose any data.

// Convert a wide Unicode string to an UTF8 string std::string utf8_encode(const std::wstring &wstr) {     if( wstr.empty() ) return std::string();     int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);     std::string strTo( size_needed, 0 );     WideCharToMultiByte                  (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);     return strTo; }  // Convert an UTF8 string to a wide Unicode String std::wstring utf8_decode(const std::string &str) {     if( str.empty() ) return std::wstring();     int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);     std::wstring wstrTo( size_needed, 0 );     MultiByteToWideChar                  (CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);     return wstrTo; } 
like image 149
tfinniga Avatar answered Sep 20 '22 23:09

tfinniga