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§

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.

  • 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};

#[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(&func_ty, Box::new(real_add), 0).expect("fail to create a Function instance");

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 pointer to the data.

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

Error

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.

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

Error
Example

The example defines an async host function real_add.

use wasmedge_sys::{FuncType, Function, WasmValue, CallingFrame};
use wasmedge_types::{error::HostFuncError, ValType, WasmEdgeResult};
use std::future::Future;
use std::os::raw::c_void;

fn real_add(
    _frame: CallingFrame,
    input: Vec<WasmValue>,
) -> Box<(dyn Future<Output = Result<Vec<WasmValue>, HostFuncError>> + Send + 'static)> {
    Box::new(async move {
        if input.len() != 3 {
            return Err(HostFuncError::User(1));
        }

        let a = if input[1].ty() == ValType::I32 {
            input[1].to_i32()
        } else {
            1
        };

        let b = if input[2].ty() == ValType::I32 {
            input[2].to_i32()
        } else {
            2
        };
        tokio::time::sleep(std::time::Duration::from_secs(4)).await;

        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_async(&func_ty, Box::new(real_add), 0).expect("fail to create a Function instance");

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

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

Error

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

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

  • real_fn - The pointer to the target function.

  • data - The pointer to the data.

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

Error

Returns the underlying wasm type of this Function.

Errors

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

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.

Example
use wasmedge_sys::{FuncType, Function, WasmValue, Executor, CallingFrame};
use wasmedge_types::{error::HostFuncError, ValType};

fn real_add(_: CallingFrame, input: Vec<WasmValue>) -> Result<Vec<WasmValue>, HostFuncError> {
    println!("Rust: Entering Rust function real_add");

    if input.len() != 2 {
        return Err(HostFuncError::User(1));
    }

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

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

    let c = a + b;
    println!("Rust: calcuating in real_add c: {:?}", c);

    println!("Rust: Leaving Rust function real_add");
    Ok(vec![WasmValue::from_i32(c)])
}

// create a FuncType
let result = FuncType::create(vec![ValType::I32; 2], vec![ValType::I32]);
assert!(result.is_ok());
let func_ty = result.unwrap();
// create a host function
let result = Function::create(&func_ty, Box::new(real_add), 0);
assert!(result.is_ok());
let host_func = result.unwrap();

// create an Executor instance
let result = Executor::create(None, None);
assert!(result.is_ok());
let mut executor = result.unwrap();

// run this function
let result = host_func.call(
    &mut executor,
    vec![WasmValue::from_i32(1), WasmValue::from_i32(2)],
);
assert!(result.is_ok());
let returns = result.unwrap();
assert_eq!(returns[0].to_i32(), 3);

Runs this host function asynchronously 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.

Returns a reference to this Function instance.

Provides a raw pointer to the inner function context.

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.