feat: add example3
This commit is contained in:
37
__wasm/wasmtime/examples/example3.rs
Normal file
37
__wasm/wasmtime/examples/example3.rs
Normal file
@@ -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(())
|
||||
}
|
||||
@@ -12,4 +12,6 @@ run_example1:
|
||||
run_example2:
|
||||
cargo run --example example2
|
||||
|
||||
run_example3:
|
||||
cargo run --example example3
|
||||
|
||||
|
||||
Reference in New Issue
Block a user