0

I use in my project QString but In some cases I have to transfer this to an external SDK, that expect null terminated const char*. For this I use:

QByteArray folderName = ((QDataItem*)(*it))->GetName().toUtf8();
folderName.append('\0');
dir.lpszDir = folderName;

Is casting the right way here? I assume I have to cast it with dynamic cast? Or is there a better way to bring the "GetName()" to a const char*?

ingo
  • 776
  • 1
  • 10
  • 25
  • I don't see `QDataItem` in the [list of Qt classes](https://doc.qt.io/qt-5/classes.html#d). What is it / where does it come from? – acraig5075 Jan 22 '20 at 06:25
  • `folderName.constData()` may be right option, if the lifetime matches. – hyde Jan 22 '20 at 06:39
  • @hyde ... QT tells me that it is not compatible. Assign qchar * to const char* – ingo Jan 22 '20 at 07:33
  • @ingo You're omitting something relevant now, because [*QByteArray::constData()*](https://doc.qt.io/qt-5/qbytearray.html#constData) definitely returns just that, `const char*`. – hyde Jan 22 '20 at 07:45
  • 2
    Does this answer your question? [QString to char\* conversion](https://stackoverflow.com/questions/2523765/qstring-to-char-conversion) – Mohammed Deifallah Jan 22 '20 at 07:52

1 Answers1

0

I did it like that in my project.

 QString stringMessage = "something";
 char* charMessage = new char[stringMessage.size() + 1];

 std::memcpy(charMessage, stringMessage.toLocal8Bit().data(), static_cast<size_t>(stringMessage.size() + 1));
Rufledore
  • 33
  • 1
  • 6