pack/unpack

The pack/unpack function implements “serialisation”, or the conversion of an object into a binary form that can be saved to a file or transmitted over the network to a process running in a different memory address space. The obvious strategy of simply sending sizeof(object) bytes starting at address &object doesn't work, as the object may contain members that are implemented using pointers -- eg dynamic strings or arrays. The obvious strategy will simply copy the contents of the pointer, which will not be valid in the destination's address space.

Using the recursive approach, simple data types can be serialised in the obvious way, or even transformed using into a machine independent form such as XDR. Data types such as arrays or strings can be handled in a type dependent fashion by supplying appropriate specialised definitions.

In this case, the pack_t type implements a buffer into/from which the data is packed/unpacked. It has public members char *data; int size which point to the buffer and its size, that can then be used for further functionality such as the checkpoint/restart functionality of Eco Lab.

There are 4 methods of using the pack function on an object --

  1. template <class T> pack_t& pack_t::operator<<(T&)
  2. template <class T> ::pack(pack_t&, string, T&)
  3. template <class T> ::pack(pack_t&, string, is_array, T*, int)
  4. void pack_t::packraw(char *,int)
The classdesc::string argument is not used, just pass "" to it. The third method above is a utility routine for packing arrays of objects, is_array is a dummy type, so just pass the object returned by the default constructor is_array(), then the final two arguments are the array pointer and size respectively. One could easily explicitly loop over the array elements using the first two methods. The last method is used to pack arbitrary byte data into the buffer. It differs from ::pack(pack_t&, string, is_array, char*, int) in that the latter packs a series of characters, which are usually 32 bit quantities. It is thus both more efficient than the latter, as well as providing a means to unpack data stored in packed char format.

xdr_pack is derived from pack_t. Instead of packing to native data representation, it uses XDR data representation, which is machine independent. The XDR_PACK macro symbol must be defined to enable this functionality, otherwise xdr_pack is synonymous with pack_t, allowing the code to be employed on machines that do not provide XDR functionality.

unpack_t is typedef'd to pack_t, and unpack_base.h is a link to pack_base.h.

In order to use the streaming operators << and >> you need to include the file pack_stream.h, after all the corresponding pack() definitions. This is automatically done by including classdesc_epilogue.h



Subsections