C Library Serialization and Deserialization Guide Serialization: Creates an output stream and converts it to an archive format. Serialize objects into archive. Deserialization: Creates an input stream and restores it from archive format. Deserialize objects from the archive. Practical example: Serialization: Creating an output stream. Create an archive object. Create and serialize objects into the archive. Deserialization: Create an input stream. Create an archive object. Create objects and deserialize them from the archive.
Introduction
Serialization and Deserialization Conversion is the process of converting an object to a byte stream and reconstructing the object from the byte stream. In C, you can use function libraries to implement this functionality. This article will introduce how to use the binary archive function library (boost::archive) for serialization and deserialization.
Serialization
In order to serialize an object, we need to create an output stream and use the boost::archive::binary_oarchive
class to Convert to archive format.
#include <boost/archive/binary_oarchive.hpp> // 创建一个输出流 std::ofstream output("myfile.dat"); // 创建一个存档对象 boost::archive::binary_oarchive archive(output); // 将对象序列化到存档中 archive << myObject;
Deserialization
To deserialize an object we need to create an input stream and use boost::archive::binary_iarchive
Class to restore it from archive format.
#include <boost/archive/binary_iarchive.hpp> // 创建一个输入流 std::ifstream input("myfile.dat"); // 创建一个存档对象 boost::archive::binary_iarchive archive(input); // 从存档中反序列化对象 MyObject loadedObject; archive >> loadedObject;
Practical case
Suppose we have a class named Person
, which has name
and age
Two attributes. Here's how to serialize and deserialize it:
Serialization
#include <boost/archive/binary_oarchive.hpp> // 创建一个输出流 std::ofstream output("person.dat"); // 创建一个存档对象 boost::archive::binary_oarchive archive(output); // 创建一个 Person 对象 Person person("John", 30); // 将 Person 对象序列化到存档中 archive << person;
Deserialization
#include <boost/archive/binary_iarchive.hpp> // 创建一个输入流 std::ifstream input("person.dat"); // 创建一个存档对象 boost::archive::binary_iarchive archive(input); // 创建一个 Person 对象 Person loadedPerson; // 从存档中反序列化 Person 对象 archive >> loadedPerson; std::cout << loadedPerson.getName() << ", " << loadedPerson.getAge() << std::endl;
Output
John, 30
The above is the detailed content of How does the C++ function library perform serialization and deserialization?. For more information, please follow other related articles on the PHP Chinese website!