14 releases

0.2.0 Mar 14, 2024
0.1.11 Sep 4, 2023
0.1.10 Apr 3, 2023
0.1.9 Sep 14, 2022
0.1.0 Aug 26, 2020

#175 in Rust patterns

Download history 2134/week @ 2024-01-28 1606/week @ 2024-02-04 2503/week @ 2024-02-11 3647/week @ 2024-02-18 2874/week @ 2024-02-25 2243/week @ 2024-03-03 2726/week @ 2024-03-10 2997/week @ 2024-03-17 2931/week @ 2024-03-24 2513/week @ 2024-03-31 2169/week @ 2024-04-07 2584/week @ 2024-04-14 2558/week @ 2024-04-21 2524/week @ 2024-04-28 2324/week @ 2024-05-05 1963/week @ 2024-05-12

9,627 downloads per month
Used in 43 crates (10 directly)

MIT/Apache

57KB
860 lines

vtable crate

Crates.io Docs.rs

A macro to create ffi-friendly virtual tables.

Check the crate documentation for more details.


lib.rs:

This crate allows you to create ffi-friendly virtual tables.

Features

  • A #[vtable] macro to annotate a VTable struct to generate the traits and structure to safely work with it.
  • VRef/VRefMut/VBox types. They are fat reference/box types which wrap a pointer to the vtable, and a pointer to the object.
  • [VRc]/VWeak types: equivalent to std::rc::{Rc, Weak} types but works with a vtable pointer.
  • Ability to store constants in a vtable.
  • These constants can even be a field offset.

Example of use:

use vtable::*;
// we are going to declare a VTable structure for an Animal trait
#[vtable]
#[repr(C)]
struct AnimalVTable {
/// pointer to a function that makes a noise.  The `VRef<AnimalVTable>` is the type of
/// the self object.
///
/// Note: the #[vtable] macro will automatically add `extern "C"` if that is missing.
make_noise: fn(VRef<AnimalVTable>, i32) -> i32,

/// if there is a 'drop' member, it is considered as the destructor.
drop: fn(VRefMut<AnimalVTable>),
}

struct Dog(i32);

// The #[vtable] macro created the Animal Trait
impl Animal for Dog {
fn make_noise(&self, intensity: i32) -> i32 {
println!("Wof!");
return self.0 * intensity;
}
}

// the vtable macro also exposed a macro to create a vtable
AnimalVTable_static!(static DOG_VT for Dog);

// with that, it is possible to instantiate a VBox
let animal_box = VBox::<AnimalVTable>::new(Dog(42));
assert_eq!(animal_box.make_noise(2), 42 * 2);

The #[vtable] macro created the "Animal" trait.

Note that the #[vtable] macro is applied to the VTable struct so that cbindgen can see the actual vtable.

Dependencies

~1.2–1.7MB
~35K SLoC