September 22nd, 2021

Converting between UTF-8 strings and UTF-16 strings in C++/WinRT

C++/WinRT provides a pair of functions for converting between UTF-8 strings (with code units represented as char) and UTF-16 strings (code units of wchar_t).

The to_string function takes a std::wstring_view of UTF-16 code units and converts them to a UTF-8 string, represented as a std::string.

Conversely, the to_hstring function takes a std::string_view of UTF-8 code units and converts them to a UTF-16 string, represented as a winrt::hstring.

The argument to to_string and to_hstring can be anything convertible to the corresponding string view type. Types that fall into this category include

Type Converts to
std::string std::string_view
std::wstring std::wstring_view
winrt::hstring std::wstring_view

We’ll put these conversions to good use next time.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

4 comments

Discussion is closed. Login to edit/delete existing comments.

  • Luan Vitor Simião Oliveira

    should there also be a to_u16string? and versions that take a u8string_view?

  • Erik Weitenberg · Edited

    I suppose I get why the wstrings are named like that (string for wide characters) but I’m not sure what to think of hstring (high characters??). You explained a while ago that the H in HRESULT likely means ‘handle’, but I’m not sure that makes sense here.. Any clues? 🙂

    • Harry Johnston

      The documentation says that winrt::hstring encapsulates HSTRING, and that HSTRING is a handle to a Windows Runtime string, so I think your guess is correct. The documentation for HSTRING adds “use HSTRING to represent immutable strings in the Windows Runtime” and there are various associate API functions, e.g., WindowsCreateString and WindowsDeleteString.