12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
编程知识 时间:2024-12-04 13:10:33
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
在C++中使用protobuf,首先需要定义一个.proto文件来描述消息的结构,然后使用protobuf的编译器生成对应的C++代码。接着可以在C++程序中使用生成的代码来序列化和反序列化消息
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
在C++中使用protobuf,首先需要定义一个.proto文件来描述消息的结构,然后使用protobuf的编译器生成对应的C++代码。接着可以在C++程序中使用生成的代码来序列化和反序列化消息。
以下是一个简单的使用protobuf的示例:
syntax = "proto3";message Person {string name = 1;int32 age = 2;repeated string hobbies = 3;}
protoc --cpp_out=. person.proto
#include "person.pb.h"#include <fstream>int main() {Person person;person.set_name("Alice");person.set_age(30);person.add_hobbies("Reading");person.add_hobbies("Swimming");// 序列化消息std::fstream output("person.pb", std::ios::out | std::ios::binary);person.SerializeToOstream(&output);// 反序列化消息Person new_person;std::fstream input("person.pb", std::ios::in | std::ios::binary);new_person.ParseFromIstream(&input);// 输出消息内容std::cout << "Name: " << new_person.name() << std::endl;std::cout << "Age: " << new_person.age() << std::endl;for (const auto& hobby : new_person.hobbies()) {std::cout << "Hobby: " << hobby << std::endl;}return 0;}
以上示例演示了如何使用protobuf在C++程序中序列化和反序列化消息,并访问消息的数据成员。在实际应用中,可以根据需要定义更复杂的消息结构,并使用更多protobuf提供的功能来处理消息。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19