Easy and convenient way to convert Wide Characters to Multibyte with modern C++

One  of the most common tasks we developers have to do comes in the form of data conversion. A good example would be converting  void* (equivalent of Object in .NET) to a specific pointer of a different class through reinterpret_cast, this is however one example. Today’s post is about converting strings as Wide Characters to Multibyte using modern C++.

By modern C++, I mean using smart pointers instead of naked or raw pointers, string class and since it’s a functionality that will be used in different sections of code, it could be in the form of a function template or lambda, in this case, I’ll use a lambda as shown below

1 auto ConvertWstringToChar = [=](std::wstring& original) -> std::string { 2 std::string retval; 3 size_t cntConverted; 4 5 if (!original.empty()) { 6 wcstombs_s(&cntConverted, nullptr, NULL, original.c_str(), 7 original.size()); 8 9 auto buffer = std::make_unique<char[]>(cntConverted); 10 11 memset(buffer.get(), ' ', original.size()); 12 13 wcstombs_s(&cntConverted, buffer.get(), strlen(buffer.get()) + 1, 14 original.c_str(), original.size()); 15 16 retval.append(buffer.get()); 17 } 18 19 return retval; 20 }; 21 22 std::wstring test(L"This is my very funky string!!!!"); 23 auto converted = ConvertWstringToChar(test); 24 }

Leave a Reply

Your email address will not be published. Required fields are marked *