Java现在也可以搞WebAssembl

用于执行WebAssembly二进制程序的Wasmer公开了目前业内首个支持WebAssembly的Java扩展库WasmerJNI。根据介绍,此次开源出来的WasmerJNI的特性包括:易于使用:API模仿标准的WebAssemblyAPI快:极尽可能运行WebAssembly模块安全:对WebAssembly的所有调用完全安全并且沙箱化隔离(采用Rust编写而成)WasmerJNI库为不同平台生成JAR包,目前支持:amd64-darwin:macOS、xamd64-linux:Linux、xamd64-windows:Windows、x同时开发者可以为自己的平台和架构生成自己的JAR。性能方面,由于WasmerJNI是首个执行WebAssembly的Java库,因此无法与Java生态中的其它项目作比较,但是,不过因为Wasmer自身的设计上有优势,它带有3个后端:Singlepass、Cranelift与LLVM,WasmerJNI库目前使用Cranelift后端,这在编译时间和执行时间之间提供了最佳折衷方案。Wasmer在WebAssembly服务器运行时领域居于领先地位,去年获得了InfoWorld年最佳开源软件奖。来看一个从Java调用WebAssembly的demo:从一个简单的Rust程序入手,将其编译为WebAssembly,然后从Java执行。

#[no_mangle]pubexternfnsum(x:i32,y:i32)-i32{x+y}编译为WebAssembly后,得到一个名为simple.wasm的文件。接着Java程序通过传递5和37这两个参数来执行sum函数:

importorg.wasmer.Instance;importjava.io.IOException;importjava.nio.file.Files;importjava.nio.file.Paths;classSimpleExample{publicstaticvoidmain(String[]args)throwsIOException{//ReadtheWebAssemblybytes.byte[]bytes=Files.readAllBytes(Paths.get("simple.wasm"));//InstantiatetheWebAssemblymodule.Instanceinstance=newInstance(bytes);//Getthe`sum`exportedfunction,callitbypassing5and37,andgettheresult.Integerresult=(Integer)instance.exports.getFunction("sum").apply(5,37)[0];assertresult==42;instance.close();}}可以看到,WasmerJNI的API与标准JavaScriptAPI非常相似。关于WasmerJNI的更多信息,可以查看官方公告:


转载请注明:http://www.guyukameng.com/html/html1/11605.html

  • 上一篇文章:
  •   
  • 下一篇文章: 没有了