A Simple Rust Library
Exporting Rust functions and types to C is easy. Here’s a simple Rust library:
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)] disables Rust’s usual name mangling, so the exported
symbol will just be the name of the function. You can also use
#[unsafe(export_name = "some_name")] to specify whatever name you want.