Files
wasmtime/docs/examples-rust-wasi.md
Alex Crichton 7a1b7cdf92 Implement RFC 11: Redesigning Wasmtime's APIs (#2897)
Implement Wasmtime's new API as designed by RFC 11. This is quite a large commit which has had lots of discussion externally, so for more information it's best to read the RFC thread and the PR thread.
2021-06-03 09:10:53 -05:00

2.0 KiB

WASI

You can also browse this source code online and clone the wasmtime repository to run the example locally.

This example shows how to use the wasmtime-wasi crate to define WASI functions within a Linker which can then be used to instantiate a WebAssembly module.

Wasm Source code

{{#include ../examples/wasi/wasm/wasi.rs}}

wasi.rs

{{#include ../examples/wasi/main.rs}}

WASI state with other custom host state

The add_to_linker takes a second argument which is a closure to access &mut WasiCtx from within the T stored in the Store<T> itself. In the above example this is trivial because the T in Store<T> is WasiCtx itself, but you can also store other state in Store like so:

# extern crate wasmtime;
# extern crate wasmtime_wasi;
# extern crate anyhow;
use anyhow::Result;
use std::borrow::{Borrow, BorrowMut};
use wasmtime::*;
use wasmtime_wasi::{WasiCtx, sync::WasiCtxBuilder};

struct MyState {
    message: String,
    wasi: WasiCtx,
}

fn main() -> Result<()> {
    let engine = Engine::default();
    let mut linker = Linker::new(&engine);
    wasmtime_wasi::add_to_linker(&mut linker, |state: &mut MyState| &mut state.wasi)?;

    let wasi = WasiCtxBuilder::new()
        .inherit_stdio()
        .inherit_args()?
        .build();
    let mut store = Store::new(&engine, MyState {
        message: format!("hello!"),
        wasi,
    });

    // ...

# let _linker: Linker<MyState> = linker;
    Ok(())
}