Home > Backend Development > C++ > How Does Boost.Serialization Handle Object Serialization in C ?

How Does Boost.Serialization Handle Object Serialization in C ?

DDD
Release: 2025-01-03 06:20:39
Original
568 people have browsed it

How Does Boost.Serialization Handle Object Serialization in C  ?

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 &degrees;
        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) {}
};
Copy after login

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
}
Copy after login

Deserialization is similar:

std::ifstream ifs("filename.dat", std::ios::binary);

gps_position g;

{
    boost::archive::binary_iarchive ia(ifs);
    ia >> g;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template