1个不稳定版本
0.18.0 | 2023年4月11日 |
---|
#834 在 WebAssembly
每月 下载 24 次
1MB
19K SLoC
Wasmer运行时
Wasmer是一个独立的JIT WebAssembly运行时,旨在与Emscripten、Rust和Go完全兼容。[了解更多](https://github.com/wasmerio/wasmer)。
此crate代表高级运行时API,使在应用程序中嵌入WebAssembly变得简单、高效且安全。
如何使用Wasmer运行时
最简单的方法是使用instantiate
函数创建一个Instance
。然后您可以使用call
或func
,然后调用导出函数以安全地调用。
示例
给定这个WebAssembly
(module
(type $t0 (func (param i32) (result i32)))
(func $add_one (export "add_one") (type $t0) (param $p0 i32) (result i32)
get_local $p0
i32.const 1
i32.add))
编译成Wasm字节码,我们可以调用导出的add_one
函数
static WASM: &'static [u8] = &[
// The module above compiled to bytecode goes here.
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x06, 0x01, 0x60,
0x01, 0x7f, 0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07, 0x0b, 0x01, 0x07,
0x61, 0x64, 0x64, 0x5f, 0x6f, 0x6e, 0x65, 0x00, 0x00, 0x0a, 0x09, 0x01,
0x07, 0x00, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x0b, 0x00, 0x1a, 0x04, 0x6e,
0x61, 0x6d, 0x65, 0x01, 0x0a, 0x01, 0x00, 0x07, 0x61, 0x64, 0x64, 0x5f,
0x6f, 0x6e, 0x65, 0x02, 0x07, 0x01, 0x00, 0x01, 0x00, 0x02, 0x70, 0x30,
];
use wasmer_runtime::{
instantiate,
DynFunc,
Value,
imports,
error,
};
fn main() -> error::Result<()> {
// We're not importing anything, so make an empty import object.
let import_object = imports! {};
let instance = instantiate(WASM, &import_object)?;
let values = instance
.exports
.get::<DynFunc>("add_one")?
.call(&[Value::I32(42)])?;
assert_eq!(values[0], Value::I32(43));
Ok(())
}
附加说明
此wasmer-runtime
crate旨在支持多个编译器后端。我们支持在wasmer-clif-backend
crate中有一个Cranelift
后端,在wasmer-llvm-backend
crate中有一个LLVM后端,在wasmer-singlepass-backend
crate中有一个Singlepass后端。目前,Cranelift后端是默认的。
您可以使用compile_with
函数指定您希望使用的编译器。
依赖项
~7–15MB
~217K SLoC