10 releases

0.1.9 Sep 14, 2022
0.1.8 Jul 5, 2022
0.1.7 May 4, 2022
0.1.6 Mar 9, 2022
0.1.0 Aug 26, 2020

#84 in GUI

Download history 324/week @ 2022-11-25 775/week @ 2022-12-02 503/week @ 2022-12-09 321/week @ 2022-12-16 367/week @ 2022-12-23 178/week @ 2022-12-30 229/week @ 2023-01-06 170/week @ 2023-01-13 329/week @ 2023-01-20 321/week @ 2023-01-27 420/week @ 2023-02-03 203/week @ 2023-02-10 491/week @ 2023-02-17 386/week @ 2023-02-24 326/week @ 2023-03-03 585/week @ 2023-03-10

1,801 downloads per month
Used in 20 crates (12 directly)

GPL-3.0-only…

46KB
688 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

~0.8–1.2MB
~28K SLoC