5

According to the documentation for readBytes() (in Qt 5.4's QDataStream), I would expect the following code to copy the input_array into newly allocated memory and point raw at the copy:

QByteArray input_array{"\x01\x02\x03\x04qwertyuiop"};
QDataStream unmarshaller{&input_array, QIODevice::ReadOnly};

char* raw;
uint length;
unmarshaller.readBytes(raw, length);

qDebug() << "raw null? " << (raw == nullptr) << " ; length = " << length << endl;

...but the code prints raw null? true ; length = 0, indicating that no bytes were read from the input array.

Why is this? What am I misunderstanding about readBytes()?

Kyle Strand
  • 15,941
  • 8
  • 72
  • 167
  • The `QByteArray` constructor needs a nul terminated char array if you don't specify the size. – cmannett85 Apr 14 '15 at 21:33
  • @cmannett85 Ah, thanks. But if I read off a series of `quint8`s using `>>` first, I get the expected `1`, `2`, `3`, `4`, which seems to imply that I am indeed constructing the expected QByteArray....right? – Kyle Strand Apr 14 '15 at 21:45
  • @cmannett85 Also, I can print the QByteArray with `qDebug()`. – Kyle Strand Apr 14 '15 at 21:47
  • @cmannett85 Finally, adding `\0` at the end of the `input_array` constructor string doesn't appear to change the code's behavior. – Kyle Strand Apr 14 '15 at 21:54

1 Answers1

5

The documentation does not describe this clearly enough, but QDataStream::readBytes expects the data to be in a certain format: quint32 part which is the data length and then the data itself.

So to read data using QDataStream::readBytes you should first write it using QDataStream::writeBytes or write it any other way using the proper format.

An example:

QByteArray raw_input = "\x01\x02\x03\x04qwertyuiop";

QByteArray ba;

QDataStream writer(&ba, QIODevice::WriteOnly);
writer.writeBytes(raw_input.constData(), raw_input.length());

QDataStream reader(ba);

char* raw;
uint length;
reader.readBytes(raw, length);

qDebug() << "raw null? " << (raw == NULL) << " ; length = " << length << endl;

Also you can use QDataStream::readRawData and QDataStream::writeRawData to read and write arbitrary data.

hank
  • 9,553
  • 3
  • 35
  • 50