[Qt-interest] howto convert QString to char*
Andrew Hodgkinson
ahodgkinson at endurancetech.co.uk
Thu Jul 15 14:27:35 CEST 2010
On 15/07/2010 06:06, Ivan Kharin wrote:
> char *qStringCopy( const QString& s )
> {
> return strdup( s.toLocal8Bit().constData() );
> }
I was going to post something similar to that very early in the thread,
but it's not all that helpful given the way the original poster wants to
use it, or indeed, the way that most people would probably want to use
the function. This indicates that it's not a well designed API. It's not
the world's most efficient piece of code either, given it ends up copying
strings all over the place.
Consider a typical use case where we want to pass a 'C' string equivalent
of some QString into a few functions.
someCStringHandler ( qStringCopy( someQString ) );
someOtherFunction ( qStringCopy( anotherString ) );
aThirdFunction ( qStringCopy( thirdString ) );
We've just leaked three strings. The caller is being given a permanently
allocated block from the malloc heap, so the caller MUST free this block.
Further, although most Linux variants cannot ever return NULL from
'malloc', the process instead simply being unceremoniously killed if all
RAM is exhausted, the Standard says that NULL may be returned from
'malloc' if allocation fails. Some operating systems will do this, so you
need to handle it.
Thus, the above code becomes very clumsy:
char * cStr1 = qStringCopy( someQString );
char * cStr2 = qStringCopy( anotherString );
char * cStr3 = qStringCopy( thirdString );
if ( cStr1 ) someCStringHandler( cStr1 );
else // Handle allocation failure
if ( cStr2 ) someOtherFunction( cStr2 );
else // Handle allocation failure
if ( cStr3 ) aThirdFunction( cStr3 );
else // Handle allocation failure
free( cStr1 );
free( cStr2 );
free( cStr3 );
At least we could start to tidy it up by throwing an exception in the
qStringCopy function if the allocation failed, but you still have to keep
a record of the returned pointer to give to 'free()' later. Trying to
work around this basic API problem within the constraints of the C/C++
language and its handling of objects on the stack is the reason why the
answers to the original poster's request became so complicated.
--
Andrew Hodgkinson, Endurance Technology
Land line: 01223 369 408, mobile: 07855 866 780
Registered Office: 5 Marine Drive West, Bognor Regis, W. Sussex, PO21 2QA
More information about the Qt-interest-old
mailing list