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 模組

假設 Android.bp 相對位置的 src/protos/my.proto 有一些 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 結構

每個 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 模組類型特有的行為。

幹、名稱、crate_name

rust_protobuf 會產生程式庫變體,因此這三個屬性的需求與 rust_library 模組相同。詳情請參閱rust_library 屬性。

protos

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

grpc_protos

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

source_stem

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

此外,與 bindgen 繫結模組類似,您也可以使用全套程式庫屬性來控制程式庫編譯作業,但這些屬性很少需要定義或變更。