Project 4: Cross-Language FFI Showdown

A simple C shared library (.so or .dll) that exports a few functions, including one that passes a struct. You will then write small programs in Python, Rust, and Go that load this library and call those functions.

Quick Reference

Attribute Value
Primary Language C
Alternative Languages Python, Rust, Go
Difficulty Level 3: Advanced
Time Estimate 1-2 weeks
Knowledge Area FFI / Interoperability
Tooling ctypes (Python), cgo (Go), Rust FFI
Prerequisites Basics of Python, Rust, or Go. Project 3 is helpful.

What You Will Build

A simple C shared library (.so or .dll) that exports a few functions, including one that passes a struct. You will then write small programs in Python, Rust, and Go that load this library and call those functions.

Why It Matters

This project builds core skills that appear repeatedly in real-world systems and tooling.

Core Challenges

  • Matching C types to foreign types → maps to ctypes.c_int in Python, i32 in Rust
  • Replicating C struct layout → maps to creating a ctypes.Structure or a #[repr(C)] struct in Rust
  • Handling pointers and memory → maps to understanding who allocates and who frees memory across the FFI boundary
  • Configuring build systems for FFI → maps to linking the C library correctly in Go or Rust

Key Concepts

  • Foreign Function Interface (FFI): A mechanism by which a program written in one language can call routines from a library written in another.
  • #[repr(C)]: Rust attribute to force a struct to have C-compatible memory layout.
  • Python ctypes: Python’s standard library for calling C functions.

Real-World Outcome

struct Point { int x; int y; };
int get_x(struct Point p) { return p.x; }

Implementation Guide

  1. Reproduce the simplest happy-path scenario.
  2. Build the smallest working version of the core feature.
  3. Add input validation and error handling.
  4. Add instrumentation/logging to confirm behavior.
  5. Refactor into clean modules with tests.

Milestones

  • Milestone 1: Minimal working program that runs end-to-end.
  • Milestone 2: Correct outputs for typical inputs.
  • Milestone 3: Robust handling of edge cases.
  • Milestone 4: Clean structure and documented usage.

Validation Checklist

  • Output matches the real-world outcome example
  • Handles invalid inputs safely
  • Provides clear errors and exit codes
  • Repeatable results across runs

References

  • Main guide: LEARN_C_ABI_DEEP_DIVE.md
  • “The Rust Programming Language” (for its excellent FFI chapter)