문제

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()));
도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top