Available on crate feature
runtime
and crate feature component-model
and docsrs
only.Expand description
Example of a world which exports a resource.
- Guest resources are modeled as
ResourceAny
. Note that this type is not specialized per-resource at this time so care must be taken to not mix them up. - Resource-related methods are a projection from a
Guest
structure, for example toGuestLogger
here. - Resource-related methods all take a
ResourceAny
as an argument or a return value. - The
ResourceAny
must be explicitly dropped.
use wasmtime::{Result, Engine, Store};
use wasmtime::component::{bindgen, Component, Linker};
use self::exports::example::exported_resources::logging::Level;
bindgen!({
inline: r#"
package example:exported-resources;
world export-some-resources {
export logging;
}
interface logging {
enum level {
debug,
info,
warn,
error,
}
resource logger {
constructor(max-level: level);
get-max-level: func() -> level;
set-max-level: func(level: level);
log: func(level: level, msg: string);
}
}
"#,
});
struct MyState;
fn main() -> Result<()> {
let engine = Engine::default();
let component = Component::from_file(&engine, "./your-component.wasm")?;
let linker = Linker::new(&engine);
// ... this small example has no imports so nothing is added here, but
// if you had imports this is where they'd go.
let mut store = Store::new(&engine, MyState);
let bindings = ExportSomeResources::instantiate(&mut store, &component, &linker)?;
let guest = bindings.example_exported_resources_logging();
let logger = guest.logger();
// Resource methods are all attached to `logger` and take the
// `ResourceAny` parameter explicitly.
let my_logger = logger.call_constructor(&mut store, Level::Warn)?;
assert_eq!(logger.call_get_max_level(&mut store, my_logger)?, Level::Warn);
logger.call_set_max_level(&mut store, my_logger, Level::Info)?;
logger.call_log(&mut store, my_logger, Level::Debug, "hello!")?;
// The `ResourceAny` type has no destructor but when the host is done
// with it it needs to invoke the guest-level destructor.
my_logger.resource_drop(&mut store)?;
Ok(())
}
Modules§
Structs§
- Auto-generated bindings for an instance a component which implements the world
export-some-resources
. - Auto-generated bindings for index of the exports of
export-some-resources
. - Auto-generated bindings for a pre-instantiated version of a component which implements the world
export-some-resources
.