How to convert a structure in to char* form before writing to socket?
Asked
Active
Viewed 2,217 times
3 Answers
4
Use QDataStream. It has the advantage of handling endiannes (byte order) and serialization of Qt classes. Simply converting a structure to char* can cause a lot of problems including byte order, compiler padding etc. I suggest using a stream instead.

O.C.
- 6,711
- 1
- 25
- 26
-
QDataStream dosent support structure like: out<
– anj May 05 '11 at 08:39 -
2Read http://stackoverflow.com/questions/2473300/overloading-the-qdatastream-and-operators-for-a-user-defined-type to see how you can make your structure serializable if you want to go this way – O.C. May 05 '11 at 08:51
-
definatly i will like to go this way, if i get a solution, because working with QDataStream is much easier then Char* – anj May 05 '11 at 09:02
1
Is it just:
char *ptr = (char*)&myStructObject;
?
Or what do you mean?

Andrew
- 24,218
- 13
- 61
- 90
-
ya i mean this only, and if a member of myStructObjet, contain pointer to another structure, so could it it self, comes in this, car* buffer – anj May 05 '11 at 08:25
-
The receiver will not be able to dreference pointers, which have only a meaning in the context of your program. If your structure contains pointers you need to convert it to a new structure, which hold the values instead of the pointers – Gunther Piez May 05 '11 at 08:29
-
1@anjali: If you want to pass your structure through a socket then it is a good idea to add an >> operator which will take a QDataStream & as an argument. And this method will push your structure to the stream attached to your socket. Also you can create a constructor for you structure that will take QDataStream & as an argument and build your structure from it. It will useful when you will have to decode the data came from the socket. – Andrew May 05 '11 at 08:58
-
@angili: no, because if you have pointers in your structure they will become invalid on receiver's side. So you have manually create the buffer with all neccesary information to restore your structure on the receiver's side – Andrew May 05 '11 at 09:53