tov / libffi-rs

Rust bindings for libffi
Apache License 2.0
100 stars 35 forks source link

Made `high::Type::make` public so `CType` can be implemented #91

Open marcustut opened 3 months ago

marcustut commented 3 months ago

This is to provide a solution for https://github.com/tov/libffi-rs/issues/48

In projects that uses bindgen, it would generate structs such as

#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct trade_event {
    pub size: u64,
    pub price: u64,
    pub side: side,
}

and if one has a function pointer such as

#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct event_handler {
    pub handle_trade_event: ::std::option::Option<unsafe extern "C" fn(event: trade_event)>,
}

Then, at the moment it won't work because trade_event doesn't implement CType. Although CType is public but high::Type::make is not hence it is not possible to implement CType outside of the crate.

After this change, users are able to implement CType on their own. For example,

unsafe impl CType for trade_event {
    fn reify() -> libffi::high::Type<Self> {
        libffi::high::Type::make(libffi::middle::Type::structure([
            libffi::middle::Type::u64(),    // size
            libffi::middle::Type::u64(),    // price
            libffi::middle::Type::c_uint(), // side
        ]))
    }

    type RetType = trade_event;
}

Now that trade_event implements CType, it is possible to construct the function pointer as shown above for event_handler.