liveBook · Manning

Chapter 5: A fabulous FFI cookbook

What you will learn in chapter 5 of Systems Programming with Zig

The chapter introduction frames a recipe-book library as a small, reliable solution to a time-pressed programming assignment.

After this chapter you will be able to

What it builds on

Section by section

Introduction

The chapter introduction frames a recipe-book library as a small, reliable solution to a time-pressed programming assignment.

Key terms: compromise, recipe book library, state management

5.1 What makes a recipe book?

The section turns Tony’s needs into a practical recipe-book library specification, including an interoperability choice, recipe data, and required operations.

Key terms: audience, PHP, foreign function interface (FFI), dynamic library, C ABI, recipe, title, author, ingredients, quantity

5.2 Learning the lingua franca

This section explains why a Zig library meant to communicate with PHP must make its functions compatible with the C ABI.

Key terms: C ABI, API surface

5.2.1 So, what is the C ABI, and why do we care about it?

The section explains how linking and ABI rules let compiled programs and libraries work together, and why the C ABI serves as a common interface.

Key terms: ABI, Application Binary Interface, binary, system library, linker, static linking, dynamic linking, shared linking, FFI, C ABI

5.2.2 What using the C ABI looks like

The section shows how Zig declares C-ABI-compatible interfaces and where its usual type conveniences need adjustment.

Key terms: extern struct, export, C ABI, memory layout, c_int, c_uint, c_long, pointers, ABI-compatible data structures, errors

5.2.3 Strings without slices

This subsection contrasts C’s NUL-terminated strings with Zig slices and shows how Zig represents those strings with sentinel-terminated slices.

Key terms: C ABI, C strings, u8 slices, NUL terminator, sentinel value, [:0]u8, [:0]const u8, slice functions

5.2.4 Enums, a semantic superpower

This section explains Zig enums, their integer representation and use as type-safe table indices, and the related struct-of-arrays pattern.

Key terms: enum, switch, enum cases, else clause, enum variants, unsigned integer, C ABI, type-safe index, Entity, @fromBackingInt

5.3 Library construction

Introduces the upcoming work of turning the desired API behavior into exposed functions and data structures with the intended audience in mind.

5.3.1 Objectively good design

This section designs a C-compatible recipe book object and explains its resource, error-handling, allocator, and I/O choices.

Key terms: C ABI, RecipeBook, pointer, create, close, quit, deinitialization, optional pointer, null, SafeAllocator

5.3.2 Tabling it

The section designs a recipe book representation that keeps recipe IDs stable and simplifies memory management by storing recipes, ingredients, and strings according to their different needs.

Key terms: RecipeId, ArrayList, ingredients, Recipe, AutoHashMapUnmanaged, HashMap, Unmanaged, Auto, arena allocator, strings

5.3.3 Making it useful

This section builds the recipe book’s Zig-side behavior while explaining its choices about identifiers, string lifetimes, ingredient access, deletion, and API design.

Key terms: RecipeId, RecipeBook, recipe hash map, createRecipe, string arena, dupeCString, outlive, dangling pointer, iterator, next

5.3.4 Recipes should live on for a long time

The section shows how to save and load a recipe book as JSON, and why its flat data design makes that straightforward.

Key terms: std.json, std.json.Stringify, string arena, hash map, std.json.Reader, std.Io.Reader, std.json.parseFromTokenSourceLeaky, arena, dupe, data-oriented design

5.4 The easy part: C compatibility

This section introduces error handling as a key concern when wrapping the Zig recipe book with a C-compatible interface.

Key terms: C ABI, error handling, nullable pointers, recipe_book_create

5.4.1 Screaming louder when things go wrong

This section improves C-facing error reporting by translating Zig errors into specific error codes and returning successful data through out parameters.

Key terms: observability, nullable pointers, error codes, error set, error values, RecipeBook, out parameter, .ok

5.4.2 Sending over all that data

This section explains how to expose whole recipes and recipe iteration across a C-compatible ABI, using caller-provided buffer memory for retrieved ingredients.

Key terms: ABI barrier, recipe, granular interface, nul-terminated bytes, pointer, length, RecipeBook, RetrievedIngredient, IngredientIterator, std.heap.FixedBufferAllocator

5.4.3 Saving and loading

This section adds file access and error handling for saving and loading recipe books.

Key terms: serialization, deserialization, readers, writers, std.Io, error.WriteFailed, file_error, write_failed, Success, translateErr

5.5 What do you think, Tony?

The section shows the recipe-book library being used by Tony’s PHP app and explains why it must be built dynamically for FFI.

Key terms: -dynamic, static, dynamic library, FFI bindings

5.6 Next steps

The section briefly recaps the chapter’s library and suggests optional ways to extend or use it.

5.7 Summary

Where this is used later

Concepts explained in this chapter

← Chapter 4: Structuring programs, from REPL to webpage Chapter 6: A CHIP-8 interpreter →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.