Skip to main content

ModuleInstance

Struct ModuleInstance 

Source
pub struct ModuleInstance(/* private fields */);
Expand description

An instantiated WebAssembly module

Create a ModuleInstance by parsing a module, creating a Store, and then calling ModuleInstance::instantiate.

§Example

let module = tinywasm::parse_bytes(&wasm)?;
let mut store = Store::default();
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;

Backed by an Rc, so cloning is cheap

See https://webassembly.github.io/spec/core/exec/runtime.html#module-instances

Implementations§

Source§

impl ModuleInstance

Source

pub fn id(&self) -> ModuleInstanceAddr

Get the module instance’s address

Source

pub fn instantiate( store: &mut Store, module: &Module, imports: Option<Imports>, ) -> Result<Self>

Source

pub fn instantiate_no_start( store: &mut Store, module: &Module, imports: Option<Imports>, ) -> Result<Self>

Instantiate the module in the given store (without running the start function)

§Example
let mut store = Store::default();
let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?;

assert_eq!(instance.global_get(&store, "g")?, 0.into());
instance.start(&mut store)?;
assert_eq!(instance.global_get(&store, "g")?, 42.into());

See https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation

Source

pub fn export_addr(&self, name: &str) -> Option<ExternVal>

Get a export by name

Source

pub fn exports(&self) -> impl Iterator<Item = (&str, ExternItem)> + '_

Returns an iterator over all exported extern values for this instance.

§Example
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;

let mut saw_func = false;
let mut saw_memory = false;
for (name, item) in instance.exports() {
    match (name, item) {
        ("f", ExternItem::Func(_)) => saw_func = true,
        ("mem", ExternItem::Memory(_)) => saw_memory = true,
        _ => {}
    }
}
assert!(saw_func && saw_memory);
Source

pub fn extern_item(&self, name: &str) -> Result<ExternItem>

Get any exported extern value by name.

§Example
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;

let ExternItem::Global(global) = instance.extern_item("answer")? else {
    panic!("expected global export");
};
assert_eq!(global.get(&store)?, 42.into());
Source

pub fn func_untyped(&self, store: &Store, name: &str) -> Result<Function>

Get a function export by name.

§Example
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
let add = instance.func_untyped(&store, "add")?;
let result = add.call(&mut store, &[WasmValue::I32(20), WasmValue::I32(22)])?;
assert_eq!(result, vec![WasmValue::I32(42)]);

For typed access, see Self::func.

Source

pub fn func_by_index( &self, store: &Store, func_index: FuncAddr, ) -> Result<Function>

Available on crate feature guest-debug only.

Get a function by its module-local index.

This exposes an internal module-owned function directly and bypasses the normal export boundary. It is mainly intended for tooling and introspection. Calling private functions can change behavior in ways the module author did not expose as part of the public API.

Source

pub fn func<P: IntoWasmValues + ToWasmTypes, R: FromWasmValues + ToWasmTypes>( &self, store: &Store, name: &str, ) -> Result<FunctionTyped<P, R>>

Get a typed function export by name.

§Example
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
let add = instance.func::<(i32, i32), i32>(&store, "add")?;
assert_eq!(add.call(&mut store, (20, 22))?, 42);

For untyped access, see Self::func_untyped and Self::extern_item.

For signatures that exceed tuple arity 12, see crate::WasmTupleChain, which can be used directly as instance.func::<crate::WasmTupleChain<_, _>, _>(...).

Source

pub fn func_typed_by_index<P: IntoWasmValues + ToWasmTypes, R: FromWasmValues + ToWasmTypes>( &self, store: &Store, func_index: FuncAddr, ) -> Result<FunctionTyped<P, R>>

Available on crate feature guest-debug only.

Get a typed function by its module-local index.

Source

pub fn memory(&self, name: &str) -> Result<Memory>

Get a memory export by name.

Source

pub fn memory_by_index(&self, memory_index: MemAddr) -> Result<Memory>

Available on crate feature guest-debug only.

Get a memory by its module-local index.

This exposes an internal module-owned memory directly and bypasses the normal export boundary. It is mainly intended for tooling and inspection. Mutating a private memory can change module behavior in ways that are not part of the module’s public API.

Source

pub fn table(&self, name: &str) -> Result<Table>

Get a table export by name.

Source

pub fn table_by_index(&self, table_index: TableAddr) -> Result<Table>

Available on crate feature guest-debug only.

Get a table by its module-local index.

This exposes an internal module-owned table directly and bypasses the normal export boundary. It is mainly intended for tooling and inspection. Mutating a private table can change module behavior in ways that are not part of the module’s public API.

Source

pub fn global_get(&self, store: &Store, name: &str) -> Result<WasmValue>

Get the value of a global export by name.

Source

pub fn global(&self, name: &str) -> Result<Global>

Get a global export by name.

Source

pub fn global_set( &self, store: &mut Store, name: &str, value: WasmValue, ) -> Result<()>

Set the value of a mutable global export by name.

Source

pub fn global_by_index(&self, global_index: GlobalAddr) -> Result<Global>

Available on crate feature guest-debug only.

Get a global by its module-local index.

This exposes an internal module-owned global directly and bypasses the normal export boundary. It is mainly intended for tooling and inspection. Mutating a private global can change module behavior in ways that are not part of the module’s public API.

Source

pub fn start_func(&self, store: &Store) -> Result<Option<Function>>

Get the start function of the module

Returns None if the module has no start function If no start function is specified, also checks for a _start function in the exports

§Example
let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?;
assert!(instance.start_func(&store)?.is_some());

See https://webassembly.github.io/spec/core/syntax/modules.html#start-function

Source

pub fn start(&self, store: &mut Store) -> Result<Option<()>>

Invoke the start function of the module

Returns None if the module has no start function

§Example
let mut store = Store::default();
let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?;

assert_eq!(instance.global_get(&store, "g")?, 0.into());
assert_eq!(instance.start(&mut store)?, Some(()));
assert_eq!(instance.global_get(&store, "g")?, 7.into());

See https://webassembly.github.io/spec/core/syntax/modules.html#syntax-start

Trait Implementations§

Source§

impl Clone for ModuleInstance

Source§

fn clone(&self) -> ModuleInstance

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ModuleInstance

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.