Michael-F-Bryan / rust-ffi-guide

A guide for doing FFI using Rust
https://michael-f-bryan.github.io/rust-ffi-guide/
Creative Commons Zero v1.0 Universal
284 stars 18 forks source link

Beware of allocators mismatch #53

Open fabricedesre opened 7 years ago

fabricedesre commented 7 years ago

When eg. you get a buffer allocated from the C side of the FFI and are expected to manage its lifetime in Rust, extra care needs to happen in the Rust code to deallocate with the C malloc/free and not just drop it since Rust is using jemalloc.

The same precautions need to be taken when handing buffers to the C side.

I've found it needed to write small custom functions to expose deallocation or allocation missing on the C side to make that clear and correct.

Michael-F-Bryan commented 7 years ago

This sounds like a nice way to shoot yourself in the foot by messing up the allocator's internal bookkeeping. I imagine the solution for this problem would mention that a good rule of thumb is to always deallocate something from the language that allocated it. That's what I've done in all the FFI bindings I've done at work.

I think another best practice is to avoid passing ownership between languages if possible. So for example, say you are wanting to pass the contents of a std::vector from C++ to Rust, you'd instead pass a pointer to the first element and the number of elements. Effectively only passing borrowed slices between languages.

Something else to note is that Rust will use the system allocator if it is compiled as a cdylib. So technically you could probably get away with using drop(), but I wouldn't recommend it.

Michael-F-Bryan commented 7 years ago

I've posted this issue on the [TWIR] Call for Participation thread on the user forums.