protobuf 模块

构建系统支持通过 rust_protobuf 模块类型生成 protobuf 接口。

基本 protobuf 代码的生成是通过 rust-protobuf crate 执行的。如需查看有关此用法的文档,请参阅包含相应 protobuf 示例GitHub 项目页面

构建系统还支持 gRPC protobuf,其代码的生成由 grpc-rs crate 提供。如需查看有关此用法的文档,请参阅相应 gRPC 的 GitHub 项目页面上的文档。

基本 rust_protobuf build 用法

下面的示例展示了如何定义一个 protobuf 模块并将该模块用作 crate。如需详细了解重要属性及其用法,请参阅定义 rust_protobuf 部分。

如果您需要通过 include!() 宏使用 protobuf 生成的代码(例如为了包含第三方代码),请参阅源代码生成器页面的示例。(该示例使用的是 rust_bindgen 模块,但所有源代码生成器用于包含源代码的方式都是一样的。)

定义 rust_protobuf Android.bp 模块

假定某些 proto 相对于您的 Android.bp 的位置是 src/protos/my.proto;那么,模块的定义如下所示:

rust_protobuf {
    name: "libmy_proto",

    // Crate name that's used to generate the rust_library variants.
    crate_name: "my_proto",

    // Relative paths to the protobuf source files
    protos: ["src/protos/my.proto"],

    // If protobufs define gRPCs, then they should go in grpc_protos
    // instead.
    // grpc_protos: ["src/protos/my.proto"],

    // 'source_stem' controls the output filename.
    // This is the filename that's used in an include! macro.
    source_stem: "my_proto_source",
}

使用此 crate 的库通过引用它来进行定义,就像引用任何其他库依赖项一样:

rust_binary {
    name: "hello_rust_proto",
    srcs: ["src/main.rs"],
    rustlibs: ["libmy_proto"],
}

rust_protobuf 模块的 crate 结构

在 crate 中,每个 protobuf 文件都被整理为其自己的模块,并采用 protobuf 文件的名称。这意味着所有 proto 基本文件名必须是唯一的。以如下定义的某个 rust_protobuf 为例:

rust_protobuf {
    name: "libfoo",
    crate_name: "foo",
    protos: ["a.proto", "b.proto"],
    grpc_protos: ["c.proto"],
    source_stem: "my_proto_source",
}

可以如下访问此 crate 中的不同 proto:

// use <crate_name>::<proto_filename>
use foo::a; // protobuf interface defined in a.proto
use foo::b; // protobuf interface defined in b.proto
use foo::c; // protobuf interface defined in c.proto
use foo::c_grpc; // grpc interface defined in c.proto

重要的 rust_protobuf 属性

除了适用于所有模块的重要的通用属性之外,还有下面定义的一些属性。这些属性要么对 Rust protobuf 模块特别重要,要么具有特定于 rust_protobuf 模块类型的独有行为。

stem、name、crate_name

rust_protobuf 会生成库变体,因此对这三个属性的要求与 rust_library 模块相同。如需了解详情,请参阅 rust_library 属性。

protos

这是用于生成 protobuf 接口的 protobuf 文件的相对路径列表。其基本文件名在 protosgrpc_protos 中必须是唯一的。

grpc_protos

grpc_protos 包括 protobuf 文件相对路径的列表,这些文件定义了用于生成 protobuf 接口的 grpcs。其基本文件名在 protosgrpc_protos 中必须是唯一的。

source_stem

source_stem 是可以包含的已生成源代码文件的文件名。这是一个必填字段定义,即使您使用绑定作为 crate 也是如此,因为 stem 属性只能控制生成的库变体的输出文件名。与其他源代码生成器不同,文件名带有 mod_ 前缀,使最终文件名成为 mod_<stem>。这可以防止文件名与从每个 proto 生成的源代码发生名称冲突。

此外,与 bindgen 绑定模块一样,整套库属性也都可以用来控制库的编译,但通常不需要定义或更改这些属性。