如何在Java中调用Rust编写的库包?在这个例子中,我们将看到如何:
- 构建一个简单的 Rust 库,它公开一个 C API(巴拿马 FFI 可以链接到它)。
- 使用cbindgen来生成这个库中的C头文件。
- 用于jextract从头文件生成 java 绑定。
- 创建一个简单的 java 程序,通过绑定调用 rust 库。
步骤 1. 设置项目
$ mkdir rust-panama-helloworld
$ cd rust-panama-helloworld
$ cargo init --lib
步骤 2. 编写一个简单的 Rust 库
编辑src/lib.rs并将内容更改为:
#[no_mangle]
pub extern <font>"C"</font><font> fn hello_world() {
println!(</font><font>"Hello, world!"</font><font>);
}
</font>
#[no_mangle]需要该属性以确保函数在库中可见,并extern "C"用于确保函数具有正确的 ABI(特定平台的 C ABI)。
步骤 3. 添加所需的项目配置
进入Cargo.toml并添加以下内容:
[build-dependencies]
cbindgen = <font>"0.20.0"</font><font>
<p>[lib]
crate_type = [</font><font