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

Example of all kinds of structures of exports from a world.

use wasmtime::{Result, Engine, Store};
use wasmtime::component::{bindgen, Component, Linker};

bindgen!({
    inline: r#"
        package example:world-exports;

        world with-exports {
            import log: func(msg: string);

            export run: func();

            /// An example of exporting an interface inline and naming it
            /// directly.
            export environment: interface {
                get: func(var: string) -> string;
                set: func(var: string, val: string);
            }

            /// An example of exporting an interface.
            export units;
        }

        interface units {
            /// Renders the number of bytes as a human readable string.
            bytes-to-string: func(bytes: u64) -> string;

            /// Renders the provided duration as a human readable string.
            duration-to-string: func(seconds: u64, ns: u32) -> string;
        }
    "#,
});

struct MyState;

impl WithExportsImports for MyState {
    fn log(&mut self, msg: String) {
        println!("{msg}");
    }
}

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

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

    let mut store = Store::new(&engine, MyState);
    let bindings = WithExports::instantiate(&mut store, &component, &linker)?;

    // top-level functions are exported directly on `WithExports` and are
    // all prefixed with `call_*`.
    bindings.call_run(&mut store)?;

    // exported named interfaces are named directly after their export name
    // and the `&Guest` return value has `call_*` functions on it.
    bindings.environment().call_set(&mut store, "key", "value")?;
    let value = bindings.environment().call_get(&mut store, "key")?;
    assert_eq!(value, "value");

    // exported interfaces by id are similar to export-by-name except that
    // the exported name is modeled after the full id, not just the name.
    let units = bindings.example_world_exports_units();
    let bytes = 1 << 30 + 1 << 20;
    let s = units.call_bytes_to_string(&mut store, bytes)?;
    println!("{bytes} = {s}");

    let (seconds, ns) = (1 << 20, 12345);
    let s = units.call_duration_to_string(&mut store, seconds, ns)?;
    println!("{seconds}s + {ns}ns = {s}");
    Ok(())
}

Modules§

Structs§

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

Traits§