Call an exported WebAssembly function
wasmtime embeds a WebAssembly runtime inside a Rust host
program. This recipe compiles a module from WebAssembly Text format
(WAT), instantiates it, and calls an exported function.
The three core types are Engine, which holds compiler settings;
Module, which holds compiled bytecode; and Store, which
holds all runtime state for a set of instances.
Instance::new links the compiled module with its imports
(none here) and produces a live instance. get_typed_func
looks up an export by name and checks that its signature matches the Rust
generic parameters — (i32, i32) in, i32 out.
Core WebAssembly function parameters are limited to four numeric types:
i32, i64, f32, and f64. Strings, structs, and other complex values
cannot cross the function boundary directly — see Exchange data via linear
memory for the pointer-and-length pattern, or the
Component Model for a higher-level IDL that lifts
these restrictions.
use anyhow::Result;
use wasmtime::{Engine, Instance, Module, Store};
fn main() -> Result<()> {
let engine = Engine::default();
let module = Module::new(
&engine,
r#"
(module
(func (export "add") (param i32 i32) (result i32)
local.get 0
local.get 1
i32.add)
)
"#,
)?;
let mut store = Store::new(&engine, ());
let instance = Instance::new(&mut store, &module, &[])?;
let add = instance.get_typed_func::<(i32, i32), i32>(&mut store, "add")?;
let result = add.call(&mut store, (5, 37))?;
println!("5 + 37 = {result}");
Ok(())
}
Run it:
cargo run --manifest-path crates/wasm/Cargo.toml --bin call_export
# 5 + 37 = 42