From 1bc45c72b1f7c241915be9e3cc032673cd323f89 Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Wed, 18 Jan 2023 23:34:02 +0800 Subject: [PATCH] feat: add example3 --- __wasm/wasmtime/examples/example3.rs | 37 ++++++++++++++++++++++++++++ __wasm/wasmtime/justfile | 2 ++ 2 files changed, 39 insertions(+) create mode 100644 __wasm/wasmtime/examples/example3.rs diff --git a/__wasm/wasmtime/examples/example3.rs b/__wasm/wasmtime/examples/example3.rs new file mode 100644 index 0000000..0ae8118 --- /dev/null +++ b/__wasm/wasmtime/examples/example3.rs @@ -0,0 +1,37 @@ +use anyhow::Result; +use wasmtime::*; + +fn main() -> Result<()> { + // Modules can be compiled through either the text or binary format + let engine = Engine::default(); + let wat = r#" + (module + (import "host" "hello" (func $host_hello (param i32))) + + (func (export "hello") + i32.const 3 + call $host_hello) + ) + "#; + let module = Module::new(&engine, wat)?; + + // Create a `Linker` which will be later used to instantiate this module. + // Host functionality is defined by name within the `Linker`. + let mut linker = Linker::new(&engine); + linker.func_wrap("host", "hello", |caller: Caller<'_, u32>, param: i32| { + println!("Got {} from WebAssembly", param); + println!("my host state is: {}", caller.data()); + })?; + + // 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, 4); + let instance = linker.instantiate(&mut store, &module)?; + let hello = instance.get_typed_func::<(), ()>(&mut store, "hello")?; + + // And finally we can call the wasm! + hello.call(&mut store, ())?; + + Ok(()) +} \ No newline at end of file diff --git a/__wasm/wasmtime/justfile b/__wasm/wasmtime/justfile index 0e45702..5f00ed0 100644 --- a/__wasm/wasmtime/justfile +++ b/__wasm/wasmtime/justfile @@ -12,4 +12,6 @@ run_example1: run_example2: cargo run --example example2 +run_example3: + cargo run --example example3