Created
June 29, 2021 16:19
-
-
Save alexeyr/c59ea2161bab919cf7dd7ddf2012cddc to your computer and use it in GitHub Desktop.
The proper way to use wcsrtombs to convert a const wchar_t* to an std::string (so far as I can tell)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstring> | |
#include <cwchar> | |
inline void ResetMbState(std::mbstate_t &state) { | |
// this is really the recommended way to zero-initialize an mbstate_t | |
std::memset(&state, 0, sizeof(std::mbstate_t)); | |
} | |
inline std::string WCharPtrToString(const wchar_t *data) { | |
std::mbstate_t state; | |
ResetMbState(state); | |
const wchar_t *src = data; | |
size_t length = std::wcsrtombs(nullptr, &src, 0, &state); | |
// replace by `if` if you want to actually do something on error | |
ASSERT(length != static_cast<size_t>(-1)); | |
std::string result(length + 1, '\0); | |
ResetMbState(state); | |
src = data; | |
std::wcsrtombs(&result[0], &src, length + 1, &state); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment