[Qt-interest] howto convert QString to char*

Matthias Pospiech matthias.pospiech at gmx.de
Wed Jul 14 09:19:11 CEST 2010


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 *
A const_cast does not work, so the only thing that does work is

    const char *str3 = strMovement.toLatin1();
    str = const_cast<char*>(str3);


This the whole code:

void QMicosPolluxController::moveAbsoluteAutoReply(double movement)
{
    d->currentTargetPosition = movement;

    QString strMovement = doubleToQString(movement);
    ProcessStringValues(strMovement);

    char *str = "";
    str = const_cast<char*>(strMovement.toLatin1().data());
    str = const_cast<char*>(strMovement.toAscii().data());
    str = const_cast<char*>(strMovement.toStdString().data());
    const char *str3 = strMovement.toLatin1();
    str = const_cast<char*>(str3);

    char *str2 ="1.234";
    d->dll.MoveAbsoluteAutoReplyA(str, d->axis);
}

I tested almost all examples given in this thread, but they all result 
in the same error.
The original QString has correct values. Here is the complete output of 
the debugger:

strMovement: "1.0000"
str: 0x9583850 
"\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\a"
str: 0x9583ae8 
"\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\a"
str: 0x957ccbc 
"\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376#"
str3: 0x9583ae8 
"\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\a"
str: 0x9583ae8 
"\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\356\376\a"
str2: 0x67a5e038 "1.234"

everything compiled with mingw. If I compile (using QtCreator) with 
msvc-2005, then the results are the same, but the debugger does not show 
the value of the QString anymore.

I also did several time a complete recompilation. Now I do not really 
know what to do next...

Matthias



More information about the Qt-interest-old mailing list