Protobuf 模組

建構系統支援透過 rust_protobuf 模組類型產生 protobuf 介面。

基本 protobuf 程式碼產生作業會使用 rust-protobuf crate 執行。如要查看這項用法的說明文件,請參閱 GitHub 專案頁面,並查看相應的 protobuf 範例

系統也支援 gRPC protobuf,並由 grpc-rs crate 提供產生功能。如要查看此用法的說明文件,請參閱對應 gRPC GitHub 專案頁面的說明文件。

基本 rust_protobuf 建構用法

以下提供定義 protobuf 模組並將該模組用作 crate 的範例。如要進一步瞭解重要屬性及其用途,請參閱「定義 rust_protobuf」一節。

如果您需要透過 include!() 巨集使用 protobuf 產生的程式碼 (例如第三方程式碼),請參閱「原始碼產生器」頁面查看範例。(範例使用 rust_bindgen 模組,但所有來源產生器的來源納入方式相同)。

定義 rust_protobuf Android.bp 模組

假設在 src/protos/my.proto 中有一些相對於 Android.bp 的 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 的程式庫會以任何其他程式庫依附元件的形式參照 Crate 來定義:

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

rust_protobuf 模組的 Crate 結構

每個 protobuf 檔案都會在 crate 中設為專屬模組,並採用 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 屬性。

proto

這是 protobuf 檔案的相對路徑清單,用於產生 protobuf 介面。protosgrpc_protos 之間的基本檔案名稱不得重複。

grpc_protos

grpc_protos 包含 protobuf 檔案的相對路徑清單,這些檔案會定義 grpcs 以產生 protobuf 介面。在 protosgrpc_protos 中,基本檔案名稱不得重複。

source_stem

source_stem產生的來源檔案的檔案名稱,可納入其中。即使您將繫結用於 Crate,此為必填欄位定義,因為 stem 屬性只會控制產生程式庫變數的輸出檔案名稱。與其他來源產生器不同,檔案名稱會加上前置字串「mod_」,最終檔案名稱為 mod_<stem>。這樣可避免與每個 proto 產生的來源發生名稱衝突。

此外,如同 bindgen 繫結模組,完整的程式庫屬性集合也可用於控制程式庫編譯作業,但這些屬性很少需要定義或變更。