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 的原型;此模組定義如下:

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",
}

使用此套件的庫是透過引用它來定義的,就好像它是任何其他庫依賴項一樣:

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

rust_protobuf 模組的 crate 結構

每個 protobuf 檔案都在 crate 中組織為自己的模組,並採用 protobuf 檔案的名稱。這意味著所有原型基本檔案名稱必須是唯一的。例如,採用如下定義的rust_protobuf

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

該板條箱中的不同原型將按如下方式存取:

// 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模組類型的獨特行為。

莖、名稱、板條箱名稱

rust_protobuf產生庫變體,因此這三個屬性與rust_library模組存在相同的要求。有關詳細信息,請參閱rust_library屬性。

普羅托斯

這是用於產生 protobuf 介面的 protobuf 檔案的相對路徑清單。基本檔名在protosgrpc_protos中必須是唯一的。

grpc_protos

grpc_protos由 protobuf 檔案的相對路徑清單組成,這些檔案定義grpcs以產生 protobuf 介面。基本檔名在protosgrpc_protos中必須是唯一的。

源_莖

source_stem產生的可以包含的來源檔案的檔案名稱。這是必需的欄位定義,即使您將綁定用作包,也是如此,因為stem屬性僅控制生成的庫變體的輸出檔名。與其他來源產生器不同,檔案名稱以 mod_ 為前綴,形成最終檔案名稱mod_<stem> 。這可以防止與每個原型產生的來源發生名稱衝突。

此外,與bindgen綁定模組一樣,全套函式庫屬性也可用於控制函式庫編譯,儘管這些屬性很少需要定義或變更。