wasmer 运行 wasm 模块
使用 wasmer 运行一个用 rust 编写的 wasm 模块。
新建 WASM
// wasm 的 import 函数
#[link(wasm_import_module = "aaa")]
extern {
fn bbb(idx: i32) -> i32;
}
// wasm 的导出函数
#[no_mangle]
pub extern fn add_one(x: i32) -> i32 {
let a;
unsafe {
a = bbb(x);
}
x + a + 1
}
编译
$ rustup target add wasm32-unknown-unknown
$ cargo build --target=wasm32-unknown-unknown
$ cargo build --target=wasm32-wasi
查看
$ wasmer inspect ./target/wasm32-unknown-unknown/debug/wasm_mod.wasm
Type: wasm
Size: 1.7 MB
Imports:
Functions:
"aaa"."bbb": [I32] -> [I32]
Memories:
Tables:
Globals:
Exports:
Functions:
"add_one": [I32] -> [I32]
Memories:
"memory": not shared (17 pages..)
Tables:
Globals:
"__data_end": I32 (constant)
"__heap_base": I32 (constant)
运行 WASM
use wasmer::{imports, Function, Instance, Module, Store, TypedFunction, Value};
fn main() -> anyhow::Result<()> {
let mut store = Store::default();
let module = Module::from_file(
&store,
"../wasm-mod/target/wasm32-unknown-unknown/debug/wasm_mod.wasm",
)?;
let imports = {
imports! {
"aaa" => {
"bbb" => Function::new_typed(&mut store, bbb)
}
}
};
let instance = Instance::new(&mut store, &module, &imports)?;
let add_one = instance.exports.get_function("add_one")?;
let result = add_one.call(&mut store, &[Value::I32(12)])?;
println!("result: {}", result[0]);
Ok(())
}
fn bbb(a: i32) -> i32 {
a + 2
}