getditto / safer_ffi

Write safer FFI code in Rust without polluting it with unsafe code
http://getditto.github.io/safer_ffi
MIT License
925 stars 40 forks source link

Support unboxed opaque types that are `Copy` #103

Open TheButlah opened 2 years ago

TheButlah commented 2 years ago

It would be cool if there was support for safer_ffi opaque types that don't require boxing because they are Copy. Ostensibly, one could just look at the size and alignment of the type and create a C type with the same layout. This is what autocxx does and it seems to work well:

Generated rust code:

#[repr(C, align(4))]
pub struct HmdMatrix34_t {
    _pinned: core::marker::PhantomData<core::marker::PhantomPinned>,
    _non_send_sync: core::marker::PhantomData<[*const u8; 0]>,
    _data: [u8; 48],
}

Corresponding C/C++ POD type:

struct HmdMatrix34_t
{
    float m[3][4];
};

I'm assuming that this solution won't work for non-copy types (implying that they have a drop fn and cannot be memcopied), but in my API I have a bunch of opaque types that are Copy, and I'l really like to avoid boxing all of them, and having the caller have to allocate and drop them all the time