Available on crate feature runtime and crate feature component-model and docsrs only.
Expand description

An example of generated bindings for top-level exported functions for a world.

Some notable generated items here are:

use wasmtime::component::*;
use wasmtime::{Engine, Store};

bindgen!({
    inline: r#"
        package my:project;

        interface host {
            gen-random-integer: func() -> u32;
            sha256: func(bytes: list<u8>) -> string;
        }

        world hello-world {
            import host;

            export demo: interface {
                run: func();
            }
        }
    "#,
});

struct MyState {
    // ...
}

// Note that the trait here is per-interface and within a submodule now.
impl my::project::host::Host for MyState {
    fn gen_random_integer(&mut self) -> u32 {
        rand::thread_rng().gen()
    }

    fn sha256(&mut self, bytes: Vec<u8>) -> String {
        // ...
    }
}

fn main() -> wasmtime::Result<()> {
    let engine = Engine::default();
    let component = Component::from_file(&engine, "./your-component.wasm")?;

    let mut linker = Linker::new(&engine);
    HelloWorld::add_to_linker(&mut linker, |state: &mut MyState| state)?;

    let mut store = Store::new(
        &engine,
        MyState { /* ... */ },
    );
    let bindings = HelloWorld::instantiate(&mut store, &component, &linker)?;

    // Note that the `demo` method returns a `&exports::Demo::Guest`
    // through which we can run the methods on that interface.
    bindings.demo().call_run(&mut store)?;
    Ok(())
}

Modules§

Structs§

  • Auto-generated bindings for an instance a component which implements the world hello-world.
  • Auto-generated bindings for index of the exports of hello-world.
  • Auto-generated bindings for a pre-instantiated version of a component which implements the world hello-world.