//! Small example of how to instantiate a wasm module that imports one function,1//! showing how you can fill in host functionality for a wasm module.23// You can execute this example with `cargo run --example hello`45use wasmtime::*;67struct MyState {8name: String,9count: usize,10}1112fn main() -> Result<()> {13// First the wasm module needs to be compiled. This is done with a global14// "compilation environment" within an `Engine`. Note that engines can be15// further configured through `Config` if desired instead of using the16// default like this is here.17println!("Compiling module...");18let engine = Engine::default();19let module = Module::from_file(&engine, "examples/hello.wat")?;2021// After a module is compiled we create a `Store` which will contain22// instantiated modules and other items like host functions. A Store23// contains an arbitrary piece of host information, and we use `MyState`24// here.25println!("Initializing...");26let mut store = Store::new(27&engine,28MyState {29name: "hello, world!".to_string(),30count: 0,31},32);3334// Our wasm module we'll be instantiating requires one imported function.35// the function takes no parameters and returns no results. We create a host36// implementation of that function here, and the `caller` parameter here is37// used to get access to our original `MyState` value.38println!("Creating callback...");39let hello_func = Func::wrap(&mut store, |mut caller: Caller<'_, MyState>| {40println!("Calling back...");41println!("> {}", caller.data().name);42caller.data_mut().count += 1;43});4445// Once we've got that all set up we can then move to the instantiation46// phase, pairing together a compiled module as well as a set of imports.47// Note that this is where the wasm `start` function, if any, would run.48println!("Instantiating module...");49let imports = [hello_func.into()];50let instance = Instance::new(&mut store, &module, &imports)?;5152// Next we poke around a bit to extract the `run` function from the module.53println!("Extracting export...");54let run = instance.get_typed_func::<(), ()>(&mut store, "run")?;5556// And last but not least we can call it!57println!("Calling export...");58run.call(&mut store, ())?;5960println!("Done.");61Ok(())62}636465