Skip to content

Instantly share code, notes, and snippets.

@alexeyr
Created June 29, 2021 16:19
Show Gist options
  • Select an option

  • Save alexeyr/c59ea2161bab919cf7dd7ddf2012cddc to your computer and use it in GitHub Desktop.

Select an option

Save alexeyr/c59ea2161bab919cf7dd7ddf2012cddc to your computer and use it in GitHub Desktop.

Revisions

  1. alexeyr created this gist Jun 29, 2021.
    21 changes: 21 additions & 0 deletions WCharPtrToStdString.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    #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;
    }