native_toolchain_zig library
Zig libraries and generated Dart bindings for Dart build hooks.
Use ZigBuilder in a build hook to compile and register a native library. Use generateBindings to write Dart bindings for exported Zig declarations, or generateBindingsSource to inspect the generated source in memory. Regenerate bindings when the exported interface changes.
The generated asset ID must match the asset registered by the build hook.
For example, an output of lib/ffi.g.dart uses assetName: 'ffi.g.dart'.
Build hook:
await build(args, (input, output) async {
await ZigBuilder(
assetName: 'ffi.g.dart',
libraryName: 'counter',
zigDir: 'zig',
).run(input: input, output: output, logger: Logger('bindings'));
});
Calling the generated bindings, from the bindings example:
// Simple function calls using generated bindings.
print('add(3, 4) = ${add(3, 4)}');
print('multiply(2.5, 4.0) = ${multiply(2.5, 4.0)}');
print('clampValue(15, 0,10) = ${clamp_value(15, 0, 10)}');
C callbacks require explicit lifetime management, as in the cImport example:
int foldPoints() {
var points = calloc<CImportPoint>(2);
try {
points[0] = cimport_point_make(1, 1);
points[1] = cimport_point_make(2, 3);
var callback = NativeCallable<FoldCallback>.isolateGroupBound(
(CImportPoint point, Pointer<Void> _) => point.x + point.y,
exceptionalReturn: 0,
);
try {
return cimport_fold_points(points, 2, callback.nativeFunction, nullptr);
} finally {
callback.close();
}
} finally {
calloc.free(points);
}
}
Zig 0.15.2 and 0.16.0 are covered by the compatibility checks.
Classes
- GeneratedBindingsResult
- In-memory result of generating Dart bindings for a Zig package.
- GeneratedDartFunction
- A public function in the generated Dart binding library.
- GeneratedDartParameter
- A named parameter in an emitted Dart function.
- GeneratedDartType
- A Dart FFI type emitted from a Zig declaration.
- Target
- Represents a Zig cross-compilation target.
- ZigBindingsOptions
- Configuration for generating Dart FFI bindings from a Zig package.
- ZigBuilder
- A Zig compiler integration for Dart native-asset build hooks.
Enums
- Optimization
- Zig build optimization levels.
Functions
-
generateBindings(
ZigBindingsOptions options, {Logger? logger}) → Future< void> - Generates bindings once and writes the Dart source to ZigBindingsOptions.output.
-
generateBindingsSource(
ZigBindingsOptions options, {Logger? logger}) → Future< GeneratedBindingsResult> - Returns generated Dart source, asset identity, and declaration metadata.
-
watchBindings(
ZigBindingsOptions options, {Logger? logger, Duration pollInterval = const Duration(seconds: 1)}) → Future< void> - Regenerates bindings when source files under the Zig directory change.