Protobuf(Protocol Buffers)是由Google开发的一种语言中立、平台中立、可扩展的序列化数据格式。它能够将结构化数据序列化并通过网络进行传输或存储。Protobuf提供了高效的二进制格式,比XML或JSON更加紧凑和高效。
在使用Protobuf之前,我们需要定义消息格式。通常将这些定义写在.proto文件中。以下是一个简单的示例:
- syntax = "proto3";
-
- message Person {
- string name = 1;
- int32 id = 2;
- string email = 3;
- }
在这个示例中,我们定义了一个Person消息,包含name、id和email三个字段。
定义好.proto文件后,我们需要使用protoc编译器将其转换为C++代码:
protoc --cpp_out=. person.proto
这将生成两个文件:person.pb.h和person.pb.cc,它们包含了Protobuf消息类的定义和实现。
接下来,我们在C++项目中包含生成的头文件并使用Protobuf消息。以下是一个简单的示例:
- #include
- #include "person.pb.h"
-
- int main() {
- // 创建Person对象
- Person person;
- person.set_name("John Doe");
- person.set_id(123);
- person.set_email("johndoe@example.com");
-
- // 序列化到字符串
- std::string serialized_data;
- person.SerializeToString(&serialized_data);
-
- // 反序列化
- Person deserialized_person;
- deserialized_person.ParseFromString(serialized_data);
-
- // 输出反序列化后的数据
- std::cout << "Name: " << deserialized_person.name() << std::endl;
- std::cout << "ID: " << deserialized_person.id() << std::endl;
- std::cout << "Email: " << deserialized_person.email() << std::endl;
-
- return 0;
- }
为了更好地理解,我们将从头到尾演示一个完整的示例。
- // main.cpp
- #include
- #include
- #include "person.pb.h"
-
- using namespace std;
-
- // 序列化 Person 对象到文件
- void serializePerson(const Person& person, const string& filename) {
- fstream output(filename, ios::out | ios::trunc | ios::binary);
- if (!person.SerializeToOstream(&output)) {
- cerr << "Failed to write person." << endl;
- }
- }
-
- // 从文件反序列化 Person 对象
- Person deserializePerson(const string& filename) {
- Person person;
- fstream input(filename, ios::in | ios::binary);
- if (!person.ParseFromIstream(&input)) {
- cerr << "Failed to read person." << endl;
- }
- return person;
- }
-
- int main() {
- // 初始化 Protocol Buffers 库
- GOOGLE_PROTOBUF_VERIFY_VERSION;
-
- // 创建并设置 Person 对象
- Person person;
- person.set_name("John Doe");
- person.set_id(123);
- person.set_email("john.doe@example.com");
-
- // 序列化到文件
- const string filename = "person.bin";
- serializePerson(person, filename);
-
- // 从文件反序列化
- Person new_person = deserializePerson(filename);
-
- // 输出反序列化后的数据
- cout << "Name: " << new_person.name() << endl;
- cout << "ID: " << new_person.id() << endl;
- cout << "Email: " << new_person.email() << endl;
-
- // 清理 Protocol Buffers 库
- google::protobuf::ShutdownProtobufLibrary();
-
- return 0;
- }
我们从定义Protobuf消息开始,逐步讲解了如何使用Protobuf编译器生成C++代码,并在C++项目中使用这些生成的代码进行数据序列化和反序列化。
想获取更加详细的用法 : 课件.doc(见文章顶部)