Define host functions for WebAssembly
[![wasmtime-badge]][wasmtime] [![cat-wasm-badge]][cat-wasm]
WebAssembly modules can import functions from the host, enabling guests to
call back into Rust. This recipe defines a print function in the host that
the WASM guest calls to write a message stored in its own linear memory.
Func::wrap creates a host-defined function from a Rust closure.
The first parameter is a Caller — a handle to the calling
instance's store. The guest module declares the import with
(import "host" "print" ...) and the host passes [print_fn.into()] as the
imports slice to Instance::new.
Instance::new takes &[Extern] — the enum that can hold a
Func, Memory, Global, or Table. .into() converts the
Func into an Extern so the slice type is satisfied.
Inside the closure, Caller::get_export retrieves the guest's
memory export so the host can read the bytes the guest passed by pointer and
length.
Run it:
cargo run --manifest-path crates/wasm/Cargo.toml --bin host_fn
# [wasm] Hello from WebAssembly!
{{#include ../links.md}}