java assembly_第一个运行WebAssembly的Java库:Wasmer JNI

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非常相似。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值