Protocol Buffers
Protocol Buffers 是一种语言和平台无关的可扩展机制,用于序列化结构化数据。
什么是 Protocol Buffers?
Protocol Buffers 是 Google 的一种语言和平台无关、可扩展的机制,用于序列化结构化数据——可以将其想象成 XML,但更小、更快、更简单。您只需定义一次您希望数据结构的方式,然后就可以使用特定的生成源代码轻松地将您的结构化数据写入多种数据流,并从多种数据流中读取数据,支持多种语言。
选择您喜欢的语言
Protocol Buffers 支持为 C++、C#、Dart、Go、Java、Kotlin、Objective-C、Python 和 Ruby 生成代码。对于 proto3,您还可以使用 PHP。
示例实现
edition = "2023";
message Person {
string name = 1;
int32 id = 2;
string email = 3;
}
图 1. Proto 定义。
// Java code
Person john = Person.newBuilder()
.setId(1234)
.setName("John Doe")
.setEmail("jdoe@example.com")
.build();
output = new FileOutputStream(args[0]);
john.writeTo(output);
图 2. 使用生成的类持久化数据。
// C++ code
Person john;
fstream input(argv[1],
ios::in | ios::binary);
john.ParseFromIstream(&input);
id = john.id();
name = john.name();
email = john.email();
图 3. 使用生成的类解析持久化数据。