Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. From wchar_t* to QString: QString::fromUtf16 or QString::fromWCharArray?
Forum Updated to NodeBB v4.3 + New Features

From wchar_t* to QString: QString::fromUtf16 or QString::fromWCharArray?

Scheduled Pinned Locked Moved General and Desktop
wchartqstringfromutf16fromwchararray
1 Posts 1 Posters 2.7k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • B Offline
    B Offline
    Bart_Vandewoestyne
    wrote on last edited by
    #1

    Today, my CppDepend complained about the following code:

    wchar_t* buffer = _wgetenv(L"USERNAME");
    if (buffer != NULL)
    {
        userId = QString::fromUtf16(buffer).toLower();
    }
    

    The problem is that buffer is wchar_t*, while QString::fromUtf16 expects a const ushort *.

    As I wasn't quite sure whether to replace the fromUtf16 function call with

    userId = QString::fromUtf16(reinterpret_cast<const ushort*>(buffer)).toLower();
    

    or with

    userId = QString::fromWCharArray(buffer).toLower();
    

    I wrote this little test program:

    https://github.com/BartVandewoestyne/Qt/blob/master/tests/qstring_from_wchar_t_array.cpp

    On Linux, wchar_t seems to be 4 bytes and there seems to be a difference between the two functions:

    sizeof(wchar_t) =  4 
    QString::fromUtf16(reinterpret_cast<const ushort*>(text)) => "F" 
    QString::fromWCharArray(text) => "FooBar"
    

    on Windows, wchar_t seems to be 2 bytes and there seems to be no difference:

    sizeof(wchar_t) =  2 
    QString::fromUtf16(reinterpret_cast<const ushort*>(text)) => "FooBar" 
    QString::fromWCharArray(text) => "FooBar"
    

    My conclusion would be that in this case, where I have to create a QString out of a wchar_t*, the safest and most portable way is to use QString::fromWCharArray(text). Is my conclusion correct, or am I overlooking something?

    Kind regards,
    Bart

    1 Reply Last reply
    0

    • Login

    • Login or register to search.
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Get Qt Extensions
    • Unsolved