Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QString to LPCSTR
Forum Updated to NodeBB v4.3 + New Features

QString to LPCSTR

Scheduled Pinned Locked Moved Solved General and Desktop
3 Posts 2 Posters 2.3k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • MassiM Offline
    MassiM Offline
    Massi
    wrote on last edited by
    #1

    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

    Software Design Engineer at Ford - Canada

    1 Reply Last reply
    0
    • R Offline
      R Offline
      Rondog
      wrote on last edited by
      #2

      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
      
      1 Reply Last reply
      5
      • MassiM Offline
        MassiM Offline
        Massi
        wrote on last edited by
        #3

        @Rondog Wonderful!!

        Software Design Engineer at Ford - Canada

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved