From wchar_t* to QString: QString::fromUtf16 or QString::fromWCharArray?
-
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*
, whileQString::fromUtf16
expects a constushort *
.As I wasn't quite sure whether to replace the
fromUtf16
function call withuserId = 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 awchar_t*
, the safest and most portable way is to useQString::fromWCharArray(text)
. Is my conclusion correct, or am I overlooking something?Kind regards,
Bart