Rust structures for FFI

Hi,

I'm developing a library that will have an FFI. What is the recommended method for structures? Should the structures be kept as Rust structures then converted by the FFI functions or should they be made as C type structs at the start?

Thanks!

Try taking a look at Overview - The (unofficial) Rust FFI Guide.

1 Like

I've used this recipe for several projects and it works pretty well:

  • write all your business logic in a pure Rust crate that knows nothing about FFI
  • create a separate crate who's only responsibility is to wrap the Rust crate in a C API
  • keep your API as high level and simple as possible - this lets you reduce the amount of unsafe code you need to write, as well as allowing your users to be less coupled so your Rust is still able to evolve without breaking backwards compatibility
  • There doesn't necessarily need to be a 1:1 correspondence between Rust types/functions and C.
  • each extern "C" function you write should be dumb. Translate arguments, call a safe Rust function, then translate results back to a form more compatible with C
  • avoid the temptation to do loads of refactoring or introduce "clever" tricks so you can avoid some copy/paste. When you eventually find out your C API has soundness holes or ownership issues, you don't want to be jumping through layers of abstraction/indirection
  • Write a test suite that exercises your C API
2 Likes