Module libffi::high

source ·
Expand description

High layer providing automatic marshalling of Rust closures as C function pointers.

The main facility here is given by the structs ClosureN, ClosureMutN, and ClosureOnceN, for natural numbers N from 0 to 12 (as of now). These represent C closures of N arguments, which can be used to turn Rust lambdas (or in generally, anything that implements Fn or FnMut) into ordinary C function pointers. For example, a Rust value of type Fn(u32, u32) -> u64 can be turned into a closure of type Closure2<u32, u32, u64> using Closure2::new. Then a C function pointer of type extern "C" fn(u32, u32) -> u64 can be borrowed from the closure and passed to C.

The above usage case eliminates much of the boilerplate involved in creating a closure as compared to the middle and low layers, but at the price of flexibility. Some flexibility can be recovered by manually constructing and configuring a CIF (e.g., a Cif2) and then creating the closure with Closure2::new_with_cif.

See the call submodule for a simple interface to dynamic calls to C functions.

Examples

Here we use ClosureMut1, which is the type for creating mutable closures of one argument. We use it to turn a Rust lambda into a C function pointer.

use libffi::high::ClosureMut1;

let mut x = 0u64;
let mut f = |y: u32| { x += y as u64; x };

let closure = ClosureMut1::new(&mut f);
let counter = closure.code_ptr();

assert_eq!(5, counter.call(5));
assert_eq!(6, counter.call(1));
assert_eq!(8, counter.call(2));

Note that in the above example, counter is an ordinary C function pointer of type extern "C" fn(u64) -> u64.

Here’s an example using ClosureOnce3 to create a closure that owns a vector:

use libffi::high::ClosureOnce3;

let v = vec![1, 2, 3, 4, 5];
let mut f = move |x: usize, y: usize, z: usize| {
    v[x] + v[y] + v[z]
};

let closure = ClosureOnce3::new(f);
let call = closure.code_ptr();

assert_eq!(12, call.call(2, 3, 4));

Invoking the closure a second time will panic.

Re-exports

Modules

  • CIF and closure types organized by function arity.
  • CIF and closure types organized by function arity.
  • CIF and closure types organized by function arity.
  • CIF and closure types organized by function arity.
  • CIF and closure types organized by function arity.
  • CIF and closure types organized by function arity.
  • CIF and closure types organized by function arity.
  • CIF and closure types organized by function arity.
  • CIF and closure types organized by function arity.
  • CIF and closure types organized by function arity.
  • CIF and closure types organized by function arity.
  • CIF and closure types organized by function arity.
  • CIF and closure types organized by function arity.
  • Simple dynamic calls.
  • Representations of C types for the high layer.

Constants

Type Definitions