From bb734d925e50e16dd57eb67e6adb90b74fcb778b Mon Sep 17 00:00:00 2001 From: Ryan Levick Date: Thu, 28 Mar 2024 10:55:25 +0100 Subject: [PATCH] Provide example usage in wasmtime crate doc Signed-off-by: Ryan Levick --- crates/wasmtime/src/runtime/component/mod.rs | 58 ++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/crates/wasmtime/src/runtime/component/mod.rs b/crates/wasmtime/src/runtime/component/mod.rs index b9f81350c6ab..e72710797a03 100644 --- a/crates/wasmtime/src/runtime/component/mod.rs +++ b/crates/wasmtime/src/runtime/component/mod.rs @@ -38,6 +38,64 @@ //! It's recommended to read over the [documentation for the Component //! Model][Component Model] to get an overview about how to build components //! from various languages. +//! +//! ## Example Usage +//! +//! Imagine you have the following WIT package definition in a file called world.wit +//! along with a component (my_component.wasm) that targets `my-world`: +//! +//! ```text,ignore +//! package component:my-package; +//! +//! world my-world { +//! import name: func() -> string; +//! export greet: func() -> string; +//! } +//! ``` +//! +//! You can instantiate and call the component like so: +//! +//! ``` +//! fn main() -> wasmtime::Result<()> { +//! # if true { return Ok(()) } +//! // Instantiate the engine and store +//! let engine = wasmtime::Engine::default(); +//! let mut store = wasmtime::Store::new(&engine, ()); +//! +//! // Load the component from disk +//! let bytes = std::fs::read("my_component.wasm")?; +//! let component = wasmtime::component::Component::new(&engine, bytes)?; +//! +//! // Configure the linker +//! let mut linker = wasmtime::component::Linker::new(&engine); +//! // The component expects one import `name` that +//! // takes no params and returns a string +//! linker +//! .root() +//! .func_wrap("name", |_store, _params: ()| { +//! Ok((String::from("Alice"),)) +//! })?; +//! +//! // Instantiate the component +//! let instance = linker.instantiate(&mut store, &component)?; +//! +//! // Call the `greet` function +//! let func = instance.get_func(&mut store, "greet").expect("greet export not found"); +//! let mut result = [wasmtime::component::Val::String("".into())]; +//! func.call(&mut store, &[], &mut result)?; +//! +//! // This should print out `Greeting: [String("Hello, Alice!")]` +//! println!("Greeting: {:?}", result); +//! +//! Ok(()) +//! } +//! ``` +//! +//! Manually configuring the linker and calling untyped component exports is +//! a bit tedious and error prone. The [`bindgen!`] macro can be used to +//! generate bindings eliminating much of this boilerplate. +//! +//! See the docs for [`bindgen!`] for more information on how to use it. #![cfg_attr(docsrs, doc(cfg(feature = "component-model")))]