0

In C++ I have data structure something like this:

struct Data 
{ 
int N; 
double R; 
char Name[20];
};

This Data I have to send over from a client to server on a different system (I have to send an array of Data structs, but i could send it just one by one). I would like to send it over as binary data, so that I could extract the data on the other end put it inside the same struct type.

If both (client and sever) are compiled with the same compiler the sizeof(Data) and all bit paddings within structure would be the same. But as server is 64bit running Linux and client could be even 32bit windows, the ordering of data within Data could be different.

Am I Right? What would be the best way of dealing with this the problem?

1
  • I'd look at something like protobuf Commented Aug 29, 2012 at 9:33

3 Answers 3

5

Assuming that all clients and servers will always be built with the same compiler for same architecture and OS is almost always a bad idea. It is better to write code that explicitly packs and unpacks the member of the structure as a stream of bytes with a specified ordering, or converts the data to non-binary formats (e.g. JSON or XML) that can be parsed on the other side.

Sign up to request clarification or add additional context in comments.

1 Comment

Supporting the "bad idea": have a look at CORBA. There is big group of people having gone through a lot of pain, in order to get this problem coped with. Not that you should use that in particular, but just to paint a picture of why it is such a bad idea.
3

You could use Boost.Serialization to marshal/unmarshal (i.e. transform your data from your source computer format to one that is suitable for transmission, and from that format to the one used by your destination computer) your data and Boost.Asio to handle communication.

Comments

0

Proper protocol definition would help you to solve this issue. Have a fixed length header followed by variable length data.

Something like this

Header***

[DataSize] - 2 bytes

[MSG ID] - 1 byte

Packet**

[N] - 4 bytes

[R] - 8 bytes

[Len] - 2 bytes

[Name] - Len bytes

read the bytes and fill the structure

1 Comment

Also be sure to specify byte-ordering for the multi-byte fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.