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