[Qt-interest] howto convert QString to char*

Thiago Macieira thiago at kde.org
Tue Jul 13 18:32:54 CEST 2010


On Tuesday 13 July 2010 17:45:57 Matthias Pospiech wrote:
> I am using the following:
> 
>     char * toChar(const QString str)
>     {
>         QByteArray ba = str.toLatin1();
>         return  ba.data();
>     }
> 
> the bytearray contains usefull data,
> however the value returned by data() is very useless.
> Is this because ba is destroyed at the end of toChar?
> If so, what would you recommend to make such a conversion?
> 
> In my code I use this to write
> 
> QString sendSignal = "1.23 1" // this is set somewhere else
> char * str = toChar(sendSignal);
> ...
> // dll functions requiring a char* string...

First of all, you have to remember one important difference between QString and 
char*: QString stores data in UTF-16, while char* is just arbitrary 8-bit 
data.

So to convert from QString to char*, the first thing you need to know is the 
encoding. What encoding is the data that you want?

If it's Latin 1 (ISO-8859-1), you can use toLatin1. If it's UTF-8, you can use 
toUtf8(). If it's the locale encoding, you can use toLocal8Bit(). Otherwise, 
you should use QTextCodec to find the appropriate codec to convert.

Once you know the encoding, you can get a QByteArray with the data that you 
want. QByteArray is a class that holds a char* and manages its memory.

If the value must persist, you should either keep the QByteArray, or you 
should copy it before the QByteArray goes out of scope.

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());

That's all.

-- 
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/20100713/810323c4/attachment.bin 


More information about the Qt-interest-old mailing list