pub trait WasmerEnv: Clone + Send + Sync {
fn init_with_instance(
&mut self,
_instance: &Instance
) -> Result<(), HostEnvInitError> { ... }
}
Expand description
Trait for initializing the environments passed to host functions after instantiation but before execution.
This is useful for filling an environment with data that can only be accesed after instantiation. For example, exported items such as memories and functions which don’t exist prior to instantiation can be accessed here so that host functions can use them.
Examples
This trait can be derived like so:
use wasmer::{WasmerEnv, LazyInit, Memory, NativeFunc};
#[derive(WasmerEnv, Clone)]
pub struct MyEnvWithNoInstanceData {
non_instance_data: u8,
}
#[derive(WasmerEnv, Clone)]
pub struct MyEnvWithInstanceData {
non_instance_data: u8,
#[wasmer(export)]
memory: LazyInit<Memory>,
#[wasmer(export(name = "real_name"))]
func: LazyInit<NativeFunc<(i32, i32), i32>>,
#[wasmer(export(optional = true, alias = "memory2", alias = "_memory2"))]
optional_memory: LazyInit<Memory>,
}
When deriving WasmerEnv
, you must wrap your types to be initialized in
LazyInit
. The derive macro will also generate helper methods of the form
<field_name>_ref
and <field_name>_ref_unchecked
for easy access to the
data.
The valid arguments to export
are:
name = "string"
: specify the name of this item in the Wasm module. If this is not specified, it will default to the name of the field.optional = true
: specify whether this export is optional. Defaults tofalse
. Being optional means that if the export can’t be found, theLazyInit
will be left uninitialized.alias = "string"
: specify additional names to look for in the Wasm module.alias
may be specified multiple times to search for multiple aliases.
This trait may also be implemented manually:
#[derive(Clone)]
pub struct MyEnv {
memory: LazyInit<Memory>,
}
impl WasmerEnv for MyEnv {
fn init_with_instance(&mut self, instance: &Instance) -> Result<(), HostEnvInitError> {
let memory: Memory = instance.exports.get_with_generics_weak("memory").unwrap();
self.memory.initialize(memory.clone());
Ok(())
}
}
When implementing the trait manually, it’s important to get a “weak” export to
prevent a cyclic reference leaking memory. You can access a “weak” export with
a method like get_with_generics_weak
.
Provided methods
fn init_with_instance(
&mut self,
_instance: &Instance
) -> Result<(), HostEnvInitError>
fn init_with_instance(
&mut self,
_instance: &Instance
) -> Result<(), HostEnvInitError>
The function that Wasmer will call on your type to let it finish
setting up the environment with data from the Instance
.
This function is called after Instance
is created but before it is
returned to the user via Instance::new
.