uniffi-rs
uniffi-rs copied to clipboard
Better system for handles
There are many situations where we manage opaque FFI handles: callback interfaces, futures, callback data, etc. The basic requirement is to create a handle for an object, pass it across the FFI, use the handle for FFI calls, then finally pass the handle to some function to free the object.
We generally use pointer/usize handles for this and have several ad-hoc systems to handle it. There are several issues with these systems:
- Pointers vary in size between platforms
- Pointers require extra level of boxing when used with
Arc<dyn Trait>(and currently oneshot::Sender) - Not all foreign languages support pointers directly (JS even has issues with 64-bit integers)
- Managing the reference count in the foreign language is hard
I think we can come up with a general system for handles that avoids these issues. The starting point can be the slab crate, which is pretty simple and essentially creates usize handles to manage object allocations. I think we can update it to use u32 handles and catch use-after-free errors in some case (maybe most).