pub struct Function { /* private fields */ }Expand description
A type-erased callable that works across languages.
A Function takes AnyView arguments and returns an Any. Make one
from a Rust closure with from_typed, look one up by
name with get_global, and call it with
call_tuple or call_packed.
into_typed_fn! turns it back into a typed closure.
§Examples
use tvm_ffi::{Function, Result};
let add = Function::from_typed(|x: i64, y: i64| -> Result<i64> { Ok(x + y) });
let sum = i64::try_from(add.call_tuple((1_i64, 2_i64))?)?;
assert_eq!(sum, 3);A Function may be called from any thread, so a Rust callback must be
Send + Sync; a callback holding an Rc is rejected. A function written
in another language is as thread-safe as its implementation.
use std::rc::Rc;
let count = Rc::new(0_i64);
tvm_ffi::Function::from_typed(move || -> tvm_ffi::Result<i64> { Ok(*count) });Implementations§
Source§impl Function
impl Function
Sourcepub fn call_packed(&self, packed_args: &[AnyView<'_>]) -> Result<Any>
pub fn call_packed(&self, packed_args: &[AnyView<'_>]) -> Result<Any>
Call the function with the arguments packed_args.
§Arguments
packed_args- The arguments, oneAnyVieweach.
§Returns
The function’s result.
§Errors
Returns the error that the function raises.
use tvm_ffi::{AnyView, Function, Result};
let add = Function::from_typed(|x: i64, y: i64| -> Result<i64> { Ok(x + y) });
let result = add.call_packed(&[AnyView::from(&1_i64), AnyView::from(&2_i64)])?;
assert_eq!(i64::try_from(result)?, 3);See also Function.
Sourcepub fn call_tuple(&self, tuple_args: impl PackedCallArgs) -> Result<Any>
pub fn call_tuple(&self, tuple_args: impl PackedCallArgs) -> Result<Any>
Call the function with the arguments in the tuple tuple_args.
An element may be a value or a reference to one; a reference passes an
object without retaining it, and a &str or &[u8] passes as a
String or Bytes.
§Arguments
tuple_args- The arguments, as a tuple such as(1_i64, &array).
§Returns
The function’s result.
§Errors
Returns the error that the function raises.
See also Function.
Sourcepub fn get_global(name: &str) -> Result<Function>
pub fn get_global(name: &str) -> Result<Function>
Look up the global function registered as name.
§Arguments
name- The name of the function, such as"my_ext.double".
§Returns
The global function.
§Errors
Returns a ValueError if no function is registered as name, as C++
Function::GetGlobalRequired. Probe with .ok() where a missing
function is expected.
use tvm_ffi::Function;
let double = Function::from_typed(|x: i64| -> tvm_ffi::Result<i64> { Ok(x * 2) });
Function::register_global("my_ext.double", double)?;
let double = Function::get_global("my_ext.double")?;
assert_eq!(i64::try_from(double.call_tuple((21_i64,))?)?, 42);See also register_global_typed.
Sourcepub fn register_global(name: &str, func: Function) -> Result<()>
pub fn register_global(name: &str, func: Function) -> Result<()>
Register a function as a global function, which every language can then look up by name.
The function’s metadata records only that it is a function, with no
parameter types. Use Function::register_global_typed to record the
parameter and return types of a typed function, and a doc string.
§Arguments
name- The name of the function.func- The function to register.
§Returns
Ok(()) once the function is registered.
§Errors
Returns an error if the registration fails.
See also get_global.
Sourcepub fn register_global_typed<F, I, O>(
name: &str,
func: F,
doc: &str,
) -> Result<()>
pub fn register_global_typed<F, I, O>( name: &str, func: F, doc: &str, ) -> Result<()>
Register a typed function as a global function, with a doc string.
The function’s metadata records its type schema, the parameter and
return types, which tvm_ffi.get_global_func_metadata and the stub
generator read. An empty doc records no doc string.
§Arguments
name- The name of the function.func- The typed function to register, as forFunction::from_typed.doc- The doc string of the function.
§Returns
Ok(()) once the function is registered.
§Errors
Returns an error if the registration fails.
use tvm_ffi::{Function, Result};
let add = |x: i64, y: i64| -> Result<i64> { Ok(x + y) };
Function::register_global_typed("my_ext.add", add, "Add two integers.")?;See also get_global.
Sourcepub fn from_packed<F>(func: F) -> Self
pub fn from_packed<F>(func: F) -> Self
Construct a function from a packed function, which takes its arguments as a slice.
Use it for a variable number of arguments; otherwise
from_typed converts the arguments for you. Report
errors by returning them. A panic in func is caught and raised to the
caller as an InternalError, but panicking is discouraged.
§Arguments
func- The packed function, of signatureFn(&[AnyView]) -> Result<Any>.
§Returns
The function.
use tvm_ffi::{Any, AnyView, Function, Result};
let count = Function::from_packed(|args: &[AnyView]| -> Result<Any> {
Ok(Any::from(args.len() as i64))
});
assert_eq!(i64::try_from(count.call_tuple((1_i64, true))?)?, 2);See also Function.
Sourcepub fn from_typed<F, I, O>(func: F) -> Self
pub fn from_typed<F, I, O>(func: F) -> Self
Construct a function from a typed function.
Each argument is converted to its parameter type, and a mismatch raises a
TypeError to the caller. Report errors by returning them. A panic in
func is caught and raised to the caller as an InternalError, but
panicking is discouraged.
§Arguments
func- The typed function, anAsPackedCallablesuch asFn(T0, T1, ...) -> Result<O>; each parameter is anAnyCompatibletype, aTensorViewor anRValueRef<T>.
§Returns
The function.
use tvm_ffi::{Function, Result};
let scale = Function::from_typed(|x: f64, factor: f64| -> Result<f64> { Ok(x * factor) });
assert_eq!(f64::try_from(scale.call_tuple((2.0_f64, 1.5_f64))?)?, 3.0);See also Function.
Sourcepub unsafe fn from_extern_c(
handle: *mut c_void,
safe_call: TVMFFISafeCallType,
deleter: Option<unsafe extern "C" fn(*mut c_void)>,
) -> Result<Self>
pub unsafe fn from_extern_c( handle: *mut c_void, safe_call: TVMFFISafeCallType, deleter: Option<unsafe extern "C" fn(*mut c_void)>, ) -> Result<Self>
Wrap a C callback as a Function.
§Safety
handle (may be null) is the state safe_call receives; deleter frees it
when the Function drops. All three must be safe to use from any thread.
§Errors
Returns an error if the runtime cannot allocate the function. The
function then does not take handle: deleter is not called, and the
caller still owns handle.
Trait Implementations§
Source§impl DowncastRefFromAny for Function
impl DowncastRefFromAny for Function
Source§impl ObjectRefAnyCompatible for Function
impl ObjectRefAnyCompatible for Function
Source§fn extra_check(obj: &Self::ContainerType) -> bool
fn extra_check(obj: &Self::ContainerType) -> bool
obj, an instance of ContainerType, is a value of Self.
Every strict and converting cast checks it, after the object type.Source§fn convert_fallback(value: AnyView<'_>) -> Option<Self>
fn convert_fallback(value: AnyView<'_>) -> Option<Self>
Self object, such as an integer that
stands for a constant; None rejects it. Only converting casts (TryFrom<Any>,
typed function arguments) call it; downcast_ref, downcast and
match_any! never do.Source§fn custom_type_str() -> String
fn custom_type_str() -> String
AnyCompatible::type_str.Source§fn custom_mismatch_type_info(value: AnyView<'_>) -> String
fn custom_mismatch_type_info(value: AnyView<'_>) -> String
value in conversion errors; by default its
runtime type key. See AnyCompatible::get_mismatch_type_info.Source§impl ObjectRefCore for Function
impl ObjectRefCore for Function
Source§type ContainerType = FunctionObj
type ContainerType = FunctionObj
Source§fn data(this: &Self) -> &ObjectArc<Self::ContainerType>
fn data(this: &Self) -> &ObjectArc<Self::ContainerType>
Source§fn into_data(this: Self) -> ObjectArc<Self::ContainerType>
fn into_data(this: Self) -> ObjectArc<Self::ContainerType>
Source§unsafe fn from_data(data: ObjectArc<Self::ContainerType>) -> Self
unsafe fn from_data(data: ObjectArc<Self::ContainerType>) -> Self
Source§fn same_as<Other: ObjectRefCore>(&self, other: &Other) -> bool
fn same_as<Other: ObjectRefCore>(&self, other: &Other) -> bool
Source§fn type_key(&self) -> &'static str
fn type_key(&self) -> &'static str
"ffi.Array", as C++ ObjectRef::GetTypeKey.Source§fn is<T: AnyCompatible>(&self) -> bool
fn is<T: AnyCompatible>(&self) -> bool
T as is, such as a subtype or a container
whose elements are checked too, by the strict check of
downcast, without a reference count change.
See also crate::Any::is.Source§impl PackedCallArg for Function
impl PackedCallArg for Function
Source§impl<'a> PackedCallArg for &'a Function
impl<'a> PackedCallArg for &'a Function
impl Send for Function
impl Sync for Function
impl TypeSubsumes<Function> for ObjectRef
Auto Trait Implementations§
impl Forget for Function
impl Freeze for Function
impl Move for Function
impl RefUnwindSafe for Function
impl Unpin for Function
impl UnsafeUnpin for Function
impl UnwindSafe for Function
Blanket Implementations§
Source§impl<T> AnyCompatible for Twhere
T: ObjectRefAnyCompatible,
impl<T> AnyCompatible for Twhere
T: ObjectRefAnyCompatible,
const MATCH_ANY_EXACT: bool = const MATCH_ANY_EXACT: bool = <T as ObjectRefAnyCompatible>::MATCH_ANY_EXACT && <T::ContainerType as ObjectCore>::TYPE_FINAL;
fn match_any_exact_type_index() -> i32
Source§unsafe fn is_undefined(field: *const T) -> bool
unsafe fn is_undefined(field: *const T) -> bool
field, which holds a value of this type or all-zero bytes,
holds all-zero bytes that are no value of this type, as a null object
reference, a string of type index None or a zero device type: a field
that a creator left undefined for reflection to set. An undefined field
is no value; a nullable reference is Option<T>, whose None is a
defined value. Read moreSource§unsafe fn copy_to_any_view(src: &T, data: &mut TVMFFIAny)
unsafe fn copy_to_any_view(src: &T, data: &mut TVMFFIAny)
Source§unsafe fn move_to_any(src: T, data: &mut TVMFFIAny)
unsafe fn move_to_any(src: T, data: &mut TVMFFIAny)
Source§unsafe fn check_any_strict(data: &TVMFFIAny) -> bool
unsafe fn check_any_strict(data: &TVMFFIAny) -> bool
Source§unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> T
unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> T
Self out of a cell that holds one, retaining any object. Read moreSource§unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> T
unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> T
Self out of an owning cell that holds one. Read moreSource§unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<T, ()>
unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<T, ()>
data into a Self by the FFI rules, such as an integer into a
float; Err if it does not convert. Read moreSource§fn get_mismatch_type_info(data: &TVMFFIAny) -> String
fn get_mismatch_type_info(data: &TVMFFIAny) -> String
data in conversion errors; by
default its runtime type key.Source§fn type_str() -> String
fn type_str() -> String
int,
ffi.String or Array<int>.