将char与数据流一起复制到QbyteArray包含一些额外的字节

copying char to QbyteArray with datastream contains some extra bytes

本文关键字:包含一 字节 QbyteArray char 数据流 一起 复制      更新时间:2023-10-16

问题概述:
操作系统:Ubuntu

我使用qt实用程序从远程机器接收视频数据(远程机器使用gstreamer发送实时数据),并将数据写入端口,例如5000。

端口5000已绑定到另一个gstreamer实用程序。该实用程序监听端口5000并将数据转换为视频流。很明显,事情不太正常,我无法观看视频。所以我有两个问题:

1) 使用Qt实用程序,尽管端口绑定到gstreamer实用程序,但写入端口5000是否合法。

2) 我正在使用第三方库及其api从外部源接收数据。数据存储在字符数组中。若我将其转换为qbyterarray,那个么qbyterArray的大小和char缓冲区的大小相同。示例

rc = zco_receive_source(sdr, &reader, bytesToRead, buffer); // this is 3rd part function

      qDebug() << " copy buffer size =" << rc; // genrally this size is 1412
       QByteArray msgRecvd;
       msgRecvd = QByteArray(reinterpret_cast<char*>(buffer), rc);
        if(! msgRecvd.isEmpty() )
        {
            qDebug() << " size of msgRecv =" << msgRecvd.size();// again 1412 
            udpSock->writeDatagram( msgRecvd, QHostAddress::LocalHost, 5000 );
       }

但是,如果我使用QDataStream,那么QbyteArray会获得4个额外的字节。下方显示的代码

rc = zco_receive_source(sdr, &reader, bytesToRead, buffer); // this is 3rd part function

    qDebug() << " copy buffer size =" << rc; // genrally this size is 1412
    QByteArray msgRecvd;
    QDataStream dataStream( &msgRecvd, QIODevice::WriteOnly );
    dataStream.writeBytes( ( const char* )buffer, rc );
    if(! msgRecvd.isEmpty() )
    {
       qDebug() << " size of msgRecv =" << msgRecvd.size();// got 4 extra bytes .. size is 1415. why ???
       udpSock->writeDatagram( msgRecvd, QHostAddress::LocalHost, 5000 ); 
    }

我想知道为什么QbyteArray有额外的字符,我需要串行化数据才能将其转发到5000端口吗?

回答第二个问题:尝试QDataStream::writeRawData()。

表单Qt文档:

QDataStream & QDataStream::writeBytes(const char * s, uint len)
Writes the length specifier len and the buffer s to the stream and returns a reference to the stream.
The len is serialized as a quint32, followed by len bytes from s. Note that the data is not encoded.