Skip to content

Docs/Language/FFI & C Interop

FFI & C Interop

Call C libraries directly: extern "C" blocks, link directives, generated bindings, and C-compatible layouts.

~2 min read

On this page

Fid calls C functions directly, so you can port a system one module at a time.

Declaring C functions

An extern "C" block names a header, optionally a library to link, and the functions you use. as gives each a Fid name, so C names do not collide with yours. Calls into C must be inside unsafe code: an @unsafe function or an unsafe { } block.

extern "C" include "<math.h>" link "m" {
    fn sqrt as c_sqrt(x: f64) -> f64;
    fn pow as c_pow(base: f64, exp: f64) -> f64;
}

@unsafe
fn main() -> i64 {
    println(c_sqrt(16.0));      // 4
    println(c_pow(2.0, 10.0));  // 1024
    return 0;
}
extern "C" include "<math.h>" link "m" {
    fn sqrt as c_sqrt(x: f64) -> f64;
}

fn hypot(a: f64, b: f64) -> f64 {
    unsafe {
        return c_sqrt(a * a + b * b);
    }
}

fn main() -> i64 {
    println(hypot(3.0, 4.0));   // 5
    return 0;
}

Calling c_sqrt outside unsafe code is rejected:

error: Safety error (line 6): calling the C function c_sqrt() needs an `unsafe` block.

fid audit <file.fd> lists the unsafe code a program can reach. The compiler cannot check regions, effects or capabilities inside C code, so keep the C surface small.

Layouts

@repr(C) gives a struct C’s field order and padding so it can cross the boundary; @packed removes padding. See Types.

Generating bindings

fid parse-header library.h -o library.fd writes an extern "C" block for the functions in a header. Review it before use; large headers such as SDL2’s and SQLite’s are not handled yet.

Where FFI works

  • C backend (fid ccompile, fid build on Linux): headers are included and link libraries linked like any C program.
  • Native Windows (fid emit): calls go through DLL imports.
  • Interpreter (fid run): common libc calls such as sqrt are simulated.

Only a named function can be passed to a C function that expects a callback, not a closure. The native Linux (ELF) executables are static and the bare-metal path has no operating system: neither has a C library, so extern "C" is not for those targets.

Report an issue