QString to LPCSTR



  • Good day Qt,

    I'm working in a non-Unicode project on VS2012 and I need to convert a QString to LPCSTR. I have tried the following code:

    QString name = ...omitted for clarity.....;
    LPCSTR labelName = (LPCSTR)name.toLocal8Bit().constData();
    

    and I'm getting artifact.

    Can you help to figure out what's wrong with this code?

    Thanks in advance!

    Massi



  • As a guess I assume that 'name.toLocal8Bit()' produces a temporary copy of the original QString data. Once this goes out of scope the pointer is no longer valid. LPCSTR is the same as 'const char*'.

    If you copied the data to a local buffer (using memcpy for example) it should work. Maybe drop the variable completely (?). The best idea would be a separate QByteArray to hold a more perminant copy of the data:

    QByteArray temp_data;
    temp_data = name.toLocal8bit();
    
    LPCSTR labelName = temp_data.constData();  // casting shouldn't be needed
    


  • @Rondog Wonderful!!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.