updating QByteArray contents via reinterpret_cast

119 Views Asked by At

Is it possible to update the contents of a QByteArray using reinterpret_cast or some other QT aliasing trick?

I have a data struct member that is wrapped in a std::unique_ptr (it is typically 12 bytes in length however sometimes it can be larger due to an array trailing field) - I need to be able to update the contents of this struct.

Due to the implicit sharing concepts in QByteArray this is tricky and I cannot find the right set of operations to mutate the underlying mpLastTxHeader member. The member is declared as:

//! Last sent header - used as template to send next headers
//! as it should always contain the last sent sequence number & timestamp
std::unique_ptr<QByteArray> mpLastTxHeader;

The member function that uses this QByteArray member variable currently makes a deep copy of the previous contents of the QByteArray (it happens to contain an RTP header with the last sent sequence # so this is why I need to mutate and save it before the next use). Ideally when I call 'rtpHeader->setSeqNum' the underlying mpLastTxHeader should be updated but I do not know how to do this.

// make a deep copy of the last sent RTP header (containing sequence# & timestamp)
const auto rawHeader = std::make_unique<QByteArray>(*mpLastTxHeader);
const auto rtpHeader = reinterpret_cast<rtp_hdr_t*>(rawHeader->data());
// create the RTP datagrams with incrementing sequence numbers and timestamps
while ((mpAudioCache->size() - mLastReadPos) >= gRAWAudioSize) {
    // reset the marker bit so it doesn't keep getting transmitted
    rtpHeader->m = 0u;
    // increment the sequence numbers
    rtpHeader->setSeqNum(rtpHeader->getSeqNum() + 1);
    // increment timestamp
    rtpHeader->setTimestamp(rtpHeader->getTimestamp() + mTSIncrement);
    // prefix the next block with the next rtp header
    QByteArrayList temp = {
        *rawHeader,
        mpAudioCache->read(gRAWAudioSize)
    };
    mTXBufferList.emplace_back(temp.join());
    mLastReadPos += gRAWAudioSize;
}
0

There are 0 best solutions below