wasmtime_wasi::preview1

Function add_to_linker_sync

source
pub fn add_to_linker_sync<T: Send>(
    linker: &mut Linker<T>,
    f: impl Fn(&mut T) -> &mut WasiP1Ctx + Copy + Send + Sync + 'static,
) -> Result<()>
Available on crate feature preview1 only.
Expand description

Adds synchronous versions of all WASIp1 functions to the [wasmtime::Linker] provided.

This method will add WASIp1 functions to linker. The f closure provided is used to project from the T state that Linker is associated with to a WasiP1Ctx. If T is WasiP1Ctx itself then this is the identity closure, but otherwise it must project out the field where WasiP1Ctx is stored within T.

The state provided by f is used to implement all WASIp1 functions and provides configuration to know what to return.

Note that this function is intended for use with Config::async_support(false). If you’re looking for a synchronous version see add_to_linker_async.

§Examples

If the T in Linker<T> is just WasiP1Ctx:

use wasmtime::{Result, Linker, Engine, Config};
use wasmtime_wasi::preview1::{self, WasiP1Ctx};

fn main() -> Result<()> {
    let mut config = Config::new();
    config.async_support(true);
    let engine = Engine::new(&config)?;

    let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);
    preview1::add_to_linker_async(&mut linker, |cx| cx)?;

    // ... continue to add more to `linker` as necessary and use it ...

    Ok(())
}

If the T in Linker<T> is custom state:

use wasmtime::{Result, Linker, Engine, Config};
use wasmtime_wasi::preview1::{self, WasiP1Ctx};

struct MyState {
    // .. other custom state here ..

    wasi: WasiP1Ctx,
}

fn main() -> Result<()> {
    let mut config = Config::new();
    config.async_support(true);
    let engine = Engine::new(&config)?;

    let mut linker: Linker<MyState> = Linker::new(&engine);
    preview1::add_to_linker_async(&mut linker, |cx| &mut cx.wasi)?;

    // ... continue to add more to `linker` as necessary and use it ...

    Ok(())
}