Wasmer JNI是一个可以直接在Java中执行WebAssembly的库。它嵌入了WebAssembly运行时Wasmer,Wasmer JNI开源项目是:https://github.com/wasmerio/java-ext-wasm
让我们从一个简单的Rust程序开始,将其编译为WebAssembly,然后在Java中执行:
#[no_mangle] pub extern fn sum(x: i32, y: i32) -> i32 { x + y }
|
汇编WebAssembly后,我们得到这样一个文件:这里,命名为simple.wasm。
以下Java程序sum通过传递5和37作为参数来执行导出的函数:
import org.wasmer.Instance;
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths;
class SimpleExample { public static void main(String[] args) throws IOException { // Read the WebAssembly bytes. byte[] bytes = Files.readAllBytes(Paths.get("simple.wasm"));
// Instantiate the WebAssembly module. Instance instance = new Instance(bytes);
// Get the `sum` exported function, call it by passing 5 and 37, and get the result. Integer result = (Integer) instance.exports.getFunction("sum").apply(5, 37)[0];
assert result == 42;
instance.close(); } }
|
我们已经用Java成功执行了一个Rust程序,该程序首先需要编译为WebAssembly。这非常简单。该API与标准JavaScript API或我们为PHP,Python,Go,Ruby等设计的其他API非常相似。