I wrote a simple rust file as
#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
a + b
}
and tried to invoke it in Java. So I loaded it and defined 2 native methods:
public interface CLibrary extends Library {
CLibrary INSTANCE = Native.load("add", CLibrary.class);
void printf(String format, Object... args);
int add(int a, int b);
}
Notice that I put printf
here except add
.
But it worked:
CLibrary.INSTANCE.printf("Hello, World!\n");
System.out.println(CLibrary.INSTANCE.add(1, 2));
These code output
3
Hello, World!
How could I can access printf
which is not defined in my rust source?
Rust uses and links the C library to define much of std
so the C standard library printf
is available in builds that include std
(which is every one that doesn't opt out).