Comment by haileys

Comment by haileys 8 days ago

4 replies

The way to do this in idiomatic Rust is to make a wrapper type that implements drop:

    struct MyForeignPtr(*mut c_void);

    impl Drop for MyForeignPtr {
        fn drop(&mut self) {
            unsafe { my_free_func(self.0); }
        }
    }
Then wrap the foreign pointer with MyForeignPtr as soon as it crosses the FFI boundary into your Rust code, and only ever access the raw pointer via this wrapper object. Don't pass the raw pointer around.
aapoalas 8 days ago

In this case they seem to have Rust on both sides of the FFI API and seemingly want to avoid heap allocating the Vec's static parts, which makes sense.

So, an extended version if your solution would be to initialize the static parts on the stack using `MaybeUninit`, and `assume_init` on that after the call to get an `OwningArrayC<T>` out, which then can have a Drop impl defined for it.

drdude 8 days ago

This is a great advice, thank you. I am learning Rust and this definitely gives me good pointers (no pun) how I should idiomatically handle them.

EDIT: can this be done/automated using macros?

  • skavi 8 days ago

    can’t really be handled nicely by macros outside of the case where the drop impl doesn’t need any data from the scope.