PDA

View Full Version : Use QString::data() Pointer as Pointer to wchar_t/WCHAR



franku
4th December 2010, 14:36
Hi There, can comeone give me a hint on how to use the QString::data() ?

As I know from the Documentation Qt stores strings internally as Unicode. So my question is: Can I use the Pointer returned by data() as a pointer to WCHAR (wchar_t) ?


static void toWideChar(const QString& qsIn, LPWSTR* wideCharOut)
{
Q_ASSERT(!qsIn.isEmpty());
*wideCharOut = (LPWSTR)qsIn.data();
}


I found in qstring.h the ushort data pointer:


struct Data {
QBasicAtomicInt ref;
int alloc, size;
ushort *data;
ushort clean : 1;
ushort simpletext : 1;
ushort righttoleft : 1;
ushort asciiCache : 1;
ushort capacity : 1;
ushort reserved : 11;
ushort array[1];
};

This Pointer will be returned as a reinterpretet QChar Pointer:

inline const QChar *QString::data() const
{ return reinterpret_cast<const QChar*>(d->data); }


All other attempts (i.e. toWCharArray()) seem to copy all the content and this is what I try to avoid.

Any Commtents (however, even good practive-hints) ? Thanks.

Zlatomir
4th December 2010, 17:20
They both (WCHAR and QChar) are unsigned short integers (2 bytes), so this should work:


QString str("Test String");
WCHAR* wcar = (WCHAR*)(str.constData());
std::wcout << wcar << '\n';


For read-only access, constData() is faster because it never causes a deep copy to occur.

Quoted from here (http://doc.qt.nokia.com/latest/qstring.html#data), so use constData member function.

Note that this pointer is valid only until you modify the original QString.