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 = "2024";

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. 使用生成的类来解析持久化的数据。

如何开始?

  1. 下载并安装 protocol buffer 编译器。
  2. 阅读概述
  3. 尝试为您选择的语言准备的教程