[Qt-interest] howto convert QString to char*

Thiago Macieira thiago at kde.org
Wed Jul 14 09:35:36 CEST 2010


On Wednesday 14. July 2010 09.19.11 Matthias Pospiech wrote:
> Thiago Macieira schrieb:
> > If it doesn't have to persist, then usually it's enough to simply use
> > QByteArray's automatic casting to char*. So if the encoding you needed
> > was
> > 
> > Latin1, you'd write:
> > 	SomeDllFunction(string.toLatin1());
> 
> Unfortunately the compiler wont accept this:
> 
> error: conversion from 'QByteArray' to 'char*' is ambiguous
> note: candidates are: QByteArray::operator QNoImplicitBoolCast() const
> <near match>
> note:                 QByteArray::operator const void*() const <near match>
> note:                 QByteArray::operator const char*() const <near match>
> 
> The function requires a LPSTR (that is a char *). QByteArray however
> returns a const char *

If it requires a char*, not a const char*, it means it's going to modify the 
buffer.

So you should do this:

	QByteArray ba = str.toLatin1();
	SomeDllFunction(ba.data(), ba.length());

If it's not going to modify the buffer, it's just a bad API.

> A const_cast does not work, so the only thing that does work is
> 
>     const char *str3 = strMovement.toLatin1();
>     str = const_cast<char*>(str3);

const_cast does work. But you still have not understood the problem, which is 
that toLatin1() returns a temporary QByteArray. That temporary is destroyed at 
the end of the statement, unless you assign it to some variable, like I did 
above.

Your code doesn't do it, it simply asks the temporary for the address of its 
data. And then the temporary is destroyed, taking the data with it. THAT is 
why you get garbage.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Senior Product Manager - Nokia, Qt Development Frameworks
      PGP/GPG: 0x6EF45358; fingerprint:
      E067 918B B660 DBD1 105C  966C 33F5 F005 6EF4 5358
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 190 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20100714/f881894d/attachment.bin 


More information about the Qt-interest-old mailing list