Search code examples
c++cmarshallingpacking

Can marshalling or packing be implemented by unions?


In beej's guide to networking there is a section of marshalling or packing data for Serialization where he describes various functions for packing and unpacking data (int,float,double ..etc).

It is easier to use union(similar can be defined for float and double) as defined below and transmit integer.pack as packed version of integer.i, rather than pack and unpack functions.

union _integer{
  char pack[4];
  int i;
}integer;
  1. Can some one shed some light on why union is a bad choice?

  2. Is there any better method of packing data?


Solution

  • Different computers may lay the data out differently. The classic issue is endianess (in your example, whether pack[0] has the MSB or LSB). Using a union like this ties the data to the specific representation on the computer that generated it.

    If you want to see other ways to marshall data, check out the Boost serialization and Google protobuf.