Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest method to get "const wchar_t*" from QString

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()));
like image 993
A.Danesh Avatar asked Apr 17 '14 04:04

A.Danesh


1 Answers

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.

like image 62
Jan Hudec Avatar answered Oct 24 '22 08:10

Jan Hudec