前言
由于wasm暂时无法支持文件读写、网络通信等系统操作。
所以现需要在Java运行wasm,同时将数据库的读写作为外部函数供给wasm调用。
问题
wasmer-java调用wasmer部分由rust编写,部分代码较老。
在wasmer仓库中,官方给出的示例为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| let wasm_bytes = wat2wasm("bytes")?; let store = Store::new(&JIT::new(Cranelift::default()).engine());
println!("Compiling module..."); let module = Module::new(&store, wasm_bytes)?;
fn multiply(a: i32) -> i32 { println!("Calling `multiply_native`..."); let result = a * 3;
println!("Result of `multiply_native`: {:?}", result);
result }
let multiply_native = Function::new_native(&store, multiply);
let import_object = imports! { "env" => { "multiply_native" => multiply_native, } };
println!("Instantiating module..."); let instance = Instance::new(&module, &import_object)?;
|
而对于仍在使用较老版本的wasmer-java中,此方法无法奏效。
解决
通过查阅源码,发现在老版本中并没有使用 Function::new_native(&store, multiply);。
而是使用位于runtime-core 中的func! 宏
注:runtime-core被标记为已弃用
1 2 3 4 5 6 7 8 9
| fn func(_: &mut vm::Ctx, arg: i32) -> i32 { arg + 1 }
let _ = imports! { "env" => { "func" => func!(func), }, };
|