extern crate core; use anyhow::Result; use wasmtime::*; // #[wasm_bindgen] // extern { // pub fn alert(s: &str); // } // // #[wasm_bindgen] // pub fn greet(name: &str) { // alert(&format!("Hello, {}!", name)); // } fn main() -> Result<()> { // Modules can be compiled through either the text or binary format let engine = Engine::default(); let wasm = std::fs::read("./examples/hello_wasm_bg.wasm").unwrap(); let module = Module::new(&engine, wasm)?; let mut linker = Linker::new(&engine); linker.func_wrap("./hello_wasm.js", "__wbg_alert_a5a2f68cc09adc6e", |caller: Caller<'_, u32>, param: i32, param2: i32| { let mut caller = caller; if let Extern::Memory(memory) = caller.get_export("memory").unwrap() { let mut buffer = vec![0; param2 as usize]; memory.read(caller.as_context(), param as usize, &mut buffer).expect("read mem error"); let s = String::from_utf8_lossy(&buffer).to_string(); println!("[alert]: {}", s); } else { panic!("Should happen, got non memory"); } })?; // All wasm objects operate within the context of a "store". Each // `Store` has a type parameter to store host-specific data, which in // this case we're using `4` for. let mut store = Store::new(&engine, 0); let instance = linker.instantiate(&mut store, &module)?; let memory = instance.get_memory(&mut store, "memory") .ok_or_else(|| anyhow::format_err!("failed to find `memory` export"))?; let msg = "hatter".as_bytes(); let malloc = instance.get_typed_func::(&mut store, "__wbindgen_malloc")?; let p = malloc.call(&mut store, msg.len() as i32)?; memory.write(&mut store, p as usize, msg)?; let hello = instance.get_typed_func::<(i32, i32), (), _>(&mut store, "greet")?; // And finally we can call the wasm! hello.call(&mut store, (p, msg.len() as i32))?; Ok(()) }