PDA

View Full Version : Convert QByteArray to object and vice versa



DiamonDogX
20th July 2009, 17:14
I have a data structure:


typedef struct
{
QString IpAddress;
int Port;
} VideoSource;

Q_DECLARE_METATYPE( VideoSource )

All I want to do is be able to convert this to a byte array in order to send on a socket, and get the object back (deserialize) on the other end. So I am doing this:


int videoSourceMetaTypeId = qRegisterMetaType< VideoSource >();
...
...
VideoSource vs;
vs.IpAddress = "127.0.0.1";
vs.Port = 5678;
QVariant videoSourceAsVariant;
videoSourceAsVariant.setValue( vs );
QByteArray videoSourceBytes = videoSourceAsVariant.toByteArray();
int numBytes = videoSourceBytes.count(); // this is 0

Not sure why the byte array's size ends up being 0.
So how do I get the object back? Was trying this but obviously it's wrong...


QVariant testVar( videoSourceBytes );
if( testVar.canConvert< VideoSource >() ) // returns false
{
VideoSource testVs = testVar.value< VideoSource >();
}

wysota
20th July 2009, 19:21
It's because QVariant doesn't know how to convert your object to byte array and as far as I remember there is no way to teach it do it.

What you should do is reimplement operators (<< and >>) for QDataStream to be able to stream your object into a datastream that can operate on a byte array.

DiamonDogX
20th July 2009, 20:06
Ok. I am going to work on that. Do you know why this doesn't compile?

VideoSource.h:


#ifndef VideoSource_h_
#define VideoSource_h_

#include <QString>
#include <QDataStream>

#pragma pack 1
typedef struct
{
QString IpAddress;
quint16 Port;
} VideoSource;

QDataStream & operator<< ( QDataStream & stream, const VideoSource & vs );
QDataStream & operator>> ( QDataStream & stream, VideoSource & vs );

Q_DECLARE_METATYPE( VideoSource )

#endif


VideoSource.cpp:


#include "VideoSource.h"

QDataStream & operator<< ( QDataStream & stream, const VideoSource & vs )
{
return stream;
}

QDataStream & operator>> ( QDataStream & stream, VideoSource & vs )
{
return stream;
}


I get errors like:
Error 2 error C3646: 'QDataStream' : unknown override specifier
Error 3 error C2143: syntax error : missing ';' before '&'
Error 4 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error 5 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error 6 error C2556: 'int &operator <<(QDataStream &,const VideoSource &)' : overloaded function differs only by return type from 'QDataStream &operator <<(QDataStream &,const VideoSource &)'
Error 7 error C2371: 'operator <<' : redefinition; different basic types

drescherjm
20th July 2009, 20:28
Looks like you need:

#include <QDataStream>



I see you have that in your header file.

[EDIT2] Whats with the ; on line 9 of your header file [EDIT2]

DiamonDogX
20th July 2009, 21:07
Took out the following line and it worked:

Q_DECLARE_METATYPE( VideoSource )