シンプルな Rust ライブラリ

Rust の関数や型を C にエクスポートするのは簡単です。以下はシンプルな Rust ライブラリです:

interoperability/rust/libanalyze/analyze.rs

// Copyright 2025 Google LLC
// SPDX-License-Identifier: Apache-2.0

//! Rust FFI demo.
#![deny(improper_ctypes_definitions)]

use std::os::raw::c_int;

/// Analyze the numbers.
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
pub extern "C" fn analyze_numbers(x: c_int, y: c_int) {
    if x < y {
        println!("x ({x}) is smallest!");
    } else {
        println!("y ({y}) is probably larger than x ({x})");
    }
}

interoperability/rust/libanalyze/Android.bp

rust_ffi {
    name: "libanalyze_ffi",
    crate_name: "analyze_ffi",
    srcs: ["analyze.rs"],
    include_dirs: ["."],
}

#[unsafe(no_mangle)] は Rust の通常の名前マングリングを無効にするため、エクスポートされた シンボルは単に関数名になります。#[unsafe(export_name = "some_name")] を使って 任意の名前を指定することもできます。