xref: /wasmtime-44.0.1/examples/multi.rs (revision e9e4afe2)
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 store = Store::new(&engine);
19 
20     // Compile.
21     println!("Compiling module...");
22     let module = Module::from_file(&engine, "examples/multi.wat")?;
23 
24     // Create external print functions.
25     println!("Creating callback...");
26     let callback_type = FuncType::new(
27         [ValType::I32, ValType::I64].iter().cloned(),
28         [ValType::I64, ValType::I32].iter().cloned(),
29     );
30     let callback_func = Func::new(&store, callback_type, |_, args, results| {
31         println!("Calling back...");
32         println!("> {} {}", args[0].unwrap_i32(), args[1].unwrap_i64());
33 
34         results[0] = Val::I64(args[1].unwrap_i64() + 1);
35         results[1] = Val::I32(args[0].unwrap_i32() + 1);
36         Ok(())
37     });
38 
39     // Instantiate.
40     println!("Instantiating module...");
41     let instance = Instance::new(&store, &module, &[callback_func.into()])?;
42 
43     // Extract exports.
44     println!("Extracting export...");
45     let g = instance.get_typed_func::<(i32, i64), (i64, i32)>("g")?;
46 
47     // Call `$g`.
48     println!("Calling export \"g\"...");
49     let (a, b) = g.call((1, 3))?;
50 
51     println!("Printing result...");
52     println!("> {} {}", a, b);
53 
54     assert_eq!(a, 4);
55     assert_eq!(b, 2);
56 
57     // Call `$round_trip_many`.
58     println!("Calling export \"round_trip_many\"...");
59     let round_trip_many = instance
60         .get_typed_func::<
61         (i64, i64, i64, i64, i64, i64, i64, i64, i64, i64),
62         (i64, i64, i64, i64, i64, i64, i64, i64, i64, i64),
63         >
64         ("round_trip_many")?;
65     let results = round_trip_many.call((0, 1, 2, 3, 4, 5, 6, 7, 8, 9))?;
66 
67     println!("Printing result...");
68     println!("> {:?}", results);
69     assert_eq!(results, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9));
70 
71     Ok(())
72 }
73 
74 #[cfg(feature = "old-x86-backend")]
75 fn main() -> Result<()> {
76     Ok(())
77 }
78