Reviewing guidelines for safe FFIs
In this section, we'll look at a few guidelines to keep in mind while interfacing with other languages using FFI in Rust:
- The extern keyword: Any foreign function defined with an
extern
keyword in Rust is inherently unsafe, and such calls must be done from anunsafe
block. - Data layout: Rust does not provide guarantees on how data is laid out in memory, because it takes charge of allocations, reallocations, and deallocations. But when working with other (foreign) languages, explicit use of a C-compatible layout (using the
#repr(C)
annotation) is important to maintain memory safety. We've seen an example earlier of how to use this. Another thing to note is that only C-compatible types should be used as parameters or return values for external functions. Examples of C-compatible types in Rust include integers, floats,repr(C)
-annotated structs, and pointers. Examples of Rust types incompatible with C include trait objects, dynamically...