What is the usage of protobuf in C++?
To use protobuf in C++, you first need to define a .proto file to describe the structure of the message, and then use the protobuf compiler to generate corresponding C++ code. After that, you can use the generated code in your C++ program to serialize and deserialize messages.
Here is a simple example demonstrating the use of protobuf.
- Define a .proto file:
syntax = "proto3";
message Person {
string name = 1;
int32 age = 2;
repeated string hobbies = 3;
}
- Compile C++ code using the Protobuf compiler.
protoc --cpp_out=. person.proto
- Use the generated code in a C++ program.
#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;
}
The examples above demonstrate how to serialize and deserialize messages in a C++ program using protobuf, and access the data members of the messages. In practical applications, more complex message structures can be defined as needed, and additional functionality provided by protobuf can be used to handle messages.