I am building safe bindings for a C library in Rust and I started facing a weird issue.
I created a struct to own the unsafe pointer to the objects returned by the library and free them safely.
This is what I have:
pub struct VipsImage {
pub(crate) ctx: *mut bindings::VipsImage,
}
impl Drop for VipsImage {
fn drop(&mut self) {
unsafe {
if !self.ctx.is_null() {
bindings::g_object_unref(self.ctx as *mut c_void);
}
}
}
}
This works fine as long as I don't share this between async
calls. If I return one of this objects in an async
function and use it afterwards it will be corrupted. If I used and free them in a single operation, they work as expected.
How would I implement Send
and Sync
for a struct like that so I can safely share it between threads?
If someone wants to check the full library code, here's the link