Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bytecodealliance
GitHub Repository: bytecodealliance/wasmtime
Path: blob/main/examples/multi.rs
1685 views
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
fn main() -> Result<()> {
13
use wasmtime::*;
14
15
println!("Initializing...");
16
let engine = Engine::default();
17
let mut store = Store::new(&engine, ());
18
19
// Compile.
20
println!("Compiling module...");
21
let module = Module::from_file(&engine, "examples/multi.wat")?;
22
23
// Create a host function which takes multiple parameters and returns
24
// multiple results.
25
println!("Creating callback...");
26
let callback_func = Func::wrap(&mut store, |a: i32, b: i64| -> (i64, i32) {
27
(b + 1, a + 1)
28
});
29
30
// Instantiate.
31
println!("Instantiating module...");
32
let instance = Instance::new(&mut store, &module, &[callback_func.into()])?;
33
34
// Extract exports.
35
println!("Extracting export...");
36
let g = instance.get_typed_func::<(i32, i64), (i64, i32)>(&mut store, "g")?;
37
38
// Call `$g`.
39
println!("Calling export \"g\"...");
40
let (a, b) = g.call(&mut store, (1, 3))?;
41
42
println!("Printing result...");
43
println!("> {a} {b}");
44
45
assert_eq!(a, 4);
46
assert_eq!(b, 2);
47
48
// Call `$round_trip_many`.
49
println!("Calling export \"round_trip_many\"...");
50
let round_trip_many = instance
51
.get_typed_func::<
52
(i64, i64, i64, i64, i64, i64, i64, i64, i64, i64),
53
(i64, i64, i64, i64, i64, i64, i64, i64, i64, i64),
54
>
55
(&mut store, "round_trip_many")?;
56
let results = round_trip_many.call(&mut store, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9))?;
57
58
println!("Printing result...");
59
println!("> {results:?}");
60
assert_eq!(results, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9));
61
62
Ok(())
63
}
64
65