xref: /wasmtime-44.0.1/examples/linking.rs (revision 72004aad)
1 //! Example of instantiating two modules which link to each other.
2 
3 // You can execute this example with `cargo run --example linking`
4 
5 use wasi_common::sync::WasiCtxBuilder;
6 use wasmtime::*;
7 
8 fn main() -> Result<()> {
9     let engine = Engine::default();
10 
11     // First set up our linker which is going to be linking modules together. We
12     // want our linker to have wasi available, so we set that up here as well.
13     let mut linker = Linker::new(&engine);
14     wasi_common::sync::add_to_linker(&mut linker, |s| s)?;
15 
16     // Load and compile our two modules
17     let linking1 = Module::from_file(&engine, "examples/linking1.wat")?;
18     let linking2 = Module::from_file(&engine, "examples/linking2.wat")?;
19 
20     // Configure WASI and insert it into a `Store`
21     let wasi = WasiCtxBuilder::new()
22         .inherit_stdio()
23         .inherit_args()?
24         .build();
25     let mut store = Store::new(&engine, wasi);
26 
27     // Instantiate our first module which only uses WASI, then register that
28     // instance with the linker since the next linking will use it.
29     let linking2 = linker.instantiate(&mut store, &linking2)?;
30     linker.instance(&mut store, "linking2", linking2)?;
31 
32     // And with that we can perform the final link and the execute the module.
33     let linking1 = linker.instantiate(&mut store, &linking1)?;
34     let run = linking1.get_typed_func::<(), ()>(&mut store, "run")?;
35     run.call(&mut store, ())?;
36     Ok(())
37 }
38