首先定义.proto文件描述数据结构,再用protoc生成C++代码,接着编译链接Protobuf库,最后通过SerializeTo/ParseFrom系列方法实现序列化与反序列化,适用于高效数据传输与存储。

在C++中使用Protobuf(Protocol Buffers)进行序列化和反序列化,需要先定义消息结构(.proto文件),然后通过protoc编译器生成C++代码,最后在程序中调用相应API完成数据的读写。整个过程清晰高效,适合高性能数据传输和存储场景。
首先创建一个.proto文件来描述你要序列化的数据结构。例如,定义一个person.proto:
syntax = "proto3";
message Person {
    string name = 1;
    int32 age = 2;
    string email = 3;
}
保存后使用protoc编译器生成C++类:
protoc --cpp_out=. person.proto
会生成person.pb.h和person.pb.cc两个文件,供C++项目使用。
立即学习“C++免费学习笔记(深入)”;
确保系统已安装Protobuf开发库。Ubuntu下可执行:
sudo apt-get install libprotobuf-dev protobuf-compiler
编译C++程序时需链接Protobuf库:
g++ main.cpp person.pb.cc -lprotobuf -o demo
创建Person对象并将其序列化为字符串或写入文件:
#include "person.pb.h"
#include <fstream>
int main() {
    Person person;
    person.set_name("Alice");
    person.set_age(30);
    person.set_email("alice@example.com");
    std::string buffer;
    if (!person.SerializeToString(&buffer)) {
        // 处理序列化失败
        return -1;
    }
    // 可将buffer写入文件或网络
    std::ofstream output("person.bin", std::ios::binary);
    person.SerializeToOstream(&output);
    output.close();
    return 0;
}
从文件或字符串中读取并恢复Person对象:
#include "person.pb.h"
#include <fstream>
int main() {
    Person person;
    std::ifstream input("person.bin", std::ios::binary);
    if (!person.ParseFromIstream(&input)) {
        // 处理解析失败
        return -1;
    }
    input.close();
    // 使用恢复的数据
    std::cout << "Name: " << person.name() << "\n";
    std::cout << "Age: " << person.age() << "\n";
    std::cout << "Email: " << person.email() << "\n";
    return 0;
}
基本上就这些。只要.proto文件不变,生成的类就能保证跨平台、前后兼容。注意处理IO错误和解析失败的情况,尤其在网络传输中要校验数据完整性。
以上就是c++++怎么使用Protobuf进行序列化和反序列化_c++ Protobuf序列化反序列化方法的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号