Reputation: 53
I'm looking for the most simple and or elegant way to create a QBuffer in C++ Qt5.6 from void * data
and long data_size
.
I tried casting the void to a char pointer and using the QByteArray::fromRawData()
as well as using QDataStream
to fill a QByteArray
. In both cases I didn't succeed.
Upvotes: 0
Views: 2240
Reputation: 1304
Since you are asking for an elegant way to create a QBuffer from data and data_size, I would simply use this:
QBuffer buffer;
buffer.setData(static_cast<const char*>(data), data_size);
Note: this copies the memory pointed to by data
.
I have no idea why you are unable to succeed, maybe you forgot to add the data_size
as size argument for QByteArray::fromRawData
? In that case strlen(data)
would be used to calculate the size.
And if you are using something like this:
QByteArray byteArray = QByteArray::fromRawData(static_cast<const char*>(data), data_size);
QBuffer buffer(&byteArray);
Then the byteArray
must remain valid until the QBuffer is destroyed. And since QByteArray::fromRawData(...)
does not copy, the memory pointed to by data
must remain valid as well. Failing to meet that requirement would also explain any failure.
Upvotes: 1
Reputation: 49319
QByteArray::QByteArray(const char *data, int size)
will copy the data.
QByteArray::fromRawData(const char *data, int size)
will use the already existing data.
Depending on your implementation, not copying the data might end up being problematic.
After you have the data in a byte array, there are several ways to go, you can directly construct a buffer:
QBuffer(QByteArray *byteArray, QObject *parent = Q_NULLPTR)
or more likely, since you are playing audio, you might want to reusing the same buffer and use one of the following to refill it:
setBuffer(QByteArray *byteArray)
setData(const QByteArray &data)
Lastly, there is also void QBuffer::setData(const char *data, int size)
for which you don't even need the byte array step at all.
Lastly, remember that QBuffer
is an IO device - it needs to be opened in order for it to work. A quick test shows that it works as expected:
char data[] = {1, 2, 3};
void * vdata = data;
QBuffer buffer;
buffer.setData((char *)vdata, sizeof(data));
buffer.open(QIODevice::ReadOnly);
qDebug() << buffer.readAll(); // outputs "\x01\x02\x03"
Upvotes: 4