Struct wasmer::Function

source ·
pub struct Function(pub(crate) Function);
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

Tuple Fields§

§0: Function

Implementations§

source§

impl Function

source

pub fn new<FT, F>(store: &mut impl AsStoreMut, ty: FT, func: F) -> Selfwhere 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 ) -> Selfwhere 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) -> Selfwhere 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 ) -> Selfwhere 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(crate) fn vm_funcref(&self, store: &impl AsStoreRef) -> VMFuncRef

source

pub(crate) unsafe fn from_vm_funcref( store: &mut impl AsStoreMut, funcref: VMFuncRef ) -> Self

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(crate) fn from_vm_extern( store: &mut impl AsStoreMut, vm_extern: InternalStoreHandle<VMFunction> ) -> Self

source

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

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

source

pub(crate) fn to_vm_extern(&self) -> VMExtern

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 Functionwhere 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.
§

type Abi = usize

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

impl PartialEq<Function> for Function

source§

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

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

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

This method 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 Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> ArchivePointee for T

§

type ArchivedMetadata = ()

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

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 Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
§

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

§

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 Qwhere 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.
§

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

§

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

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

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

§

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

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

impl<'a, T> ExportableWithGenerics<'a, (), ()> for Twhere T: Exportable<'a> + Clone + 'static,

source§

fn get_self_from_extern_with_generics( _extern: &'a Extern ) -> Result<T, ExportError>

Get an export with the given generics.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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 Twhere 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.

§

impl<T> LayoutRaw for T

§

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

Gets the layout of the type.
§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

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

impl<T> Pointee for T

§

type Metadata = ()

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

impl<T> ToOwned for Twhere T: Clone,

§

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 Twhere U: Into<T>,

§

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 Twhere U: TryFrom<T>,

§

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.
§

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

§

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

upcast ref
§

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

upcast mut ref
§

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

upcast boxed dyn
§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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