Object Serialization in C
Serialization allows for converting objects into a byte array, enabling their transmission and recreation. C , unlike Java, does not offer an inherent mechanism for this process. However, libraries such as Boost provide a comprehensive solution.
The Boost serialization API facilitates the conversion of objects into byte arrays. Consider the following code snippet:
#include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> class gps_position { public: friend class boost::serialization::access; template <class Archive> void serialize(Archive &ar, const unsigned int version) { ar °rees; ar &minutes; ar &seconds; } int degrees; int minutes; float seconds; gps_position(){}; gps_position(int d, int m, float s) : degrees(d), minutes(m), seconds(s) {} };
To serialize an object, follow these steps:
std::ofstream ofs("filename.dat", std::ios::binary); // create class instance const gps_position g(35, 59, 24.567f); // save data to archive { boost::archive::binary_oarchive oa(ofs); // write class instance to archive oa << g; // archive and stream closed when destructors are called }
Deserialization is similar:
std::ifstream ifs("filename.dat", std::ios::binary); gps_position g; { boost::archive::binary_iarchive ia(ifs); ia >> g; }
Boost serialization offers flexible options, including support for serialization of pointers, derived classes, and binary and text modes. STL containers are also handled effortlessly.
The above is the detailed content of How Does Boost.Serialization Handle Object Serialization in C ?. For more information, please follow other related articles on the PHP Chinese website!