rust-diplomat / diplomat

Experimental Rust tool for generating FFI definitions allowing many other languages to call Rust code
https://rust-diplomat.github.io/book/
Other
527 stars 51 forks source link

Allow the caller to allocate memory for opaque data #25

Open Manishearth opened 3 years ago

Manishearth commented 3 years ago

Currently opaque structs need to be allocated with the system allocator. It would be nice if C++ (at least) callers could handle their own memory management, perhaps using bump allocators for short-lived objects.

There are two ways I can see us doing this, which I'll write out in comments

Manishearth commented 3 years ago

MaybeUninit

The first way is supporting &mut MaybeUninit<T> as parameters.

E.g.

#[diplomat::bridge]
mod ffi {
    impl FixedDecimal {
        fn new_in_place(&mut MaybeUninit<Self>) {..}
    }
}

For this code, the following stuff happens:

Manishearth commented 3 years ago

CustomAllocBox

#[diplomat::bridge] mod ffi {
impl PluralRules {
    fn new_alloc(Locale, alloc: CustomAllocFn) -> CustomAllocBox<PluralRules> {
       let pr = PluralRules::new(Locale);
       CustomAllocBox::new(pr, alloc);
    }
}
}

CustomAllocBox is a type with an aborting destructor, that is intended to be called with a new(alloc_fn) and paired with box.free(free_fn). This generates: