Struct wasmedge_sys::Function

source ·
pub struct Function { /* private fields */ }
Expand description

Defines a host function.

A WasmEdge Function defines a WebAssembly host function described by its type. A host function is a closure of the original function defined in either the host or the WebAssembly module.

Implementations§

source§

impl Function

source

pub fn create_sync_func<T>( ty: &FuncType, real_fn: Box<dyn Fn(CallingFrame, Vec<WasmValue>, *mut c_void) -> Result<Vec<WasmValue>, HostFuncError> + Send + Sync>, data: Option<Box<T>>, cost: u64 ) -> WasmEdgeResult<Self>

Creates a host function with the given function type.

N.B. that this function is used for thread-safe scenarios.

Arguments
  • ty - The types of the arguments and returns of the target function.

  • real_fn - The pointer to the target function.

  • data - The host context data used in this function.

  • cost - The function cost in the Statistics. Pass 0 if the calculation is not needed.

Error
Example

The example defines a host function real_add, and creates a Function binding to it by calling the create_binding method.

use wasmedge_macro::sys_host_function;
use wasmedge_sys::{FuncType, Function, WasmValue, CallingFrame};
use wasmedge_types::{error::HostFuncError, ValType, WasmEdgeResult, NeverType};

#[sys_host_function]
fn real_add(_frame: CallingFrame, inputs: Vec<WasmValue>) -> Result<Vec<WasmValue>, HostFuncError> {
    if inputs.len() != 2 {
        return Err(HostFuncError::User(1));
    }

    let a = if inputs[0].ty() == ValType::I32 {
        inputs[0].to_i32()
    } else {
        return Err(HostFuncError::User(2));
    };

    let b = if inputs[1].ty() == ValType::I32 {
        inputs[1].to_i32()
    } else {
        return Err(HostFuncError::User(3));
    };

    let c = a + b;

    Ok(vec![WasmValue::from_i32(c)])
}

// create a FuncType
let func_ty = FuncType::create(vec![ValType::I32; 2], vec![ValType::I32]).expect("fail to create a FuncType");

// create a Function instance
let func = Function::create_sync_func::<NeverType>(&func_ty, Box::new(real_add), None, 0).expect("fail to create a Function instance");
source

pub fn create_async_func<T: Send + Sync>( ty: &FuncType, real_fn: Box<dyn Fn(CallingFrame, Vec<WasmValue>, *mut c_void) -> Box<dyn Future<Output = Result<Vec<WasmValue>, HostFuncError>> + Send> + Send + Sync>, data: Option<Box<T>>, cost: u64 ) -> WasmEdgeResult<Self>

Available on crate feature async and Linux only.

Creates an async host function with the given function type.

Arguments
  • ty - The types of the arguments and returns of the target function.

  • real_fn - The pointer to the target function.

  • data - The host context data used in this function.

  • cost - The function cost in the Statistics. Pass 0 if the calculation is not needed.

Error
source

pub unsafe fn create_with_custom_wrapper( ty: &FuncType, fn_wrapper: CustomFnWrapper, real_fn: *mut c_void, data: *mut c_void, data_owner: bool, cost: u64 ) -> WasmEdgeResult<Self>

Creates a host function with the given function type and the custom function wrapper.

Arguments
  • ty - The types of the arguments and returns of the target function.

  • fn_wrapper - The custom function wrapper.

  • real_fn - The pointer to the target function.

  • data - The pointer to the host context data used in this function.

  • data_owner - Whether the host context data is owned by the host function.

  • cost - The function cost in the Statistics. Pass 0 if the calculation is not needed.

Error
Safety

Notice that the caller should guarantee the life cycle of both the real_fn and the data object.

source

pub fn ty(&self) -> WasmEdgeResult<FuncType>

Returns the underlying wasm type of this Function.

Errors

If fail to get the function type, then an error is returned.

source

pub fn call<E: Engine>( &self, engine: &E, args: impl IntoIterator<Item = WasmValue> ) -> WasmEdgeResult<Vec<WasmValue>>

Runs this host function and returns the result.

Arguments
  • engine - The object implementing the Engine trait.

  • args - The arguments passed to the host function.

Error

If fail to run the host function, then an error is returned.

source

pub async fn call_async<E: Engine + Send + Sync>( &self, async_state: &AsyncState, engine: &E, args: impl IntoIterator<Item = WasmValue> + Send ) -> WasmEdgeResult<Vec<WasmValue>>

Available on crate feature async and Linux only.

Runs this host function asynchronously and returns the result.

Arguments
  • async_state - Used to store asynchronous state at run time.

  • engine - The object implementing the Engine trait.

  • args - The arguments passed to the host function.

Error

If fail to run the host function, then an error is returned.

source

pub fn as_ref(&self) -> FuncRef

Returns a reference to this Function instance.

source

pub fn as_ptr(&self) -> *const WasmEdge_FunctionInstanceContext

Available on crate feature ffi only.

Provides a raw pointer to the inner function context.

Trait Implementations§

source§

impl Clone for Function

source§

fn clone(&self) -> Self

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 Drop for Function

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

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

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

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.

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<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V