A professional-grade starter template for creating Rust libraries that expose a C-compatible Foreign Function Interface (FFI).
This project serves as a blueprint for software engineers who need to integrate Rust's memory safety and performance into existing C/C++ codebases or provide a library that can be consumed by any language supporting the C ABI.
It demonstrates the "Correct Way" to handle FFI, focusing on:
- Stability: Preventing Rust panics from leaking into the C host.
- Maintainability: Synchronizing headers and implementations.
- Safety: Strict memory ownership and pointer validation.
- Interoperability: Using fixed-width types for cross-platform consistency.
src/lib.rs: The core Rust implementation.c_api/: The "Source of Truth". Contains.hheaders used by the C consumer.examples/c_client/: A complete C application demonstrating how to link and call the library.tests/c_tests/: Integration tests written in C to verify the ABI boundary.RULES.md: Strict development guidelines for maintaining the FFI contract.
- Rust toolchain (
cargo) - C compiler (
gccorclang) make
Build the Rust cdylib and execute the C client:
cargo build
make -C examples/c_client runThe project employs a dual-layer testing strategy:
- Rust Unit Tests: Verifies internal logic and safety guards.
cargo test - C Integration Tests: Verifies that the compiled binary actually works as expected when called from C.
cargo build make -C tests/c_tests run
To maintain the integrity of the FFI boundary, all contributors MUST follow the rules defined in RULES.md.
Key requirements include:
- Every Rust export must have a corresponding C header declaration.
- Use of
#[unsafe(no_mangle)]andextern "C". - Mandatory
std::panic::catch_unwindwrappers for public APIs. - Symmetrical memory allocation and deallocation.
MIT