問題描述
我有一個小的對象層次結構,我需要通過套接字連接序列化和傳輸這些對象.我需要序列化對象,然后根據(jù)它的類型反序列化它.在 C++ 中有沒有一種簡單的方法可以做到這一點(就像在 Java 中一樣)?
是否有 C++ 序列化在線代碼示例或教程?
明確地說,我正在尋找將對象轉換為字節(jié)數(shù)組,然后再轉換回對象的方法.我可以處理套接字傳輸.
談序列化,boost 序列化 API.至于通過網(wǎng)絡傳輸序列化數(shù)據(jù),我要么使用伯克利套接字,要么使用 asio 庫.>
如果要將對象序列化為字節(jié)數(shù)組,可以按以下方式使用 boost 序列化器(取自教程站點):
#include #include 類 gps_position{私人的:友元類 boost::serialization::access;模板<類存檔>void serialize(Archive & ar, const unsigned int version){和度;和分鐘;和秒;}整數(shù)度;整數(shù)分鐘;浮動秒;民眾:gps_position(){};gps_position(int d, int m, float s) :度(d)、分(m)、秒(s){}};
實際的序列化非常簡單:
#include std::ofstream ofs("filename.dat", std::ios::binary);//創(chuàng)建類實例const gps_position g(35, 59, 24.567f);//保存數(shù)據(jù)到存檔{boost::archive::binary_oarchive oa(ofs);//將類實例寫入存檔oa<<G;//調(diào)用析構函數(shù)時存檔和流關閉}
反序列化的工作方式類似.
還有一些機制可以讓您處理指針的序列化(復雜的數(shù)據(jù)結構,如 tres 等沒有問題),派生類,您可以在二進制和文本序列化之間進行選擇.此外,所有 STL 容器都是開箱即用的.
I have a small hierarchy of objects that I need to serialize and transmit via a socket connection. I need to both serialize the object, then deserialize it based on what type it is. Is there an easy way to do this in C++ (as there is in Java)?
Are there any C++ serialization online code samples or tutorials?
EDIT: Just to be clear, I'm looking for methods on converting an object into an array of bytes, then back into an object. I can handle the socket transmission.
Talking about serialization, the boost serialization API comes to my mind. As for transmitting the serialized data over the net, I'd either use Berkeley sockets or the asio library.
Edit:
If you want to serialize your objects to a byte array, you can use the boost serializer in the following way (taken from the tutorial site):
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
class gps_position
{
private:
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;
public:
gps_position(){};
gps_position(int d, int m, float s) :
degrees(d), minutes(m), seconds(s)
{}
};
Actual serialization is then pretty easy:
#include <fstream>
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 works in an analogous manner.
There are also mechanisms which let you handle serialization of pointers (complex data structures like tress etc are no problem), derived classes and you can choose between binary and text serialization. Besides all STL containers are supported out of the box.
這篇關于你如何在 C++ 中序列化一個對象?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!