3 Introduction to C FFI and unsafe Rust
This chapter covers
- Understanding C Foreign Function Interface and its relation to unsafe Rust
- Performing normally forbidden operations with
unsafe
Rust - Refactoring a component of a C program into Rust
The last chapter provided a high-level overview of Rust code and discussed some elements of Rust that may be surprising or difficult to understand for new developers. Now that we’re able to write simple Rust programs, this chapter walks through an example of how to embed Rust code within an existing C program.
If we want to embed Rust code within an existing application, we need some very well-defined semantics for how the two languages communicate, how values are passed back and forth between them, and how memory may or may not be shared between them. Ideally, this interface between the two languages will be well supported across a number of different languages and platforms so we can avoid rewriting code to perform a specific integration.