Zig FFI 与跨语言互操作
zig-interop
源自 Bun、Ghostty 和 TigerBeetle 的 Zig FFI 与跨语言互操作经验。适用于封装 C 库、绑定 C++、将 Zig 导出为 C 接口,或配置 build.zig 以进行 C 编译。
- License 许可
- MIT
- 最近更新
- 2026-11-11
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- zig-interop
- description
- Zig FFI and cross-language interop from Bun, Ghostty, and TigerBeetle. Use when wrapping C libraries, binding C++, exporting Zig as C, or configuring build.zig for C compilation.
02 资源文件 14
- 其他examples/build_c_sources.zig4.3 KB
- 其他examples/cimport_wrapping.zig2.9 KB
- 其他examples/comptime_ffi_wrapper.zig5.1 KB
- 其他examples/cpp_shim_binding.zig4.0 KB
- 其他examples/cross_language_abi.zig3.8 KB
- 其他examples/cross_language_consumers.zig8.4 KB
- 其他examples/export_c_library.zig4.5 KB
- 其他examples/memory_ownership_boundary.zig4.8 KB
- 参考文档references/build-system-c-integration.md11.6 KB
- 参考文档references/cimport-and-type-mapping.md8.1 KB
- 参考文档references/comptime-ffi-metaprogramming.md14.0 KB
- 参考文档references/cpp-shim-patterns.md10.1 KB
- 参考文档references/cross-language-abi.md11.3 KB
- 参考文档references/exporting-zig-as-c.md10.6 KB
03 SKILL.md 正文
Zig Interop Skill
Patterns for bridging Zig with C, C++, Rust, Swift, and Objective-C, drawn from production projects that ship real FFI boundaries. This skill covers the mechanics of crossing language borders -- type mapping, memory ownership transfer, ABI compliance, build integration, and comptime code generation.
Table of Contents
- How to Use This Skill
- Bundled Resources
- @cImport Direct Binding
- C Shim Layer for C++
- Exporting Zig as a C Library
- Cross-Language via C ABI
- Zig Build System C Compilation
- Comptime Metaprogramming for FFI
- Memory Ownership Across Boundaries
- Sources
How to Use This Skill
Pick the section that matches your task:
- Wrapping a C library -- Start with @cImport Direct Binding and the
cimport_wrapping.zigexample - Binding C++ code -- Read C Shim Layer for C++, then the shim pipeline in
cpp_shim_binding.zig - Exposing Zig to other languages -- Exporting Zig as a C Library and
export_c_library.zig - Zig talking to Rust, Swift, ObjC, Go, or Ruby -- Cross-Language via C ABI and
cross_language_abi.zig - Building a multi-language client library -- Exporting Zig as a C Library and
cross_language_consumers.zig - Compiling C sources with zig build -- Zig Build System C Compilation and
build_c_sources.zig - Generating type-safe wrappers at comptime -- Comptime Metaprogramming for FFI and
comptime_ffi_wrapper.zig - Ownership rules at FFI boundaries -- Memory Ownership Across Boundaries and
memory_ownership_boundary.zig
Bundled Resources
References
Load on demand when working on a specific interop pattern:
| Reference | Description | Search hint |
|---|---|---|
references/cimport-and-type-mapping.md |
@cImport mechanics, Ghostty's c.zig pattern, Bun's pre-translation approach, opaque vs handle wrapping | @cImport, translate-c |
references/cpp-shim-patterns.md |
Bun's codegen pipeline, [[ZIG_EXPORT]] annotations, ExternTraits, Errorable(T), flat C API alternatives |
C++ shim, extern "C" |
references/exporting-zig-as-c.md |
libxev's fixed-size byte arrays, Ghostty's CAPI struct, @fieldParentPtr smuggling, module.modulemap | export fn, callconv |
references/cross-language-abi.md |
Zig-ObjC (zig-objc), Zig-Swift (module.modulemap), Zig-Rust, Zig-Go (cgo/runtime.Pinner), Zig-Ruby (zig.rb/RubyAllocator) | ABI, Rust FFI, cgo, Ruby |
references/build-system-c-integration.md |
addCSourceFiles, addTranslateC, framework linking, allyourcodebase vendoring patterns, cross-compilation |
addCSourceFiles, linkSystemLibrary, addTranslateC |
references/comptime-ffi-metaprogramming.md |
zig-objc @Type synthesis, ziglua field walking, TigerBeetle foreign code gen, zig-gobject GIR pipeline | comptime, @typeInfo, @Type |
Examples
Complete, annotated code demonstrating each pattern:
| Example | Description |
|---|---|
examples/cimport_wrapping.zig |
@cImport, type aliases, sentinel pointer conversion |
examples/cpp_shim_binding.zig |
Zig side of a C++ shim: extern decls, init/deinit lifecycle |
examples/export_c_library.zig |
Exporting Zig functions with opaque handles and error codes |
examples/cross_language_abi.zig |
extern struct layout, callbacks, context pointer passing |
examples/build_c_sources.zig |
build.zig template for compiling C alongside Zig |
examples/comptime_ffi_wrapper.zig |
Comptime type reflection for type-safe C wrappers |
examples/memory_ownership_boundary.zig |
Ownership transfer patterns across FFI boundaries |
examples/cross_language_consumers.zig |
Comptime binding generator emitting Go/Rust/C types (TigerBeetle pattern) |
@cImport Direct Binding
Zig's @cImport translates C headers at compile time, giving direct access to C types and functions without writing bindings by hand. Production projects take different approaches depending on header complexity:
- Dedicated c.zig files -- Ghostty isolates each C library's
@cImportinto a per-packagec.zigfile (e.g.,pkg/freetype/c.zig,pkg/fontconfig/c.zig). This prevents duplicate translation units and keeps import paths clean. - Pre-translated bindings -- Bun does NOT use
@cImportfor BoringSSL. Instead it ships a 19K-line pre-translated and manually enriched Zig file, giving tighter control over types and avoiding translate-c limitations. - addTranslateC in build.zig -- ziglua uses
addTranslateCas a middle ground: build-time header translation without embedding@cImportin source. - C ABI workaround files -- When Zig's C ABI has platform-specific issues, Ghostty uses small ext.c files compiled alongside the Zig code as shims.
See references/cimport-and-type-mapping.md for the full type mapping table and examples/cimport_wrapping.zig for a worked example wrapping a C library.
C Shim Layer for C++
C++ cannot be imported directly. Production projects use different strategies depending on the C++ codebase's size and complexity:
- Codegen pipeline -- Bun wraps JavaScriptCore through a three-layer system: C++
bindings.cppfiles annotated with[[ZIG_EXPORT(tag)]], a TypeScript code generator (cppbind.ts) that parses annotations and emits Zig bindings, and Zig opaque types that consume the generated declarations. Exception handling uses three tags:nothrow,zero_is_throw,check_slow. - Flat C API alternative -- Lightpanda does NOT wrap V8 C++ directly. It uses zig-v8-fork, which provides a pre-existing flat C API. When a maintained C API exists for your C++ dependency, prefer it over writing custom shims.
- ABI-compatible types -- Bun's JSValue is
enum(i64), directly matching JSC's NaN-boxed EncodedJSValue. Errorable(T) is an ABI-safe tagged union for error propagation across the boundary. ExternTraits<T> in C++ define conversion rules (e.g., WTF::String usesleakRef()to transfer ownership). - Opaque handle wrapping for STL types -- zpp wraps
std::stringbehind opaqueintptr_thandles with three ownership modes (read-only, fixed write, growable write). C++ side usesnew/deletebehindextern "C"functions; Zig caches data pointer and length to avoid FFI calls on reads. Build requires-fno-exceptions -fno-rttion the C++ side. - Separate build systems -- Bun's C++ is NOT compiled by build.zig. It uses a separate Ninja/TypeScript build system; Zig produces one .o file that links against the C++ artifacts.
See references/cpp-shim-patterns.md and examples/cpp_shim_binding.zig.
Exporting Zig as a C Library
Zig can produce shared or static libraries consumable by any C-compatible language. Production projects demonstrate two distinct approaches:
- Fixed-size byte array handles -- libxev exposes opaque types as stack-allocatable C structs containing a fixed-size byte array (
uint8_t data[XEV_SIZEOF_LOOP - sizeof(XEV_ALIGN_T)]). No heap allocation needed on the C side. Size validation tests prevent drift. - CAPI struct pattern -- Ghostty collects all
export fndeclarations into a single CAPI struct inembedded.zig. The C consumer receives one struct with all function pointers, rather than linking against individual symbols. - Callback pointer smuggling -- libxev extends its Completion struct with extra fields, then uses
@fieldParentPtrto recover context inside callbacks -- avoiding a separate userdata pointer. - Multi-language client pattern -- TigerBeetle compiles one Zig core into platform-specific static libraries consumed by Go, Rust, Python, and other language clients through the C ABI. Comptime binding generators emit idiomatic types per target language. Gotcha:
u128is passed as[16]u8because u128-by-value is broken across compilers. - Swift consumption path -- Ghostty exports through a hand-written
ghostty.hheader with amodule.modulemap, allowing Swift to import the Zig library asGhosttyKit. XCFramework generation handles macOS/iOS targets.
See references/exporting-zig-as-c.md and examples/export_c_library.zig.
Cross-Language via C ABI
The C ABI is the lingua franca for cross-language calls. Production projects demonstrate several paths:
- Zig-ObjC via zig-objc -- Ghostty uses mitchellh/zig-objc, NOT raw
objc_msgSend. Pattern:objc.getClass("NSFileManager").?.msgSend(objc.Object, objc.sel("defaultManager"), .{}). Metal rendering is the heaviest ObjC consumer, with AutoreleasePool manually managed per frame. - Zig-Swift via C API -- Ghostty has no direct Zig-Swift bridge. Architecture: Zig export fn -> hand-written ghostty.h -> module.modulemap -> Swift imports as GhosttyKit. Swift passes userdata via
Unmanaged.passUnretained(self).toOpaque(). - Zig-Rust via extern "C" -- Lightpanda bridges to html5ever: Rust exposes
extern "C"functions, Zig declares matching extern prototypes. Callback-driven memory: Zig passes function pointers into Rust, Rust calls back for DOM mutations. No shared heap. - Zig-Go via cgo -- TigerBeetle's Go client links a pre-built Zig static library through cgo. Go objects accessed from Zig callback threads are pinned with
runtime.Pinnerfor GC safety. Async bridge: Zig event loop fires a C completion callback that writes to a Go buffered channel. Achieves 94% of native Zig speed. - Zig-Ruby via zig.rb -- zig.rb implements
std.mem.Allocatorbacked by Ruby'sxmalloc/xrealloc/xfree, keeping Zig allocations visible to Ruby's GC. Comptime method binding validates signatures and generates per-arity C trampolines (0-15 args), avoiding varargs entirely. TypedDataClass wraps Zig structs as GC-tracked Ruby objects. - Callback + userdata pattern -- Ghostty's Options extern struct carries function pointers plus
?*anyopaqueuserdata for each callback, letting the other language smuggle its own context through the C boundary.
See references/cross-language-abi.md and examples/cross_language_abi.zig.
Zig Build System C Compilation
zig build can compile C and C++ sources alongside Zig, replacing Make/CMake for many projects:
- Per-package build.zig -- Ghostty isolates each C library in
pkg/<name>/with its ownbuild.zigand dedicatedc.zigfor@cImport. This keeps dependency boundaries clean and makes each library independently buildable. - addTranslateC for headers -- ziglua compiles upstream Lua C source via
addCSourceFilesand usesaddTranslateCfor headers, supporting Lua 5.1-5.5, LuaJIT, and Luau from a single codebase via comptime version dispatch. - Cross-compilation -- Pass target triple; Zig's bundled libc headers handle sysroot concerns.
- Separate C++ build -- Bun does NOT compile C++ through build.zig. When the C++ dependency has its own complex build system, link against pre-built artifacts rather than trying to replicate the build in Zig.
See references/build-system-c-integration.md and examples/build_c_sources.zig (a build.zig template).
Comptime Metaprogramming for FFI
Zig's comptime can generate type-safe wrappers from type information, eliminating boilerplate. But the approach depends on API surface size:
- Comptime function synthesis -- zig-objc's core trick:
@Type(.{ .@"fn" = ... })synthesizesobjc_msgSendcall signatures at comptime, selecting_stret/_fpretvariants based onbuiltin.target.cpu.archand return type. The MsgSend(T) mixin gives both Object and Class the same dispatch interface. - Build-time code generation -- vulkan-zig does NOT use comptime for the Vulkan API (too large). A generator executable runs during
zig build, producingvk.zigwith dispatch tables. Consumers useinline for (std.meta.fields(Dispatch))to load nullable function pointers from an opaque loader. - Comptime version dispatch -- ziglua's define.zig walks
@typeInfo(T).@"struct".fieldsat comptime to generate Lua type definitions. A single codebase supports multiple Lua versions viaswitch (lang). - Comptime-generates-foreign-code -- TigerBeetle's
rust_bindings.zigandgo_bindings.ziguse Zig comptime to emit source code in other languages --#[repr(C)]Rust structs and layout-compatible Go structs. The Zig build system runs the generator, and each language client consumes the output as checked-in generated code. - Build-time XML-to-Zig pipeline -- zig-gobject translates GIR XML into a complete Zig package with
build.zig. Generatedextern fndeclarations are aliased topub const(zero-cost). Comptime type hierarchy enablesisAssignableFrom()that walks parent chains and interfaces at compile time, withas()for safe upcast andcast()returning?*Tfor downcast. - Comptime bridge mapping -- Lightpanda's bridge.zig uses
Builder(comptime T: type)to map Zig types to JavaScript concepts at compile time.
See references/comptime-ffi-metaprogramming.md and examples/comptime_ffi_wrapper.zig.
Memory Ownership Across Boundaries
Memory ownership is the hardest part of FFI. Production projects use these strategies:
- Tagged pointer encoding -- Bun's ZigString is an extern struct with UTF-16/Latin1 encoding packed into the high bits of the pointer, avoiding a separate encoding field.
- Callback-driven allocation -- Lightpanda's Rust bridge passes function pointers into Rust; Rust calls back into Zig for DOM mutations. No shared heap means no cross-language allocator coordination.
- Custom allocator routing -- Bun routes BoringSSL memory through mimalloc by exporting
OPENSSL_memory_alloc/OPENSSL_memory_freehooks. The C library calls these instead of system malloc. - Sentinel tracking -- Ghostty's
ghostty_string_stracks a sentinel flag so the receiving side knows whether to scan for a null terminator or use a length field for deallocation. - Ownership transfer via leakRef -- Bun's ExternTraits<WTF::String> uses
leakRef()to hand a reference-counted string across the boundary without the C++ side releasing it.
See examples/memory_ownership_boundary.zig for a comprehensive example combining these patterns.
Sources
Tier 1 -- Production codebases with extensive FFI
- Bun -- JavaScript runtime; C++ interop with JavaScriptCore via codegen pipeline, BoringSSL via pre-translated bindings, custom allocator routing through mimalloc
- Ghostty -- Terminal emulator; Zig-ObjC via zig-objc, Zig-Swift via C API + module.modulemap, per-package C library isolation, CAPI struct pattern
- libxev -- Cross-platform event loop; fixed-size byte array opaque handles, @fieldParentPtr callback smuggling, hand-written C header + pkg-config
- Lightpanda -- Headless browser; flat C API via zig-v8-fork, Rust-Zig via callback-driven extern "C", comptime bridge mapping
- TigerBeetle -- Financial transactions database; one Zig core with Go/Rust/Python/etc. clients via C ABI, comptime binding generators emit foreign-language source, u128-as-[16]u8 ABI workaround, runtime.Pinner for Go GC safety
Tier 2 -- Libraries and binding generators
- vulkan-zig -- Build-time generated Vulkan bindings from XML spec, dispatch table pattern
- ziglua -- Lua binding using addTranslateC + comptime version dispatch across Lua 5.1-5.5/LuaJIT/Luau
- zig-objc -- Objective-C runtime bindings via comptime @Type function synthesis, architecture-aware dispatch
- zig-gobject -- GIR XML-to-Zig pipeline with comptime-safe type hierarchy, zero-cost extern fn aliasing, typed signal connection
- zpp -- C++ STL bridging via opaque handles; wraps std::string with three ownership modes, bidirectional data flow via function pointers
- zig.rb -- Ruby extension framework; RubyAllocator (std.mem.Allocator backed by xmalloc), comptime per-arity trampoline generation, TypedDataClass for GC-tracked Zig structs
- allyourcodebase -- Community collection of 115+ C library build.zig packages; vendoring patterns, config headers, platform dispatch without pkg-config
04 同仓库更多 Skills
Claude 技能创建指南
skill-creator
创建有效技能的指南。当用户想要创建新技能(或更新现有技能),以通过专业知识、工作流或工具集成来扩展 Claude 的能力时,应使用此技能。
素材成文逐段撰写
writing-shape
写作,利用(exploit):将原始素材逐段塑造成一篇文章。
Playwright 网页应用测试
webapp-testing
使用 Playwright 测试本地 Web 应用。适用于验证前端功能、调试 UI 行为、截取浏览器截图或查看浏览器日志。
消息重述
wait-what
停。上一条消息没有被理解(没说清楚):换一种方式重新表述。
快速原型构建
prototype
构建一个一次性原型来回答设计问题。当用户想要验证某个状态模型或逻辑是否合理,或探索 UI 应该是什么样子时使用。
代码库架构优化分析
improve-codebase-architecture
扫描代码库以发现可深化改进的机会,将其以可视化 HTML 报告的形式呈现,然后对你选中的某一项进行深入质询。