Setting Up Rust
Step 1: Exporting Rust Functions
To make Rust functions callable from Java, you need to:
- Prevent name mangling: Add
#[no_mangle]
to ensure Java can find the Rust function by its exact name. - Use the C ABI: Add
extern "C"
so the function adheres to the C Application Binary Interface (C ABI), which Java can interact with.
Before Adding #[no_mangle] and extern "C"
Here’s a simple Rust function that adds two numbers. This version cannot yet be used by Java because the function name will be mangled and will not conform to the C ABI.
// Rust function: Adds two numbers
pub fn add_numbers(x: i32, y: i32) -> i32 {
x + y
}
After Adding #[no_mangle] and extern “C"
To make the function callable from Java, modify it as follows:
// Rust function: Adds two numbers
#[no_mangle]
pub extern "C" fn add_numbers(x: i32, y: i32) -> i32 {
x + y
}
Step 2: Modify Cargo.toml
Add the following to the Cargo.toml file to specify that the library should be compiled as a shared library:
[lib]
crate-type = [“cdylib”]
Step 3: Build Cargo.toml
Run the following command to compile the Rust project into a shared library:
cargo build --release
Output: The shared library will be generated in the target/release/
directory.
- On Windows:
FileName.dll
- On Linux:
FileName.so
- On macOS:
FileName.dylib
File Organization Example
Here’s how your project should look after building the shared library:
rust_project/
├── src/
│ └── lib.rs # Contains the Rust function
├── Cargo.toml # Rust project configuration
└── target/
└── release/
└── librust_lib.dylib # Shared library (for macOS)