FAQ - Help and questions

Should I rewrite my C code in Rust or wrap it with FFI?

#porting#c-language#ffipublished 2 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail
Last post

Short answer

Wrap the C code when it is stable, tested and rarely changes; write new code in Rust around it. Rewrite the parts that parse untrusted input or keep causing memory bugs. Many projects do both: a Rust layer over the old library first, then one module at a time replaced in Rust.

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

The two options are not exclusive, and the right choice differs per module. The deciding questions are: how well tested is the C code, how often does it change, does it handle input from outside your program, and how large is it?

The answers below describe the two approaches as separate, complete options, with the trade-off of each.

Can Rust and C code live in one project?#

Yes. Cargo can compile C files with a build.rs script (the cc crate), and Rust code can export extern "C" functions that C calls. One executable can contain both.

How do I decide module by module?#

Start with the code that reads files, network data or user input, because memory errors there are security problems. Leave pure computation that is well tested for later.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    2 answers from the Ruststudio team: different approaches, each with its own trade-offs

    Sort: Oldest Newest
    #2

    Approach 1: wrap the C library and write new code in Rust#

    Keep the C code as it is, declare its functions in Rust, and put a small safe Rust wrapper around the unsafe calls. New features are written in Rust.

    src/lib.rsrust
    use std::ffi::{c_char, CStr};
    
    // The Rust side of an `extern "C"` function: C code keeps calling the same name and signature.
    /// # Safety
    /// `s` must be null or point to a NUL-terminated string that stays valid for the call.
    #[unsafe(no_mangle)]
    pub unsafe extern "C" fn word_count(s: *const c_char) -> i32 {
        if s.is_null() {
            return -1;
        }
        // SAFETY: the caller promises a valid NUL-terminated string (see the contract above).
        let text = unsafe { CStr::from_ptr(s) };
        match text.to_str() {
            Ok(t) => t.split_whitespace().count() as i32,
            Err(_) => -1,
        }
    }

    The sample above is the opposite direction (Rust code that C can call) and was compiled and run with a small main that printed 3 for the string "one two three" and -1 for a null pointer. For calling C from Rust, the thread on bindgen and the cc crate shows the setup.

    Best when: the C code is stable and well tested, it is large, or you cannot afford a rewrite now. Cost: you keep a C toolchain in the build, every call across the boundary is unsafe code that you must review, and memory bugs inside the C code stay possible.

      QuoteReply
      Share
      Hacker NewsRedditLinkedInE-mail
      #3

      Approach 2: rewrite one module at a time, behind the same interface#

      Pick one module, give the Rust version the same function names and signatures (extern "C", as in the example above), and switch the build to link the Rust version. Repeat until no C is left. Keep the C tests and run them against each Rust module.

      Best when: the module handles untrusted input (parsers, network protocols, file formats), has a history of memory bugs, or must be maintained for many years. Cost: real work, and a rewrite can introduce its own behaviour differences. Before deleting the C version, run both on the same inputs and compare the outputs (golden files or a differential test).

      A practical order is: tests first (they define the behaviour), then the module that parses outside data, then the rest by how often it changes.

        QuoteReply
        Share
        Hacker NewsRedditLinkedInE-mail