Skip to content

naranyala/ffi-starter-rust-lib

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ffi-starter-rust-lib

A professional-grade starter template for creating Rust libraries that expose a C-compatible Foreign Function Interface (FFI).

🎯 Purpose

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.

📂 Project Structure

  • src/lib.rs: The core Rust implementation.
  • c_api/: The "Source of Truth". Contains .h headers 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.

🚀 Quick Start

Prerequisites

  • Rust toolchain (cargo)
  • C compiler (gcc or clang)
  • make

Build and Run Example

Build the Rust cdylib and execute the C client:

cargo build
make -C examples/c_client run

🧪 Testing

The project employs a dual-layer testing strategy:

  1. Rust Unit Tests: Verifies internal logic and safety guards.
    cargo test
  2. C Integration Tests: Verifies that the compiled binary actually works as expected when called from C.
    cargo build
    make -C tests/c_tests run

🛠 Development Guidelines

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)] and extern "C".
  • Mandatory std::panic::catch_unwind wrappers for public APIs.
  • Symmetrical memory allocation and deallocation.

📄 License

MIT

About

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.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors