JavaWithRust-Lib
Transfer function calls between Rust and Java in a rust-like (ish) way.
Features
- Call static java functions from rust.
- Call associated rust functions from java.
- Convert java objects to rust structs.
Limitations
- Can not call java methods from rust.
- Can not call rust methods from java.
- Can only convert the following rust types to java objects:
String
i8
i16
i32
i64
f32
f64
Setup
Create a dynamic library crate.
cargo init . --lib
[dependencies]
javawithrust = "0.1"
serde = {version = "1.0", features = ["derive"]}
[lib]
crate_type = ["cdylib"]
Usage
Get the needed stuff.
use javawithrust::prelude::*;
Link a new Java class. This will link JavaObject
(in Rust) and io.example.JavaClassName
(in Java).
#[jclass(io.example.JavaClassName)]
pub struct JavaObject;
Link the functions.
#[jfuncs]
impl JavaObject {
}
Examples
use javawithrust::prelude::*;
#[jclass(io.example.CustomJavaClass)]
pub struct CustomRustStruct;
#[jfuncs]
impl CustomRustStruct {
fn hello() { println!("hello");
CustomRustStruct::world()?;
return Ok(());
}
fn world();
fn sum(a : i32, b : i32) -> i32 { return Ok(a + b);
}
}
package io.example;
import org.astonbitecode.j4rs.api.Instance;
import org.astonbitecode.j4rs.api.java2rust.Java2RustUtils;
public class CustomJavaClass
{
static {
String os=System.getProperty("os.name").toLowerCase();String path=J2RS.class.getProtectionDomain().getCodeSource().getLocation().getPath();path=path.substring(0,path.lastIndexOf("/")).replaceAll("%20"," ")+"/"+
"robot"; if (os.contains("linux") || os.contains("unix") || os.contains("android")) {
path += ".so";
} else if (os.contains("win")) {
path += ".dll";
}
else {throw new UnsatisfiedLinkError("Can not load dynamic library in unknown operating system `" + os + "`");}
System.load(path);
}
public static native void hello();
public static void world() {
System.out.println("world!");
}
private static native Instance<Integer> sum(Instance<Integer> i1, Instance<Integer> i2);
public static Integer sumFromRust(Integer a, Integer b) {
return Java2RustUtils.getObjectCasted(J2RS.sum(
Java2RustUtils.createInstance(a),
Java2RustUtils.createInstance(b)
));
}
}