Question

I want to pass a QString variable to a function with const wchar_t* argument.

Safe solution is:

void foo(const wchar_t*);
QString x = "test";
foo(x.toStdWString().c_str());

but it has overhead of converting to wstring. Is there any faster solution?

How about this solution? Is it safe and portable?

foo(reinterpret_cast<const wchar_t*>(x.constData()));
Was it helpful?

Solution

No, the reinterpret cast is not safe and will not work on some platforms where the encoding is different. QChar is 16-bit and the internal encoding is UTF-16, but on Linux wchar_t is 32-bit UCS-4 encoding.

The cast would happen to work (it's still undefined behaviour, but msc++ does not currently do anything that would break it) on Windows where wchar_t is forever stuck at 16 bit, but the point of using Qt is being portable, right?

Note, that the conversion via std::wstring is as efficient as you can get. Given the difference in encoding memory has to be allocated once, which is managed by the std::wstring (the return copy can be elided even in C++98) and std::wstring::c_str() is a trivial getter.

OTHER TIPS

If x.constData gives you data addressable as const wchar_t*, you won't need a cast.

Any situation which won't compile without a cast, is badly broken (illegal aliasing and most likely also incompatible encoding).

It looks like the correct way is x.utf16() (no cast), and even then only when wchar_t is unsigned short. See http://qt-project.org/doc/qt-4.8/qstring.html#utf16

QString is always UTF-16, so if wchar_t isn't, then there is no method without conversion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top