Skip to main content
RLarr.1
Associate III
October 22, 2025
Solved

Convert wstring to Unicode String

  • October 22, 2025
  • 2 replies
  • 346 views

I have a multi-language graphics project which requires the use of characters beyond the standard ASCII set.  I have not found a working method to convert C++ wstring to TouchGFX::Unicode.  I have attempted the following:

 

Unicode::strncpy(txtTitleBuffer, headerText.c_str(), buf_size1);  //No matching funtions...

Unicode::strncpy(txtTitleBuffer, headerText, buf_size1);             //No matching funtions...

 

Unicode::snprintf(txtTitleBuffer, buf_size1, "%s", headerText.c_str());       //Compiles without error but only shows 1st character.

Unicode::snprintf(txtPasswordTitleBuffer, buf_size1, "%s", headerText);  //Compiles without error but only shows ??? which is the default undefined font character.

 

If possible I would like to stay with the standard C++ type for the strings and convert as it is about to be displayed as manipulating TouchGFX::Unicode is a bit clunky.

Best answer by ferro

Hi, this works with C++20.

std::wstring ws = L"Hello";

std::u16string ws_to_u16s ( const std::wstring & ws )
{
	// wchar_t is 16-bit, so direct copy works.
 return std::u16string ( ws.begin (), ws.end () );
}


Unicode::snprintf ( txtTitleBuffer, buf_size1, "%s", ws_to_u16s ( ws ).data () );

 

2 replies

Associate II
October 22, 2025

I don't know about TouchGFX, but I assume it is related to standard C++.

 

Assuming you want to have a byte string which is UTF-8 encoded and TouchGFX::Unicode is such a thing:

Then it depends on your C++ version unfortunately. Up to C++ 17 at least this would be the way: https://en.cppreference.com/w/cpp/locale/codecvt.html

But it is deprecated starting with C++ 20 (though it might work probably). Then you could search for ICU (u_strToUTF8/u_strFromUTF8) - which I never used.

ferro
ferroBest answer
Lead
October 22, 2025

Hi, this works with C++20.

std::wstring ws = L"Hello";

std::u16string ws_to_u16s ( const std::wstring & ws )
{
	// wchar_t is 16-bit, so direct copy works.
 return std::u16string ( ws.begin (), ws.end () );
}


Unicode::snprintf ( txtTitleBuffer, buf_size1, "%s", ws_to_u16s ( ws ).data () );

 

ferro
Lead
October 22, 2025

And this works as well, on Windows, so no need for conversion it seems ?

std::wstring ws = L"Hello";

Unicode::snprintf ( txtTitleBuffer, buf_size1, "%s", ws.data () );