Zig Project: Wrap a C Library
One of Zig’s best tricks is how well it gets along with C. There are decades of good C libraries out there, and Zig can compile them, call them and ship them inside your program, with no extra tools. In this project you’ll do the whole thing yourself: write a tiny C library, build it with zig build, call it from Zig, and then wrap it in a Zig API that feels like it was written in Zig all along.
Writing the C library yourself means there’s nothing to download, and you’ll know exactly what’s on the other side of every call. The same steps work for a real library like SQLite or zlib.
What you’ll build
Section titled “What you’ll build”The C library, tinykv, is a small key-value store: string keys, int values. The Zig side turns this C usage:
int value;if (tinykv_get(kv, "pears", &value) == TINYKV_OK) { ... }into this:
if (stock.get("pears")) |n| { ... }and the finished demo program, a fruit stand’s stock list, prints:
2 kinds of fruit left apples: 25 pears: sold out plums: 10can't store that one: KeyTooLongWhat you’ll practise:
- Compiling C files with
zig buildand linking libc (Zig Calling C Libraries). - Declaring C functions with
extern fn, and C types likeintandconst char *in Zig (Zig C Interop). - Opaque types for C handles you never look inside (Zig Opaque Types).
- Null-terminated strings: turning a Zig slice into the
char *C wants (Zig Sentinel-Terminated Types). - Turning C return codes into Zig errors and optionals.
- Testing the wrapper with
zig build test.
Step 1: The C library
Section titled “Step 1: The C library”Make this layout:
tinykv/├── build.zig├── c/│ ├── tinykv.h│ └── tinykv.c└── src/ ├── tinykv.zig the Zig wrapper └── main.zig the demo programThe header is the library’s public face. It’s written in the usual C style: an opaque handle (callers only ever hold a pointer to it), functions that return an int status code, and an out-parameter for the value:
#ifndef TINYKV_H#define TINYKV_H
#include <stddef.h>
/* A tiny key-value store: string keys, int values. */
#define TINYKV_MAX_KEY 31 /* longest key, in bytes */
/* Return codes. */#define TINYKV_OK 0#define TINYKV_NO_MEMORY -1#define TINYKV_KEY_TOO_LONG -2#define TINYKV_NOT_FOUND -3
typedef struct tinykv tinykv; /* opaque: callers only ever see a pointer */
tinykv *tinykv_new(void); /* NULL if out of memory */void tinykv_free(tinykv *kv);int tinykv_set(tinykv *kv, const char *key, int value);int tinykv_get(const tinykv *kv, const char *key, int *value_out);int tinykv_remove(tinykv *kv, const char *key);size_t tinykv_count(const tinykv *kv);
#endifThe implementation keeps the entries in a linked list, which is plenty for a small store. You don’t need to follow every line; what matters for Zig is the header above:
#include "tinykv.h"
#include <stdlib.h>#include <string.h>
struct entry { char key[TINYKV_MAX_KEY + 1]; int value; struct entry *next;};
struct tinykv { struct entry *first; size_t count;};
tinykv *tinykv_new(void) { return calloc(1, sizeof(tinykv));}
void tinykv_free(tinykv *kv) { if (kv == NULL) return; struct entry *e = kv->first; while (e != NULL) { struct entry *next = e->next; free(e); e = next; } free(kv);}
static struct entry *find(const tinykv *kv, const char *key) { for (struct entry *e = kv->first; e != NULL; e = e->next) { if (strcmp(e->key, key) == 0) return e; } return NULL;}
int tinykv_set(tinykv *kv, const char *key, int value) { if (strlen(key) > TINYKV_MAX_KEY) return TINYKV_KEY_TOO_LONG; struct entry *e = find(kv, key); if (e != NULL) { e->value = value; return TINYKV_OK; } e = malloc(sizeof(struct entry)); if (e == NULL) return TINYKV_NO_MEMORY; strcpy(e->key, key); e->value = value; e->next = kv->first; kv->first = e; kv->count += 1; return TINYKV_OK;}
int tinykv_get(const tinykv *kv, const char *key, int *value_out) { struct entry *e = find(kv, key); if (e == NULL) return TINYKV_NOT_FOUND; *value_out = e->value; return TINYKV_OK;}
int tinykv_remove(tinykv *kv, const char *key) { struct entry **link = &kv->first; while (*link != NULL) { if (strcmp((*link)->key, key) == 0) { struct entry *gone = *link; *link = gone->next; free(gone); kv->count -= 1; return TINYKV_OK; } link = &(*link)->next; } return TINYKV_NOT_FOUND;}
size_t tinykv_count(const tinykv *kv) { return kv->count;}Notice the classic C habits we’ll have to deal with from Zig: keys must end with a 0 byte, a key longer than 31 bytes is rejected with a status code, a missing key is another status code, and the caller must remember to call tinykv_free.
Step 2: Call it from Zig, the raw way
Section titled “Step 2: Call it from Zig, the raw way”Zig can’t read the header by itself (more on that in Step 6), so we tell it what the functions look like. Each C function gets an extern fn declaration with the matching Zig types. Put this in src/raw.zig:
const std = @import("std");
// Hand-written declarations for the functions in c/tinykv.h.const tinykv = opaque {};extern fn tinykv_new() ?*tinykv;extern fn tinykv_free(kv: ?*tinykv) void;extern fn tinykv_set(kv: *tinykv, key: [*:0]const u8, value: c_int) c_int;extern fn tinykv_get(kv: *const tinykv, key: [*:0]const u8, value_out: *c_int) c_int;extern fn tinykv_remove(kv: *tinykv, key: [*:0]const u8) c_int;extern fn tinykv_count(kv: *const tinykv) usize;
pub fn main() void { const kv = tinykv_new() orelse { std.debug.print("out of memory\n", .{}); return; }; defer tinykv_free(kv);
_ = tinykv_set(kv, "apples", 3); _ = tinykv_set(kv, "pears", 5);
var value: c_int = undefined; if (tinykv_get(kv, "pears", &value) == 0) { std.debug.print("pears = {d}\n", .{value}); } std.debug.print("get(\"plums\") returned {d}\n", .{tinykv_get(kv, "plums", &value)}); std.debug.print("{d} keys\n", .{tinykv_count(kv)});}Compile it together with the C file. -lc links the C standard library, which tinykv.c needs for malloc, free and strcmp:
zig run src/raw.zig c/tinykv.c -lcYou’ll see:
pears = 5get("plums") returned -32 keysIt works! Each C type has a Zig twin:
| C | Zig | Why |
|---|---|---|
typedef struct tinykv tinykv; |
const tinykv = opaque {}; |
A type whose size and fields Zig doesn’t know. You can only point at it. |
tinykv * that may be NULL |
?*tinykv |
tinykv_new returns NULL when out of memory, so the result is optional. |
tinykv * that must not be NULL |
*tinykv |
The other functions need a real store. |
const char *key |
[*:0]const u8 |
A pointer to bytes that end with a 0. |
int, int * |
c_int, *c_int |
c_int is whatever size C’s int is on the target. |
size_t |
usize |
Both are “the size of a pointer”. |
Zig string literals already end with a hidden 0 byte, which is why "pears" can be passed straight to a [*:0]const u8.
But look at how it reads: magic numbers like -3, an undefined variable for the out-parameter, _ = to ignore status codes we should be checking. That’s what the wrapper in Step 4 will fix.
Step 3: Build it with zig build
Section titled “Step 3: Build it with zig build”Passing C files on the command line gets old quickly. Here’s a build.zig that compiles the C library into a Zig module called tinykv, builds the demo program, and adds a test step:
const std = @import("std");
pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{});
// The wrapper module, with the C library compiled into it. const tinykv = b.addModule("tinykv", .{ .root_source_file = b.path("src/tinykv.zig"), .target = target, .optimize = optimize, .link_libc = true, // tinykv.c uses malloc, free and strcmp }); tinykv.addCSourceFile(.{ .file = b.path("c/tinykv.c"), .flags = &.{ "-std=c99", "-Wall", "-Wextra" }, }); tinykv.addIncludePath(b.path("c"));
// The program that uses it. const exe = b.addExecutable(.{ .name = "fruit", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "tinykv", .module = tinykv }}, }), }); b.installArtifact(exe);
const run_step = b.step("run", "Run the fruit stand demo"); const run_cmd = b.addRunArtifact(exe); run_step.dependOn(&run_cmd.step);
// zig build test: runs the tests in src/tinykv.zig. const tests = b.addTest(.{ .root_module = tinykv }); const test_step = b.step("test", "Run the wrapper's tests"); test_step.dependOn(&b.addRunArtifact(tests).step);}The C parts, piece by piece:
.link_libc = trueis the build script’s-lc.addCSourceFilecompilesc/tinykv.cwith Zig’s built-in C compiler. The.flagsare ordinary C compiler flags:-std=c99picks the C standard, and-Wall -Wextraturn on warnings, which is good practice for any C you write.addIncludePath(b.path("c"))is where#include "tinykv.h"is looked up.- The C file is attached to the
tinykvmodule, not to the program. Anything that imports the module gets the C code with it, somain.zigdoesn’t need to know C is involved at all.
The C code is compiled for the same target and mode as the Zig code. zig build -Dtarget=x86_64-windows produced a working fruit.exe here on Linux, C part included, with no Windows C compiler installed (Zig Cross-Compilation).
Step 4: A Zig API on top
Section titled “Step 4: A Zig API on top”Now the main event: src/tinykv.zig. It keeps the raw C declarations private, inside a c namespace, and offers a Store type with methods that use Zig’s own tools: an error set instead of negative numbers, an optional instead of an out-parameter, and slices instead of null-terminated pointers:
//! A Zig-friendly wrapper around the tinykv C library (c/tinykv.h).
const std = @import("std");
/// The raw C API, declared by hand from c/tinykv.h.const c = struct { const tinykv = opaque {}; extern fn tinykv_new() ?*tinykv; extern fn tinykv_free(kv: ?*tinykv) void; extern fn tinykv_set(kv: *tinykv, key: [*:0]const u8, value: c_int) c_int; extern fn tinykv_get(kv: *const tinykv, key: [*:0]const u8, value_out: *c_int) c_int; extern fn tinykv_remove(kv: *tinykv, key: [*:0]const u8) c_int; extern fn tinykv_count(kv: *const tinykv) usize;
const MAX_KEY = 31; const OK = 0; const NO_MEMORY = -1; const KEY_TOO_LONG = -2; const NOT_FOUND = -3;};
pub const max_key_len = c.MAX_KEY;
pub const Error = error{ OutOfMemory, KeyTooLong, InvalidKey };
pub const Store = struct { handle: *c.tinykv,
pub fn init() error{OutOfMemory}!Store { const handle = c.tinykv_new() orelse return error.OutOfMemory; return .{ .handle = handle }; }
pub fn deinit(store: *Store) void { c.tinykv_free(store.handle); store.* = undefined; }
/// Sets `key` to `value`, replacing any old value. pub fn put(store: Store, key: []const u8, value: i32) Error!void { var buffer: [c.MAX_KEY + 1]u8 = undefined; const c_key = try toCString(&buffer, key); return switch (c.tinykv_set(store.handle, c_key, value)) { c.OK => {}, c.NO_MEMORY => error.OutOfMemory, c.KEY_TOO_LONG => error.KeyTooLong, else => unreachable, // tinykv_set returns nothing else }; }
/// Returns the value for `key`, or null if there is none. pub fn get(store: Store, key: []const u8) ?i32 { var buffer: [c.MAX_KEY + 1]u8 = undefined; const c_key = toCString(&buffer, key) catch return null; // such a key can't be stored var value: c_int = undefined; return switch (c.tinykv_get(store.handle, c_key, &value)) { c.OK => value, c.NOT_FOUND => null, else => unreachable, }; }
/// Removes `key`. Returns false if it wasn't there. pub fn remove(store: Store, key: []const u8) bool { var buffer: [c.MAX_KEY + 1]u8 = undefined; const c_key = toCString(&buffer, key) catch return false; return c.tinykv_remove(store.handle, c_key) == c.OK; }
pub fn count(store: Store) usize { return c.tinykv_count(store.handle); }};
/// Copies `key` into `buffer` and adds the 0 byte C expects at the end.fn toCString(buffer: *[c.MAX_KEY + 1]u8, key: []const u8) Error![*:0]const u8 { if (key.len > c.MAX_KEY) return error.KeyTooLong; if (std.mem.findScalar(u8, key, 0) != null) return error.InvalidKey; // C would stop reading there @memcpy(buffer[0..key.len], key); buffer[key.len] = 0; return buffer[0..key.len :0];}
test "put, get, overwrite and remove" { var store: Store = try .init(); defer store.deinit();
try store.put("apples", 3); try store.put("apples", 4); try std.testing.expectEqual(@as(?i32, 4), store.get("apples")); try std.testing.expectEqual(@as(?i32, null), store.get("plums")); try std.testing.expectEqual(@as(usize, 1), store.count());
try std.testing.expect(store.remove("apples")); try std.testing.expect(!store.remove("apples")); try std.testing.expectEqual(@as(usize, 0), store.count());}
test "keys C can't handle are rejected" { var store: Store = try .init(); defer store.deinit();
const longest = "abcdefghijklmnopqrstuvwxyz01234"; // 31 bytes: the limit try store.put(longest, 1); try std.testing.expectError(error.KeyTooLong, store.put(longest ++ "5", 1)); try std.testing.expectError(error.InvalidKey, store.put("bad\x00key", 1));}The ideas worth stealing for any C wrapper:
- Keep the raw API private.
cisn’tpub, so code using the module can’t calltinykv_setdirectly and skip the checks. OnlyStore,Errorandmax_key_lenare visible. initanddeinit.tinykv_newreturningNULLbecomeserror.OutOfMemory. Withvar stock: Store = try .init(); defer stock.deinit();the C memory is freed on every path, which is the Zig habit you already know from allocators. Settingstore.* = undefinedindeinitmakes an accidental use afterdeinitfail loudly in debug builds instead of quietly working.- Status codes become errors.
putturnsTINYKV_NO_MEMORYandTINYKV_KEY_TOO_LONGintoerror.OutOfMemoryanderror.KeyTooLong. Callers cantry,catchandswitchon them, and they can’t silently ignore them as with_ =. Theelse => unreachablesays “the C function never returns anything else”. Indebugandsafebuilds, Zig checks that promise and panics if it’s ever broken. - Out-parameters become return values.
getreturns?i32: a number, ornullfor “not there”. Noundefinedvariable for the caller. - Slices in, C strings inside.
toCStringcopies the key into a small stack buffer and adds the0byte, so callers can pass any[]const u8, not only literals. It also refuses keys with a0byte in the middle, which C would quietly cut short, and keys that are too long, before C ever sees them. - The constants (
MAX_KEY, the status codes) are copied from the header by hand. That’s the price of hand-written declarations: if the C library changes them, you have to update the Zig side too.
The demo program in src/main.zig uses only the Zig API:
const std = @import("std");const tinykv = @import("tinykv");
pub fn main() !void { var stock: tinykv.Store = try .init(); defer stock.deinit();
// A day at the fruit stand: deliveries are positive, sales negative. const changes = [_]struct { []const u8, i32 }{ .{ "apples", 40 }, .{ "pears", 25 }, .{ "apples", -12 }, .{ "plums", 10 }, .{ "pears", -25 }, .{ "apples", -3 }, }; for (changes) |change| { const fruit, const amount = change; const now = (stock.get(fruit) orelse 0) + amount; if (now == 0) { _ = stock.remove(fruit); } else { try stock.put(fruit, now); } }
std.debug.print("{d} kinds of fruit left\n", .{stock.count()}); for ([_][]const u8{ "apples", "pears", "plums" }) |fruit| { if (stock.get(fruit)) |n| { std.debug.print(" {s}: {d}\n", .{ fruit, n }); } else { std.debug.print(" {s}: sold out\n", .{fruit}); } }
stock.put("a-very-long-name-for-a-kind-of-fruit", 1) catch |err| { std.debug.print("can't store that one: {t}\n", .{err}); };}Run it:
zig build runYou’ll see:
2 kinds of fruit left apples: 25 pears: sold out plums: 10can't store that one: KeyTooLongstock.get(fruit) orelse 0 treats a missing fruit as zero. When a count reaches zero, the fruit is removed, so pears shows “sold out”. The last line tries a 36-byte key and gets a proper Zig error instead of a -2.
Step 5: Test the wrapper
Section titled “Step 5: Test the wrapper”The two test blocks at the bottom of src/tinykv.zig check the wrapper and the C code under it. zig build test compiles both and runs them:
zig build test --summary allYou’ll see something like:
Build Summary: 3/3 steps succeeded; 2/2 tests passedtest success+- run test 2 pass (2 total) 10ms MaxRSS:6M +- compile test debug native success 493ms MaxRSS:167MThe second test checks the edges: a 31-byte key works, 32 bytes is error.KeyTooLong, and an embedded 0 is error.InvalidKey. Edge cases like these are where wrappers break, so they’re the most useful things to test (Zig Testing has more).
Step 6: Let Zig write the declarations
Section titled “Step 6: Let Zig write the declarations”For five functions, hand-written extern lines are fine. For a real library with hundreds, you want them generated from the header. In Zig 0.17 that’s the job of the official translate-c package: @cImport was removed, as the 0.17.0 release notes explain. You add the package with zig fetch --save, and a few lines in build.zig turn c/tinykv.h into a module you can @import. Zig Calling C Libraries walks through that setup step by step.
To just look at what the translator makes of a header, the zig translate-c command still ships with the compiler:
zig translate-c c/tinykv.hAmong its output are these lines:
pub extern fn tinykv_new() ?*tinykv;pub extern fn tinykv_free(kv: ?*tinykv) void;pub extern fn tinykv_set(kv: ?*tinykv, key: [*c]const u8, value: c_int) c_int;pub extern fn tinykv_get(kv: ?*const tinykv, key: [*c]const u8, value_out: [*c]c_int) c_int;pub const TINYKV_MAX_KEY = @as(c_int, 31);Compare them with ours. The translator can’t know that key must never be NULL or that it ends with a 0, so it uses [*c]const u8, a C pointer that allows anything C allows. Every pointer parameter becomes optional too. Hand-written declarations can say more (*tinykv, [*:0]const u8), and the wrapper is where you add that knowledge either way. A common approach for big libraries: generate the raw declarations with translate-c, then write a small wrapper like ours on top.
Common mistakes
Section titled “Common mistakes”Forgetting libc. Leave out -lc (or .link_libc = true) and the C file doesn’t even compile, because without libc there are no C standard headers:
c/tinykv.c:3:10: error: 'stdlib.h' file not found#include <stdlib.h> ^~~~~~~~~~~Forgetting the C file. With zig run src/raw.zig -lc, the Zig part compiles fine, and then the linker can’t find the functions:
error: undefined symbol: tinykv_new note: referenced by raw.o:raw.mainerror: undefined symbol: tinykv_set note: referenced by raw.o:raw.main“Undefined symbol” always means “declared, but nobody compiled the code”. Add the .c file, or addCSourceFile in build.zig.
Passing a slice where C wants a C string. A []const u8 is a pointer and a length, with no 0 at the end guaranteed. Zig won’t let it through:
raw.zig:20:24: error: expected type '[*:0]const u8', found '[]const u8' _ = tinykv_set(kv, fruit, 3); ^~~~~Don’t reach for a pointer cast to make the error go away: C would read past the end of the slice looking for the 0. Copy it into a buffer with a 0 at the end, like toCString does, or use allocator.dupeSentinel(u8, slice, 0) for long strings.
Ignoring status codes. _ = tinykv_set(...) compiles, and then the one time a key is too long, nothing happens and nobody knows. Wrapping every C call in a function that turns codes into errors is the cure.
Ideas to extend it
Section titled “Ideas to extend it”- Iterate. Add
tinykv_each(kv, callback, context)to the C library, calling a function pointer for every entry, and wrap it so Zig code can loop over all keys. Zig C Interop shows callbacks withcallconv(.c). - Bigger keys. Make the C side store keys of any length with
malloc, and drop the 31-byte limit from the wrapper. - Use translate-c. Replace the hand-written
cnamespace with the module from the translate-c package, as shown on Zig Calling C Libraries, and keep theStoreAPI unchanged. Yourmain.zigand tests shouldn’t notice. - Wrap a real library. zlib, SQLite or stb_image work the same way: compile or link them in
build.zig, declare or translate the functions, wrap the handle in a struct withinit/deinit, and turn status codes into errors. - Go the other way. Build a Zig library that C programs can call, with
export fn(Zig Exporting to C).
zig buildcompiles C next to Zig:addCSourceFile(with C.flags),addIncludePath, and.link_libc = truefor C code that uses the standard library.extern fndeclares a C function. Map types carefully:opaque {}for hidden structs,?*Tfor pointers that may beNULL,[*:0]const u8for C strings,c_intforint. Zig can’t check these against the C code.- A good wrapper keeps the raw API private and offers
init/deinit, error sets instead of status codes, optionals instead of out-parameters, and slices instead of C strings. - Converting a slice to a C string means copying it and adding a
0; reject embedded zeros and over-long input before C sees them. @cImportis gone in 0.17: use the translate-c package to generate declarations, orzig translate-c header.hto peek at them.- Zig’s leak checker doesn’t track memory C allocates with
malloc.
Next up: Zig Project: Terminal Snake Game, a snake game that runs in your terminal using nothing but the standard library.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- C in the 0.17.1 language reference: C types, C pointers, and how Zig and C code fit together.
- C translation moving to an external package (0.17.0 release notes): why
@cImportwas removed and how to switch. - translate-c on Codeberg: the official package, its
Translatoroptions and example projects. - Zig build system guide: more on modules, C source files and system libraries in
build.zig.