您好,登錄后才能下訂單哦!
在C++中,有許多輕量級(jí)的序列化庫(kù)可以幫助你處理數(shù)據(jù)的序列化和反序列化
示例:
#include <cereal/archives/binary.hpp>
#include <fstream>
struct MyData {
int x;
float y;
template<class Archive>
void serialize(Archive &archive) {
archive(x, y);
}
};
int main() {
// 序列化
std::ofstream os("data.bin", std::ios::binary);
cereal::BinaryOutputArchive archive_out(os);
MyData data_out{42, 3.14f};
archive_out(data_out);
// 反序列化
std::ifstream is("data.bin", std::ios::binary);
cereal::BinaryInputArchive archive_in(is);
MyData data_in;
archive_in(data_in);
}
示例:
// schema.fbs
table MyData {
x: int;
y: float;
}
// 編譯 schema.fbs 生成 C++ 代碼
// flatc --cpp schema.fbs
#include "schema_generated.h"
#include <iostream>
int main() {
// 序列化
flatbuffers::FlatBufferBuilder builder;
auto data_offset = schema::CreateMyData(builder, 42, 3.14f);
builder.Finish(data_offset);
// 反序列化
auto data_in = schema::GetMyData(builder.GetBufferPointer());
std::cout << "x: " << data_in->x() << ", y: " << data_in->y() << std::endl;
}
示例:
#include <msgpack.hpp>
#include <iostream>
#include <sstream>
struct MyData {
int x;
float y;
MSGPACK_DEFINE(x, y);
};
int main() {
// 序列化
MyData data_out{42, 3.14f};
std::stringstream ss;
msgpack::pack(ss, data_out);
// 反序列化
msgpack::unpacked unpacked;
msgpack::unpack(unpacked, ss.str().data(), ss.str().size());
MyData data_in = unpacked.get().as<MyData>();
std::cout << "x: " << data_in.x << ", y: " << data_in.y << std::endl;
}
這些庫(kù)都是輕量級(jí)的,易于集成和使用。你可以根據(jù)項(xiàng)目需求選擇合適的庫(kù)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。