Crate ffi_trait

Source
Expand description

ffi_trait

This crate has an vtable_for_trait! macro that will generate an FFI-safe vtable for the trait that you declare inside it

§Usage

vtable_for_trait! {
    pub trait Foo {
        fn foo(&self, x: i32) -> f32;
        fn bar(&mut self);
    }

    pub vtable FooVtable;
}

will turn into something like

pub trait Foo {
    fn foo(&self, x: i32) -> f32;
    fn bar(&mut self);
}

#[derive(Clone, Copy)]
#[repr(C)]
pub struct FooVtable {
    pub drop_vtable: DropVtable,
    pub foo: unsafe extern "C" fn(NonNull<()>, i32) -> f32,
    pub bar: unsafe extern "C" fn(NonNull<()>),
}

unsafe impl<T: Foo> VtableFor<T> for FooVtable {
    const VTABLE: &'static Self = {
        // extern "C" compatible thunks

        &Self {
            drop_vtable: *<DropVtable as VtableFor<T>>::VTABLE,
            // methods
        }
    };
}

impl<'a> Foo for RefDyn<'a, FooVtable> {
    // methods
}

impl<'a> Foo for OwnDyn<'a, FooVtable> {
    // methods
}

Macros§

vtable_for_trait

Structs§

DropVtable
OwnDyn
RefDyn

Traits§

VtableFor
Safety