← 返回日报
精读 预计 3 分钟

The C to Rust migration book

摘要

本书由 Mainmatter 发布,内容围绕 C 到 Rust 迁移哲学:将从头重写自包含库转为对大型复杂代码库的渐进迁移。章节包括:1. Foreign Function Interfaces(FFI 基础:C ABI、符号表、linker,extern "C" 绑定、签名匹配);2. Types and Data Across the Boundary(原始值、字符串、struct、集合跨边界移动,用 bindgen 从 C 头生成 Rust 绑定,用 cheadergen 从 Rust 生成 C 头,配置非平凡类型);3. FFI-Safe Types(Raw 指针和未命名原始类型是 FFI 边界大源头,用 NonNull、Option、newtype 包装器、enum discriminants 替代,设计类型使 C 代码无类型安全时的无效状态不可表示);4. FFI validation(每个 FFI 函数为信任边界,C 调用者可传 null 指针、越界值或无效 UTF-8,构建验证和缩小输入的纪律,使无效数据不进入安全 Rust 或业务逻辑);5. Error Handling and API Design(Rust Result 和? 在 extern "C" 处中断,用 error-code enums 和 out-parameters 转换 Rust 错误类型为 C 兼容结果,不泄漏 Rust 内部,暴露粗粒度操作而非逐字段 setter,保持 API 表面小);6. Production-Quality FFI(用 Rust 的/// # Safety convention 和 numbered invariants 记录 FFI 函数,所有不安全合约明确化,通过 cheadergen 在生成头中作为 C doc comments 出现,覆盖构建集成、自动化检查,将 FFI 表面当作永久维护的 API)。假设读者已有 Rust 基础和 C 知识,无需先有 FFI 经验。作者 Jonas Kruckenberg 为 Mainmatter 资深咨询师,Mainmatter 专注 Rust 工程服务、培训和对 C 到 Rust 迁移的支持。

荐读理由

Mainmatter的哲学是self-paced练习:每章节配一个实际Rust包练习题,覆盖FFI外函数接口、跨边界类型搬运(bindgen生成C头,cheadergen反向生成C头)、FFI-safe类型(NonNull、Option、newtype),以及生产级验证和Safety文档。主体据此在AI工程项目里能直接落地把现有C依赖安全引入Rust,无需全重写。

原文

Mainmatter

A close up view of a machine with gears

The C to Rust Migration Book

By Mainmatter

Overview

The course

Table of contents

About the author

About Mainmatter

Migrate from C to Rust without breaking the world

Securing and modernizing software is a top priority today. Tech debt and memory-safety bugs remain the largest sources of vulnerabilities, which is why teams increasingly turn to Rust for its reliability and memory safety. But rewrites are hard, scary, and carry a lot of risk. Mainmatter assembled our experience from helping clients successfully modernize some of the worlds most important software into this book.

Whether you rewrite a self-contained library from scratch or incrementally migrate a large, complex codebase that keeps changing, this book teaches you the techniques to succeed. You will learn how to maintain a safe mixed C-Rust codebase, design and structure clean APIs, and translate common C idioms into idiomatic Rust.

The C to Rust Migration Book

Start learning

C to Rust migration books

This course is built around our philosophy of self-paced exercises. Each concept is paired with an exercise you solve in a real Rust package, with a test suite that checks your solution.

It assumes prior knowledge of Rust and some C. No prior FFI experience required. That's what the course teaches.

By the end you'll be ready to introduce Rust into a C codebase in a productive way.

Table of contents

Foreign Function Interfaces

The fundamentals of FFI: how C and Rust communicate at the binary level through the C ABI, symbol tables, and the linker. You'll write your first extern "C" blocks by hand and see what you're promising the compiler when you declare a binding, and what goes wrong when the signature doesn't match.

Types and Data Across the Boundary

How to move primitive values, strings, structs, and collections across the language boundary while keeping ownership clear. You'll use bindgen to generate Rust bindings from C headers, and cheadergen, Mainmatter's tool for the reverse direction, to generate C headers from your Rust code, and configure both for non-trivial types.

FFI-Safe Types

Raw pointers and untyped primitives are a major source of bugs at the FFI boundary. You'll learn safer alternatives: NonNull, Option, newtype wrappers, and enum discriminants that carry meaning instead of bare values, and how to design types that make invalid states unrepresentable even when talking to C code that has no type safety of its own.

FFI validation

Every FFI function is a trust boundary. C callers can pass null pointers, out-of-range values, or invalid UTF-8, and Rust can't catch that at compile time. You'll build the discipline of validating and narrowing inputs at the boundary, so invalid data from C never reaches safe Rust or your business logic.

Error Handling and API Design

Rust's Result and ? stop at extern "C". You'll convert Rust error types into C-compatible results with error-code enums and out-parameters, and surface failure information without leaking Rust internals. You'll also learn to expose coarse operations rather than per-field setters and keep your API surface small.

Production-Quality FFI

You'll document FFI functions with Rust's /// # Safety convention and numbered invariants, so every unsafe contract is explicit and surfaces as C doc comments in the generated headers via cheadergen. We cover build integration, automated checks, and treating your FFI surface as an API you'll maintain forever.

About the author

Jonas Kruckenberg

Jonas Kruckenberg

Senior Engineering Consultant @Mainmatter

Jonas Kruckenberg is a systems engineer and technologist focused on next-generation computing infrastructure. He is the lead author of k23, an experimental high-reliability operating system. As a TC39 Invited Expert, he helps shape the future of web by bringing non-browser perspectives to JavaScript language standardization.

Mainmatter is an engineering consultancy specializing in Rust. We offer engineering services, training, and mentorship to companies that aim to migrate from C to Rust or introduce Rust into an existing codebase.

Facing Rust challenges and need a helping hand?

We can help with complex C-to-Rust migrations, reliability issues, training, and skill gaps.

Contact us

EuroRust 2026 logo

Community

EuroRust 2026

EuroRust is a two-day conference for all things Rust, plus two more days of side activities, workshops, and hackathons. Join us in October in Barcelona.

Get your ticket

Hacker News · 15 赞 · 4 评 讨论 → 阅读原文 →

这条对你有帮助吗?