Setting Up Rust
Step 1: Exporting Rust Functions
To make Rust functions callable from Java, we need to do two things:
- Use
#[no_mangle]
to prevent Rust from renaming (mangling) the function name internally. This ensures Java can find the function by its exact name. - Declare the function with
extern "C"
to make sure it uses the C Application Binary Interface (ABI), which Java understands.
Rust Example:
#![allow(unused)] fn main() { #[no_mangle] pub extern "C" fn create_point(x: i32, y: i32) -> *mut Point { Box::into_raw(Box::new(Point { x, y })) } #[no_mangle] pub extern "C" fn get_x(point: *mut Point) -> i32 { unsafe { (*point).x } } #[no_mangle] pub extern "C" fn free_point(point: *mut Point) { unsafe { Box::from_raw(point); } // Frees the allocated memory } struct Point { x: i32, y: i32, } }
Explanation:
*mut Point:
The function returns a raw pointer (*mut Point
), which Java can manage using the FFM API.
Step 2: Compiling Rust into a Shared Library
To compile the Rust code into a format Java can load, modify the Cargo.toml
file:
[lib]
crate-type = ["cdylib"]
Then, compile the Rust project into a shared library:
cargo build --release
This command will generate a shared library file (e.g., libmyrustlib.so
or myrustlib.dll
) in the target/release/
directory, which Java can dynamically load.