此頁麵包含有關Android 日誌記錄的信息,提供Rust AIDL 範例,告訴您如何從 C 呼叫 Rust ,並提供使用 CXX 的 Rust/C++ 互通的說明。
安卓日誌記錄
以下範例顯示如何將訊息記錄到logcat
(裝置上)或stdout
(主機上)。
在Android.bp
模組中,加入liblogger
和liblog_rust
作為依賴項:
rust_binary {
name: "logging_test",
srcs: ["src/main.rs"],
rustlibs: [
"liblogger",
"liblog_rust",
],
}
接下來,在 Rust 來源中加入以下程式碼:
use log::{debug, error, Level};
fn main() {
let init_success = logger::init(
logger::Config::default()
.with_tag_on_device("mytag")
.with_min_level(Level::Trace),
);
debug!("This is a debug message.");
error!("Something went wrong!");
}
也就是說,添加上面顯示的兩個依賴項( liblogger
和liblog_rust
),呼叫init
方法一次(如果需要,您可以多次呼叫它),並使用提供的巨集記錄訊息。請參閱記錄器箱以取得可能的配置選項清單。
記錄器箱提供了一個 API 來定義您想要記錄的內容。根據程式碼是在裝置上運行還是在主機上執行(例如主機端測試的一部分),使用android_logger或env_logger記錄訊息。
Rust AIDL 範例
本節提供了將 AIDL 與 Rust 結合使用的 Hello World 風格範例。
使用 Android 開發人員指南AIDL 概述部分作為起點,建立external/rust/binder_example/aidl/com/example/android/IRemoteService.aidl
並在IRemoteService.aidl
檔案中包含以下內容:
// IRemoteService.aidl
package com.example.android;
// Declare any non-default types here with import statements
/** Example service interface */
interface IRemoteService {
/** Request the process ID of this service, to do evil things with it. */
int getPid();
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
}
然後,在external/rust/binder_example/aidl/Android.bp
檔案中,定義aidl_interface
模組。您必須明確啟用Rust 後端,因為它預設未啟用。
aidl_interface {
name: "com.example.android.remoteservice",
srcs: [ "aidl/com/example/android/*.aidl", ],
unstable: true, // Add during development until the interface is stabilized.
backend: {
rust: {
// By default, the Rust backend is not enabled
enabled: true,
},
},
}
AIDL 後端是一個 Rust 來源產生器,因此它像其他 Rust 來源產生器一樣運作並產生 Rust 庫。產生的 Rust 庫模組可以作為依賴項被其他 Rust 模組使用。作為使用產生的函式庫作為依賴項的範例,可以在external/rust/binder_example/Android.bp
中定義如下rust_library
:
rust_library {
name: "libmyservice",
srcs: ["src/lib.rs"],
crate_name: "myservice",
rustlibs: [
"com.example.android.remoteservice-rust",
"libbinder_rs",
],
}
請注意, rustlibs
中使用的 AIDL 產生的庫的模組名稱格式是aidl_interface
模組名稱後面跟著-rust
;在本例中com.example.android.remoteservice-rust
。
然後可以在src/lib.rs
中引用 AIDL 接口,如下所示:
// Note carefully the AIDL crates structure:
// * the AIDL module name: "com_example_android_remoteservice"
// * next "::aidl"
// * next the AIDL package name "::com::example::android"
// * the interface: "::IRemoteService"
// * finally, the 'BnRemoteService' and 'IRemoteService' submodules
//! This module implements the IRemoteService AIDL interface
use com_example_android_remoteservice::aidl::com::example::android::{
IRemoteService::{BnRemoteService, IRemoteService}
};
use binder::{
BinderFeatures, Interface, Result as BinderResult, Strong,
};
/// This struct is defined to implement IRemoteService AIDL interface.
pub struct MyService;
impl Interface for MyService {}
impl IRemoteService for MyService {
fn getPid(&self) -> BinderResult<i32> {
Ok(42)
}
fn basicTypes(&self, _: i32, _: i64, _: bool, _: f32, _: f64, _: &str) -> BinderResult<()> {
// Do something interesting...
Ok(())
}
}
最後,在 Rust 二進位檔案中啟動服務,如下所示:
use myservice::MyService;
fn main() {
// [...]
let my_service = MyService;
let my_service_binder = BnRemoteService::new_binder(
my_service,
BinderFeatures::default(),
);
binder::add_service("myservice", my_service_binder.as_binder())
.expect("Failed to register service?");
// Does not return - spawn or perform any work you mean to do before this call.
binder::ProcessState::join_thread_pool()
}
非同步 Rust AIDL 範例
本節提供了將 AIDL 與非同步 Rust 結合使用的 Hello World 風格範例。
繼續RemoteService
範例,產生的 AIDL 後端庫包含非同步接口,可用於實現 AIDL 接口RemoteService
的非同步伺服器實作。
產生的非同步伺服器介面IRemoteServiceAsyncServer
可以實作如下:
use com_example_android_remoteservice::aidl::com::example::android::IRemoteService::{
BnRemoteService, IRemoteServiceAsyncServer,
};
use binder::{BinderFeatures, Interface, Result as BinderResult};
/// This struct is defined to implement IRemoteServiceAsyncServer AIDL interface.
pub struct MyAsyncService;
impl Interface for MyAsyncService {}
#[async_trait]
impl IRemoteServiceAsyncServer for MyAsyncService {
async fn getPid(&self) -> BinderResult<i32> {
//Do something interesting...
Ok(42)
}
async fn basicTypes(&self, _: i32, _: i64, _: bool, _: f32, _: f64,_: &str,) -> BinderResult<()> {
//Do something interesting...
Ok(())
}
}
非同步伺服器實作可以如下啟動:
#[tokio::main(flavor = "multi_thread", worker_threads = 2)]
async fn main() {
binder::ProcessState::start_thread_pool();
let my_service = MyAsyncService;
let my_service_binder = BnRemoteService::new_async_binder(
my_service,
TokioRuntime(Handle::current()),
BinderFeatures::default(),
);
binder::add_service("myservice", my_service_binder.as_binder())
.expect("Failed to register service?");
task::block_in_place(move || {
binder::ProcessState::join_thread_pool();
});
}
請注意,需要使用block_in_place來離開非同步上下文,這允許join_thread_pool
在內部使用block_on 。這是因為#[tokio::main]
將程式碼包裝在對block_on
的呼叫中,而join_thread_pool
在處理傳入交易時可能會呼叫block_on
。從block_on
內部呼叫block_on
會導致恐慌。這也可以透過手動建立 tokio 運行時而不是使用#[tokio::main]
然後在block_on
方法之外呼叫join_thread_pool
來避免。
此外,rust 後端產生的庫包含一個接口,允許為RemoteService
實現非同步客戶端IRemoteServiceAsync
,其實作方式如下:
use com_example_android_remoteservice::aidl::com::example::android::IRemoteService::IRemoteServiceAsync;
use binder_tokio::Tokio;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let binder_service = binder_tokio::get_interface::<dyn IRemoteServiceAsync<Tokio>>("myservice");
let my_client = binder_service.await.expect("Cannot find Remote Service");
let result = my_client.getPid().await;
match result {
Err(err) => panic!("Cannot get the process id from Remote Service {:?}", err),
Ok(p_id) => println!("PID = {}", p_id),
}
}
從 C 呼叫 Rust
此範例展示如何從 C 呼叫 Rust。
Rust 庫範例
在external/rust/simple_printer/libsimple_printer.rs
中定義libsimple_printer
文件,如下所示:
//! A simple hello world example that can be called from C
#[no_mangle]
/// Print "Hello Rust!"
pub extern fn print_c_hello_rust() {
println!("Hello Rust!");
}
Rust 函式庫必須定義依賴的 C 模組可以引入的標頭,因此定義external/rust/simple_printer/simple_printer.h
標頭如下:
#ifndef SIMPLE_PRINTER_H
#define SIMPLE_PRINTER_H
void print_c_hello_rust();
#endif
定義external/rust/simple_printer/Android.bp
如下所示:
rust_ffi {
name: "libsimple_c_printer",
crate_name: "simple_c_printer",
srcs: ["libsimple_c_printer.rs"],
// Define export_include_dirs so cc_binary knows where the headers are.
export_include_dirs: ["."],
}
C 二進位範例
定義external/rust/c_hello_rust/main.c
如下:
#include "simple_printer.h"
int main() {
print_c_hello_rust();
return 0;
}
定義external/rust/c_hello_rust/Android.bp
如下:
cc_binary {
name: "c_hello_rust",
srcs: ["main.c"],
shared_libs: ["libsimple_c_printer"],
}
最後,透過呼叫m c_hello_rust
進行建構。
Rust-Java 互通
jni
crate 透過 Java 本機介面 (JNI) 提供 Rust 與 Java 的互通性。它為 Rust 定義了必要的類型定義,以產生直接插入 Java 的 JNI( JNIEnv
、 JClass
、 JString
等)的 Rust cdylib
庫。與透過cxx
執行程式碼產生的 C++ 綁定不同,透過 JNI 的 Java 互通性在建置期間不需要程式碼產生步驟。因此它不需要特殊的建造系統支援。 Java 程式碼像其他本機程式庫一樣載入 Rust 提供的cdylib
。
用法
jni
crate 文件中介紹了 Rust 和 Java 程式碼中的用法。請按照此處提供的入門範例進行操作。編寫src/lib.rs
後,返回此頁面以了解如何使用 Android 的建置系統建置庫。
建構定義
Java 要求將 Rust 函式庫作為cdylib
提供,以便可以動態載入。 Soong 中的 Rust 函式庫定義如下:
rust_ffi_shared {
name: "libhello_jni",
crate_name: "hello_jni",
srcs: ["src/lib.rs"],
// The jni crate is required
rustlibs: ["libjni"],
}
Java 函式庫將 Rust 函式庫列為required
依賴項;這可以確保它與 Java 庫一起安裝到設備上,即使它不是建置時依賴項:
java_library {
name: "libhelloworld",
[...]
required: ["libhellorust"]
[...]
}
或者,如果您必須在AndroidManifest.xml
檔案中包含 Rust 庫,請將該庫新增至uses_libs
中,如下所示:
java_library {
name: "libhelloworld",
[...]
uses_libs: ["libhellorust"]
[...]
}
使用 CXX 的 Rust-C++ 互通
CXX板條箱在 Rust 和 C++ 子集之間提供安全的 FFI。 CXX 文件提供了有關其一般工作方式的良好範例,我們建議首先閱讀它以熟悉該庫及其橋接 C++ 和 Rust 的方式。下面的範例展示如何在Android中使用它。
要讓 CXX 產生 Rust 呼叫的 C++ 程式碼,請定義一個genrule
來呼叫 CXX 和一個cc_library_static
將其捆綁到函式庫中。如果您打算讓 C++ 呼叫 Rust 程式碼,或使用 C++ 和 Rust 之間共用的類型,請定義第二個 genrule(以產生包含 Rust 綁定的 C++ 標頭)。
cc_library_static {
name: "libcxx_test_cpp",
srcs: ["cxx_test.cpp"],
generated_headers: [
"cxx-bridge-header",
"libcxx_test_bridge_header"
],
generated_sources: ["libcxx_test_bridge_code"],
}
// Generate the C++ code that Rust calls into.
genrule {
name: "libcxx_test_bridge_code",
tools: ["cxxbridge"],
cmd: "$(location cxxbridge) $(in) > $(out)",
srcs: ["lib.rs"],
out: ["libcxx_test_cxx_generated.cc"],
}
// Generate a C++ header containing the C++ bindings
// to the Rust exported functions in lib.rs.
genrule {
name: "libcxx_test_bridge_header",
tools: ["cxxbridge"],
cmd: "$(location cxxbridge) $(in) --header > $(out)",
srcs: ["lib.rs"],
out: ["lib.rs.h"],
}
上面使用cxxbridge
工具來產生橋的 C++ 端。接下來使用libcxx_test_cpp
靜態函式庫作為 Rust 執行檔的依賴項:
rust_binary {
name: "cxx_test",
srcs: ["lib.rs"],
rustlibs: ["libcxx"],
static_libs: ["libcxx_test_cpp"],
}
在.cpp
和.hpp
檔案中,根據需要使用CXX 包裝器類型來定義 C++ 函數。例如, cxx_test.hpp
定義包含以下內容:
#pragma once
#include "rust/cxx.h"
#include "lib.rs.h"
int greet(rust::Str greetee);
雖然cxx_test.cpp
包含
#include "cxx_test.hpp"
#include "lib.rs.h"
#include <iostream>
int greet(rust::Str greetee) {
std::cout << "Hello, " << greetee << std::endl;
return get_num();
}
要在 Rust 中使用它,請在lib.rs
中定義一個 CXX 橋,如下所示:
#[cxx::bridge]
mod ffi {
unsafe extern "C++" {
include!("cxx_test.hpp");
fn greet(greetee: &str) -> i32;
}
extern "Rust" {
fn get_num() -> i32;
}
}
fn main() {
let result = ffi::greet("world");
println!("C++ returned {}", result);
}
fn get_num() -> i32 {
return 42;
}