FFI-Safe Polymorphism: Thin Trait Objects
A while ago someone posted a question on the Rust User Forums asking how to achieve polymorphism in a C API and while lots of good suggestions were made, I’d like to explore my take on things.
As a recap, Rust provides two mechanisms for letting you write code which will work with multiple types. These are
Static Dispatch, where the compiler will generate multiple copies of the function, tailor-made for each type and resolved at compile time, and Dynamic Dispatch, where we use an extra level of indirection to only resolve the actual implementation at runtime While both mechanisms are extremely powerful and can cover almost all of your needs in normal Rust code, they both have one drawback… The actual mechanisms used are (deliberately) unspecified and not safe for FFI.
Michael-F-Bryan