QDataStream won't work with custom crafted char array



  • Hi guys. I have an application which consists of two primary modules. One is written in C, uses standard C runtime library and one written in Qt C++. They communicate with each other with IPC. C module creates a char array, fills it with data and sends to the module written in Qt. I want to deserialize received data using QDataStream, but my efforts didn't yield any result yet. Here's a simple example what I'm trying to achieve:

    @ unsigned int pointer = 0;
    const int IPC_MSG_LEN = 500;
    const int IPC_MSG_HEADER = 200;
    const int SOMETHING = 1443;
    char api = 55;

    char msg[IPC_MSG_LEN] = {0};
    memcpy_s(msg, IPC_MSG_LEN, &IPC_MSG_HEADER, sizeof(int));
    pointer = sizeof(unsigned int);
    memcpy_s(&msg[pointer], IPC_MSG_LEN - pointer, &api, sizeof(char));
    ++pointer;
    memcpy_s(&msg[pointer], IPC_MSG_LEN - pointer, &SOMETHING, sizeof(int));
    
    QByteArray arr(msg, IPC_MSG_LEN);
    QDataStream ds(&arr, QIODevice::ReadOnly);
    qint32 header = 0, aa = 0;
    qint8 t_api = 0;
    ds >> header; //Doesn't work
    ds >> t_api; //Works
    ds >> aa; //Doesn't work
    

    @

    As you can see, the code is pretty simple, but header and aa variables are deserialized to a random number. However t_api (one byte variable) has correct value assigned.
    So what's the problem with this code? Does QDataStream uses a private data format which is not compatible with the one I'm using? Should I write my own QIODevice implementation or there is a quick fix I'm not aware of? :)
    Thanks, I appreciate your help.



  • It's most probably a byte order issue. Windows uses little endian, whereas QDataStream by default uses big endian. You should add this right after the data stream instantiation (after line 15):

    @
    ds.setByteOrder(QDataStream::LittleEndian);
    @

    A platform independent way would be:

    @
    #include <QSysInfo>

    ds.setByteOrder(QSysInfo::ByteOrder);
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.