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