January 28, 2012

Davita Davita
Lab Rat
73 posts

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:

  1.     unsigned int pointer = 0;
  2.     const int IPC_MSG_LEN = 500;
  3.     const int IPC_MSG_HEADER = 200;
  4.     const int SOMETHING = 1443;
  5.     char api = 55;
  6.  
  7.     char msg[IPC_MSG_LEN] = {0};
  8.     memcpy_s(msg, IPC_MSG_LEN, &IPC_MSG_HEADER, sizeof(int));
  9.     pointer = sizeof(unsigned int);
  10.     memcpy_s(&msg[pointer], IPC_MSG_LEN - pointer, &api, sizeof(char));
  11.     ++pointer;
  12.     memcpy_s(&msg[pointer], IPC_MSG_LEN - pointer, &SOMETHING, sizeof(int));
  13.  
  14.     QByteArray arr(msg, IPC_MSG_LEN);
  15.     QDataStream ds(&arr, QIODevice::ReadOnly);
  16.     qint32 header = 0, aa = 0;
  17.     qint8 t_api = 0;
  18.     ds >> header; //Doesn't work
  19.     ds >> t_api; //Works
  20.     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.

1 reply

January 29, 2012

Volker Volker
Robot Herder
5428 posts

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):

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

A platform independent way would be:

  1. #include <QSysInfo>
  2.  
  3. ds.setByteOrder(QSysInfo::ByteOrder);

 
  ‹‹ Virtual Camera Device      Making a checkbox in a QTableView useable? ››

You must log in to post a reply. Not a member yet? Register here!