How to use QDataStream::readBytes()

丶灬走出姿态 提交于 2021-01-27 07:51:46

问题


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()?


回答1:


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.



来源:https://stackoverflow.com/questions/29636833/how-to-use-qdatastreamreadbytes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!