Struct wasmer::Function

source ·
pub struct Function(/* private fields */);
Expand description

A WebAssembly function instance.

A function instance is the runtime representation of a function. It effectively is a closure of the original function (defined in either the host or the WebAssembly module) over the runtime Instance of its originating Module.

The module instance is used to resolve references to other definitions during execution of the function.

Spec: https://webassembly.github.io/spec/core/exec/runtime.html#function-instances

§Panics

  • Closures (functions with captured environments) are not currently supported with native functions. Attempting to create a native Function with one will result in a panic. Closures as host functions tracking issue

Implementations§

source§

impl Function

source

pub fn new<FT, F>(store: &mut impl AsStoreMut, ty: FT, func: F) -> Self
where FT: Into<FunctionType>, F: Fn(&[Value]) -> Result<Vec<Value>, RuntimeError> + 'static + Send + Sync,

Creates a new host Function (dynamic) with the provided signature.

If you know the signature of the host function at compile time, consider using Function::new_typed for less runtime overhead.

source

pub fn new_with_env<FT, F, T: Send + 'static>( store: &mut impl AsStoreMut, env: &FunctionEnv<T>, ty: FT, func: F, ) -> Self
where FT: Into<FunctionType>, F: Fn(FunctionEnvMut<'_, T>, &[Value]) -> Result<Vec<Value>, RuntimeError> + 'static + Send + Sync,

Creates a new host Function (dynamic) with the provided signature.

If you know the signature of the host function at compile time, consider using Function::new_typed_with_env for less runtime overhead.

Takes a FunctionEnv that is passed into func. If that is not required, Function::new might be an option as well.

§Examples
let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]);

let f = Function::new_with_env(&mut store, &env, &signature, |_env, args| {
    let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
    Ok(vec![Value::I32(sum)])
});

With constant signature:

const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]);

let f = Function::new_with_env(&mut store, &env, I32_I32_TO_I32, |_env, args| {
    let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
    Ok(vec![Value::I32(sum)])
});
source

pub fn new_typed<F, Args, Rets>(store: &mut impl AsStoreMut, func: F) -> Self
where F: HostFunction<(), Args, Rets, WithoutEnv> + 'static + Send + Sync, Args: WasmTypeList, Rets: WasmTypeList,

Creates a new host Function from a native function.

source

pub fn new_typed_with_env<T: Send + 'static, F, Args, Rets>( store: &mut impl AsStoreMut, env: &FunctionEnv<T>, func: F, ) -> Self
where F: HostFunction<T, Args, Rets, WithEnv> + 'static + Send + Sync, Args: WasmTypeList, Rets: WasmTypeList,

Creates a new host Function with an environment from a typed function.

The function signature is automatically retrieved using the Rust typing system.

§Example
fn sum(_env: FunctionEnvMut<()>, a: i32, b: i32) -> i32 {
    a + b
}

let f = Function::new_typed_with_env(&mut store, &env, sum);
source

pub fn ty(&self, store: &impl AsStoreRef) -> FunctionType

Returns the FunctionType of the Function.

§Example
fn sum(_env: FunctionEnvMut<()>, a: i32, b: i32) -> i32 {
    a + b
}

let f = Function::new_typed_with_env(&mut store, &env, sum);

assert_eq!(f.ty(&mut store).params(), vec![Type::I32, Type::I32]);
assert_eq!(f.ty(&mut store).results(), vec![Type::I32]);
source

pub fn param_arity(&self, store: &impl AsStoreRef) -> usize

Returns the number of parameters that this function takes.

§Example
fn sum(_env: FunctionEnvMut<()>, a: i32, b: i32) -> i32 {
    a + b
}

let f = Function::new_typed_with_env(&mut store, &env, sum);

assert_eq!(f.param_arity(&mut store), 2);
source

pub fn result_arity(&self, store: &impl AsStoreRef) -> usize

Returns the number of results this function produces.

§Example
fn sum(_env: FunctionEnvMut<()>, a: i32, b: i32) -> i32 {
    a + b
}

let f = Function::new_typed_with_env(&mut store, &env, sum);

assert_eq!(f.result_arity(&mut store), 1);
source

pub fn call( &self, store: &mut impl AsStoreMut, params: &[Value], ) -> Result<Box<[Value]>, RuntimeError>

Call the Function function.

Depending on where the Function is defined, it will call it.

  1. If the function is defined inside a WebAssembly, it will call the trampoline for the function signature.
  2. If the function is defined in the host (in a native way), it will call the trampoline.
§Examples
let sum = instance.exports.get_function("sum").unwrap();

assert_eq!(sum.call(&mut store, &[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]);
source

pub fn typed<Args, Rets>( &self, store: &impl AsStoreRef, ) -> Result<TypedFunction<Args, Rets>, RuntimeError>
where Args: WasmTypeList, Rets: WasmTypeList,

Transform this WebAssembly function into a typed function. See TypedFunction to learn more.

§Examples
let sum = instance.exports.get_function("sum").unwrap();
let sum_typed: TypedFunction<(i32, i32), i32> = sum.typed(&mut store).unwrap();

assert_eq!(sum_typed.call(&mut store, 1, 2).unwrap(), 3);
§Errors

If the Args generic parameter does not match the exported function an error will be raised:

let sum = instance.exports.get_function("sum").unwrap();

// This results in an error: `RuntimeError`
let sum_typed : TypedFunction<(i64, i64), i32> = sum.typed(&mut store).unwrap();

If the Rets generic parameter does not match the exported function an error will be raised:

let sum = instance.exports.get_function("sum").unwrap();

// This results in an error: `RuntimeError`
let sum_typed: TypedFunction<(i32, i32), i64> = sum.typed(&mut store).unwrap();
source

pub fn is_from_store(&self, store: &impl AsStoreRef) -> bool

Checks whether this Function can be used with the given store.

Trait Implementations§

source§

impl Clone for Function

source§

fn clone(&self) -> Function

Returns a copy of the value. Read more
1.0.0 · source§

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

Performs copy-assignment from source. Read more
source§

impl Debug for Function

source§

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

Formats the value using the given formatter. Read more
source§

impl<'a> Exportable<'a> for Function

source§

fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError>

Implementation of how to get the export corresponding to the implementing type from an Instance by name.
source§

impl From<Function> for Extern

source§

fn from(r: Function) -> Self

Converts to this type from the input type.
source§

impl From<Function> for Value

source§

fn from(val: Function) -> Self

Converts to this type from the input type.
source§

impl<Args, Rets> From<TypedFunction<Args, Rets>> for Function
where Args: WasmTypeList, Rets: WasmTypeList,

source§

fn from(other: TypedFunction<Args, Rets>) -> Self

Converts to this type from the input type.
source§

impl NativeWasmType for Function

source§

const WASM_TYPE: Type = Type::FuncRef

Type for this NativeWasmType.
source§

type Abi = usize

The ABI for this type (i32, i64, f32, f64)
source§

impl PartialEq for Function

source§

fn eq(&self, other: &Function) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl Eq for Function

source§

impl StructuralPartialEq for Function

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> ArchivePointee for T

source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
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, dst: *mut T)

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

impl<F, W, T, D> Deserialize<With<T, W>, D> for F
where W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized,

source§

fn deserialize( &self, deserializer: &mut D, ) -> Result<With<T, W>, <D as Fallible>::Error>

Deserializes using the given deserializer
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> LayoutRaw for T

source§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Gets the layout of the type.
source§

impl<T> Pointable for T

source§

const ALIGN: usize = _

The alignment of pointer.
source§

type Init = T

The type for initializers.
source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Pointee for T

source§

type Metadata = ()

The type for metadata in pointers and references to Self.
source§

impl<T> Same for T

source§

type Output = T

Should always be Self
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.
source§

impl<T> Upcastable for T
where T: Any + Send + Sync + 'static,

source§

fn upcast_any_ref(&self) -> &(dyn Any + 'static)

upcast ref
source§

fn upcast_any_mut(&mut self) -> &mut (dyn Any + 'static)

upcast mut ref
source§

fn upcast_any_box(self: Box<T>) -> Box<dyn Any>

upcast boxed dyn
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more