รูปแบบ Android สนิม

หน้านี้ประกอบด้วยข้อมูลเกี่ยวกับ การบันทึกของ Android ให้ ตัวอย่าง Rust AIDL บอกวิธี เรียก Rust จาก C และให้คำแนะนำสำหรับ Rust/C++ Interop โดยใช้ CXX

การบันทึก Android

ตัวอย่างต่อไปนี้แสดงวิธีที่คุณสามารถบันทึกข้อความไปยัง 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

ตัวอย่างสนิม AIDL

ส่วนนี้ให้ตัวอย่างสไตล์ Hello World ของการใช้ AIDL กับ Rust

การใช้ส่วน ภาพรวม AIDL ของคู่มือนักพัฒนา Android เป็นจุดเริ่มต้น สร้าง 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 อื่น ๆ เป็นการพึ่งพาได้ เป็นตัวอย่างของการใช้ไลบรารีที่สร้างขึ้นเป็นการพึ่งพา สามารถกำหนด rust_library ได้ดังต่อไปนี้ใน external/rust/binder_example/Android.bp :

rust_library {
    name: "libmyservice",
    srcs: ["src/lib.rs"],
    crate_name: "myservice",
    rustlibs: [
        "com.example.android.remoteservice-rust",
        "libbinder_rs",
    ],
}

โปรดทราบว่ารูปแบบชื่อโมดูลสำหรับไลบรารีที่สร้างโดย AIDL ที่ใช้ใน rustlibs คือชื่อโมดูล aidl_interface ตามด้วย -rust ; ในกรณีนี้ com.example.android.remoteservice-rust

อินเทอร์เฟซ AIDL สามารถอ้างอิงได้ใน src/lib.rs ดังนี้:

// 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()
}

ตัวอย่าง Async Rust AIDL

ส่วนนี้ให้ตัวอย่างสไตล์ Hello World ของการใช้ AIDL กับ async Rust

จากตัวอย่าง RemoteService ต่อไป ไลบรารีแบ็กเอนด์ AIDL ที่สร้างขึ้นจะมีอินเทอร์เฟซอะซิงก์ที่สามารถใช้เพื่อปรับใช้เซิร์ฟเวอร์อะซิงก์สำหรับอินเทอร์เฟซ AIDL RemoteService

อินเทอร์เฟซเซิร์ฟเวอร์ async ที่สร้างขึ้น 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(())
    }
}

การใช้งานเซิร์ฟเวอร์ async สามารถเริ่มต้นได้ดังนี้:

#[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 เพื่อออกจากบริบท async ซึ่งอนุญาตให้ join_thread_pool ใช้ block_on ภายใน นี่เป็นเพราะ #[tokio::main] ล้อมโค้ดในการเรียกไปยัง block_on และ join_thread_pool อาจเรียก block_on เมื่อจัดการธุรกรรมที่เข้ามา การเรียก block_on จากภายใน block_on ส่งผลให้เกิดความตื่นตระหนก สิ่งนี้สามารถหลีกเลี่ยงได้ด้วยการสร้างรันไทม์ tokio ด้วยตนเอง แทนที่จะใช้ #[tokio::main] จากนั้นเรียก join_thread_pool นอกเมธอด block_on

นอกจากนี้ ไลบรารีที่สร้างแบ็กเอนด์สนิมยังมีอินเทอร์เฟซที่อนุญาตให้ใช้งานไคลเอ็นต์ async IRemoteServiceAsync สำหรับ RemoteService ซึ่งสามารถนำไปใช้ได้ดังต่อไปนี้:

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

ตัวอย่างห้องสมุดสนิม

กำหนดไฟล์ libsimple_printer ใน external/rust/simple_printer/libsimple_printer.rs ดังนี้:

//! 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 include_dirs so cc_binary knows where the headers are.
    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

การทำงานร่วมกันระหว่างสนิมและ Java

กล่อง jni จัดเตรียมความสามารถในการทำงานร่วมกันของ Rust กับ Java ผ่าน Java Native Interface (JNI) โดยกำหนดคำจำกัดความประเภทที่จำเป็นสำหรับ Rust เพื่อสร้างไลบรารี่ cdylib ของ Rust ที่เสียบเข้ากับ JNI ของ Java ( JNIEnv , JClass , JString และอื่นๆ โดยตรง) ต่างจากการผูก C++ ที่ทำโค้ดเจนผ่าน cxx การทำงานร่วมกันของ Java ผ่าน JNI ไม่ต้องการขั้นตอนการสร้างโค้ดระหว่างการบิลด์ ดังนั้นจึงไม่ต้องการการสนับสนุนระบบบิลด์พิเศษ โค้ด Java จะโหลด cdylib ที่ได้รับจาก Rust เช่นเดียวกับไลบรารีเนทิฟอื่นๆ

การใช้งาน

การใช้งานทั้งในโค้ด Rust และ Java ครอบคลุมอยู่ใน เอกสารประกอบ jni crate โปรดปฏิบัติตามตัวอย่าง การเริ่มต้น ใช้งานที่ให้ไว้ที่นั่น หลังจากที่คุณเขียน src/lib.rs แล้ว ให้กลับมาที่หน้านี้เพื่อเรียนรู้วิธีสร้างไลบรารีด้วยระบบบิลด์ของ Android

สร้างคำจำกัดความ

Java ต้องการให้ไลบรารี Rust จัดทำเป็น cdylib เพื่อให้สามารถโหลดได้แบบไดนามิก คำจำกัดความของไลบรารี Rust ใน Soong มีดังต่อไปนี้:

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"]
        [...]
}

หรืออีกทางหนึ่ง หากคุณต้องรวมไลบรารี Rust ไว้ในไฟล์ AndroidManifest.xml ให้เพิ่มไลบรารีลงใน uses_libs ดังนี้:

java_library {
        name: "libhelloworld",
        [...]
        uses_libs: ["libhellorust"]
        [...]
}

การทำงานร่วมกันของ Rust–C++ โดยใช้ CXX

ลัง CXX ให้ FFI ที่ปลอดภัยระหว่าง Rust และชุดย่อยของ C++ เอกสาร CXX ให้ตัวอย่างที่ดีเกี่ยวกับวิธีการทำงานโดยทั่วไป และเราขอแนะนำให้อ่านก่อนเพื่อทำความคุ้นเคยกับไลบรารี และวิธีการเชื่อมโยง C++ และ Rust ตัวอย่างต่อไปนี้แสดงวิธีการใช้งานใน Android

หากต้องการให้ CXX สร้างโค้ด C++ ที่ Rust เรียกใช้ ให้กำหนด genrule เพื่อเรียกใช้ CXX และ cc_library_static เพื่อรวมกลุ่มนั้นไว้ในไลบรารี หากคุณวางแผนที่จะใช้โค้ด Rust ในการเรียก C++ หรือใช้ประเภทที่แชร์ระหว่าง C++ และ Rust ให้กำหนดประเภทที่สอง (เพื่อสร้างส่วนหัว C++ ที่มีการเชื่อม Rust)

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 ให้กำหนดฟังก์ชัน C++ ตามที่คุณต้องการ โดยใช้ ประเภท wrapper CXX ตามที่คุณต้องการ ตัวอย่างเช่น ข้อกำหนด 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 ให้กำหนดบริดจ์ CXX ดังต่อไปนี้ใน lib.rs :

#[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;
}