dimanche 29 mars 2015

QDataStream and a custom struct

I am trying to serialize a simple discovery packet into a QDataStream.


Packet:



class handshakePacket
{
public:
quint32 magic_packet;
quint32 port;
QString computer_name;
};


Serialization operators overload:



QDataStream &operator<<(QDataStream &out, const handshakePacket &packet)
{
out << packet.magic_packet << packet.port << packet.computer_name;
return out;
}
QDataStream &operator>>(QDataStream &in, handshakePacket &packet)
{
in >> packet.magic_packet >> packet.port >> packet.computer_name;
return in;
}


Test code:



int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

QDataStream datastream;
handshakePacket hpb;
handshakePacket hpa;

hpa.magic_packet = 0x12341234;
hpa.port = 12345;
hpa.computer_name = QString("hello");
datastream << hpa;
datastream >> hpb;

if(hpb.magic_packet != hpa.magic_packet) qDebug()<<"fail on magic packet";
if(hpb.computer_name != hpa.computer_name) qDebug()<<"Fail on computer name";

return a.exec();
}


"hpb" is always equal to zero and both asserts fail.


I've been trying for a few hours to make this work. I tried to make the handshakePacket class a struct, making it's << and >> overloads friends, making the QDataStream write into a QByteArray, reviewed my overload signatures a few times, making sure the << and the >> are pointing in the right way...


Thanks in advance.


EDIT: Found a solution. I need to rewind the QDataStream:



int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

QByteArray qba;
QDataStream datastream(&qba, QIODevice::ReadWrite);
handshakePacket hpb;
handshakePacket hpa;

hpa.magic_packet = 0x12341234;
hpa.port = 12345;
hpa.computer_name = QString("hello");
datastream << hpa;
datastream.device()->seek(0);
qDebug() << "atend: "<<datastream.atEnd() ;
datastream >> hpb;

if(hpb.magic_packet != hpa.magic_packet) qDebug()<<"fail on magic packet";
if(hpb.computer_name != hpa.computer_name) qDebug()<<"Fail on computer name";

return a.exec();
}


Is there a way to do that without using a QByteArray?


Aucun commentaire:

Enregistrer un commentaire