linux-china / panama-rust-demo

Java Panama(FFI) with Rust demo

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Java Panama Rust Demo

Use Java 22 JEP 454: Foreign Function & Memory API to call Rust functions by FFI.

Requirements

Project structure

  • src/main/rust: Rust library cdylib source code with FFI
  • src/main/java: Java source code to call Rust functions by FFI
  • RustLibWrapper.java: Java wrapper class to call stub code.

How it works

  1. Write Rust functions with #[no_mangle] and extern "C" attributes.
  2. Build Rust functions as a shared library with cdylib crate type.
  3. Generate lib.h header file with cbindgen tool for Rust FFI functions.
  4. Use jextract tool to generate Java bindings from the header file and shared library.
  5. Write Java code to call the stub functions generated by jextract.

GraalVM native-image support

Please refer Foreign Function and Memory API in Native Image

Install jextract from source code

$ git clone https://github.com/openjdk/jextract.git
$ cd jextract
$ ./gradlew -Pjdk22_home=$HOME/.jbang/cache/jdks/22 -Pllvm_home=/Library/Developer/CommandLineTools/usr/ clean verify
$ cp -r build/jextract ~/tools/jextract

References

About

Java Panama(FFI) with Rust demo


Languages

Language:Java 45.0%Language:C 34.6%Language:Just 9.3%Language:C++ 6.2%Language:Rust 4.9%