-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathreentrance.rs
More file actions
44 lines (34 loc) · 1.34 KB
/
Copy pathreentrance.rs
File metadata and controls
44 lines (34 loc) · 1.34 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use anyhow::Result;
use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store};
const WASM: &str = r#"
(module
(import "host" "call_add_twice" (func $call_add_twice (param i32) (result i32)))
(func $add_one (export "add_one") (param i32) (result i32)
local.get 0
i32.const 1
i32.add)
(func (export "run") (param i32) (result i32)
local.get 0
call $call_add_twice
i32.const 10
i32.add))
"#;
fn main() -> Result<()> {
let wasm = wat::parse_str(WASM)?;
let module = tinywasm::parse_bytes(&wasm)?;
let mut store = Store::default();
let call_add_twice = HostFunction::from(|mut ctx: FuncContext<'_>, value: i32| {
// FuncContext exposes the active module and its Store to the callback.
let add_one = ctx.module().func::<i32, i32>(ctx.store(), "add_one")?;
// Use ctx.call while a host callback has an active Wasm invocation.
// Function::call only starts top-level invocations.
let value = ctx.call(&add_one, value)?;
ctx.call(&add_one, value)
});
let mut imports = Imports::new();
imports.define("host", "call_add_twice", call_add_twice);
let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
let run = instance.func::<i32, i32>(&store, "run")?;
assert_eq!(run.call(&mut store, 40)?, 52);
Ok(())
}