-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcall_hello.rs
42 lines (33 loc) · 1.16 KB
/
call_hello.rs
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
use nowasm::{Env, HostFunc, Module, Resolve, StdVectorFactory, Val};
pub fn main() {
#[cfg(test)]
let wasm_bytes = include_bytes!("../target/wasm32-unknown-unknown/debug/examples/hello.wasm");
#[cfg(not(test))]
let wasm_bytes = &[];
let module = Module::<StdVectorFactory>::decode(wasm_bytes).expect("Failed to decode module");
let mut instance = module
.instantiate(Resolver)
.expect("Failed to instantiate module");
instance
.invoke("hello", &[])
.expect("Failed to invoke function");
}
struct Resolver;
impl Resolve for Resolver {
type HostFunc = Print;
fn resolve_func(&self, module: &str, name: &str) -> Option<Self::HostFunc> {
assert_eq!(module, "env");
assert_eq!(name, "print");
Some(Print)
}
}
struct Print;
impl HostFunc for Print {
fn invoke(&mut self, args: &[Val], env: &mut Env) -> Option<Val> {
let ptr = args[0].as_i32().expect("Not a i32") as usize;
let len = args[1].as_i32().expect("Not a i32") as usize;
let msg = std::str::from_utf8(&env.mem[ptr..ptr + len]).expect("Invalid utf8");
print!("{msg}");
None
}
}