Skip to content

Lesson 6 of 9 · 28m

C Interop: Sharp Knives at the Boundary

Import C headers, link system libraries, translate types and ownership carefully, and keep unsafe boundary code small enough to audit.

Zig's C interop is excellent, and that is exactly why it causes trouble. When calling C is easy, teams import giant headers, pass pointers across ownership boundaries, and recreate the ambiguity they chose Zig to avoid. Treat the boundary as a foreign-function interface, not as a casual import. Translate types, ownership, errors, and lifetimes into explicit Zig concepts as close to the edge as possible.

Import only what you need

@cImport translates C headers into Zig declarations:

const c = @cImport({
    @cInclude("zlib.h");
});

The build must expose include paths and link the library. Conceptually:

exe.linkLibC();
exe.linkSystemLibrary("z");

Exact build APIs differ across Zig versions, but the dependency facts do not: header availability, library discovery, target sysroot, and ABI compatibility are build inputs. If the artifact is expected to cross-compile, the C dependency must exist for that target too.

C types are not automatically Zig types

C has platform-dependent integer widths, signedness quirks, enum representation, and pointer ambiguity. A char * may be mutable text, bytes with a length, an owned allocation, a static string, or a null-terminated output buffer. Zig cannot infer intent.

Translate deliberately:

extern fn compressBound(source_len: c_ulong) c_ulong;

fn bound(len: usize) usize {
    return @intCast(compressBound(@intCast(len)));
}

Narrow wrappers isolate casts. Do not scatter @intCast, @ptrCast, and sentinel conversions throughout business logic.

Null-terminated strings are a protocol

Many C APIs expect sentinel-terminated strings. Zig slices are pointer plus length and may contain zero bytes. These are different representations:

fn withCString(allocator: std.mem.Allocator, text: []const u8, f: anytype) !void {
    const z = try allocator.dupeZ(u8, text);
    defer allocator.free(z);
    try f(z.ptr);
}

If input can contain embedded zero bytes, decide whether that is invalid input or whether the C API is simply unsuitable. Silent truncation is a bug with a security costume on.

Ownership must be translated, not assumed

A C library may return memory you must free with its own allocator, memory owned by a context object, or static memory you must not free. Read the API contract and encode it in the wrapper:

sqlite3_free(x)        use sqlite's allocator, not free()
SSL_free(ctx)          context destructor
EVP_MD_CTX_free(ctx)   object-specific destructor
curl_easy_cleanup(h)   handle cleanup

The wrong free is memory corruption even if the sizes line up. In Zig wrappers, expose init/deinit or scoped functions so callers never manipulate raw C lifetimes directly.

Error conventions differ

C may report failure through return codes, null pointers, errno, output parameters, or library-specific error strings. Convert once:

fn openZ(path: [:0]const u8) !c.gzFile {
    return c.gzopen(path.ptr, "rb") orelse return error.OpenFailed;
}

A good wrapper may preserve detail internally but should expose a coherent Zig error set. Avoid returning raw integer status codes unless callers truly need them.

Keep the unsafe perimeter small

The healthiest pattern is a narrow internal module:

src/zlib.zig       imports C, casts, owns rules
src/archive.zig    pure Zig API built on zlib.zig
src/main.zig       CLI and user-facing errors

This gives you one place to audit ABI assumptions and one place to adapt when the dependency changes.

Field notes

  • C macros, bitfields, variadic functions, and flexible array members may translate imperfectly or require manual extern declarations.
  • Do not pass Zig slices directly to C expecting sentinel termination or ownership transfer. Representation and lifetime are separate questions.
  • @cImport uses Zig's C translation; it is excellent but not proof that the resulting declarations express API intent.
  • Cross-compiling with system libraries means you need target libraries and headers, not just the host package.
  • If callbacks cross the boundary, pay attention to calling convention and thread lifetime. A callback outliving its Zig state is a use-after-free factory.
  • Wrapping an unsafe C library in Zig does not make memory safe. It makes the unsafe perimeter easier to locate and audit.

Was this lesson helpful?

Sign in to rate