I want to learn FFI, from zero start. have any resoures to share to me?

i read rust the book before, and can write some things whit rust.
I want to learn FFI, from zero start. have any resoures to share to me ?

I got to where I needed using: FFI - The Rustonomicon

The nomicon may be on the more difficult end of the scale with regards to difficulty levels, so there are probably better resources, but it worked for me.

A couple years back I wrote an article stepping through writing bindings to a native library called chmlib. It goes into quite a lot of detail with plenty of hints and tricks along the way.

I've also got a much more specialised article on passing Rust closures across the FFI boundary.

I also ran into a situation where I wanted to pass some sort of Box<dyn Foo> across the FFI boundary, but trait objects aren't FFI-safe so I ended up writing my own trait objects. Working with "vtables" is also a pretty useful tool to have in your toolbelt.

The function_wrapper body in your first post seems to be susceptible to the panic-on-drop panic payload footgun: when result is discarded as Err(_), its Box<dyn Any + ...> payload is dropped, and that drop can cause an unwinding panic into C code. Luckily, in the real chmlib crate, your strategy of propagating the payload through the state avoids this footgun. (Incidentally, using state as a result enum is quite clever; I might use that for my own code sometime.)

Ehh... Reading through that issue, it feels more like an academic exercise than a practical problem people will run into or should be concerned about. In 6 years of using Rust, there are about 3 times I've seen a custom panic payload[1] being used instead of the normal &'static str or String you'll get from the panic!() macro.

If you are deliberately using drop bombs as the panic payload then I'm okay with you segfaulting :man_shrugging:

  1. Note that this is different from just panicking in a Drop implementation. The only way to have a panic payload with the panic-on-drop bug is by explicitly calling std::panic::panic_any() with a drop bomb (or something that contains one).
    Dropping a panic-on-drop object while unwinding can't cause this bug because you aren't using the drop bomb as your panic payload. ↩︎