xref: /wasmtime-44.0.1/examples/multi.rs (revision 331b0dee)
1 //! This is an example of working with multi-value modules and dealing with
2 //! multi-value functions.
3 //!
4 //! Note that the `Func::wrap*` interfaces cannot be used to return multiple
5 //! values just yet, so we need to use the more dynamic `Func::new` and
6 //! `Func::call` methods.
7 
8 // You can execute this example with `cargo run --example multi`
9 
10 use anyhow::Result;
11 
12 #[cfg(not(feature = "old-x86-backend"))]
13 fn main() -> Result<()> {
14     use wasmtime::*;
15 
16     println!("Initializing...");
17     let engine = Engine::default();
18     let mut store = Store::new(&engine, ());
19 
20     // Compile.
21     println!("Compiling module...");
22     let module = Module::from_file(&engine, "examples/multi.wat")?;
23 
24     // Create a host function which takes multiple parameters and returns
25     // multiple results.
26     println!("Creating callback...");
27     let callback_func = Func::wrap(&mut store, |a: i32, b: i64| -> (i64, i32) {
28         (b + 1, a + 1)
29     });
30 
31     // Instantiate.
32     println!("Instantiating module...");
33     let instance = Instance::new(&mut store, &module, &[callback_func.into()])?;
34 
35     // Extract exports.
36     println!("Extracting export...");
37     let g = instance.get_typed_func::<(i32, i64), (i64, i32), _>(&mut store, "g")?;
38 
39     // Call `$g`.
40     println!("Calling export \"g\"...");
41     let (a, b) = g.call(&mut store, (1, 3))?;
42 
43     println!("Printing result...");
44     println!("> {} {}", a, b);
45 
46     assert_eq!(a, 4);
47     assert_eq!(b, 2);
48 
49     // Call `$round_trip_many`.
50     println!("Calling export \"round_trip_many\"...");
51     let round_trip_many = instance
52         .get_typed_func::<
53         (i64, i64, i64, i64, i64, i64, i64, i64, i64, i64),
54         (i64, i64, i64, i64, i64, i64, i64, i64, i64, i64),
55         _,
56         >
57         (&mut store, "round_trip_many")?;
58     let results = round_trip_many.call(&mut store, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9))?;
59 
60     println!("Printing result...");
61     println!("> {:?}", results);
62     assert_eq!(results, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9));
63 
64     Ok(())
65 }
66 
67 // Note that this example is not supported in the off-by-default feature of the
68 // old x86 compiler backend for Cranelift. Wasmtime's default configuration
69 // supports this example, however.
70 #[cfg(feature = "old-x86-backend")]
71 fn main() -> Result<()> {
72     Ok(())
73 }
74