Skip to content

Commit

Permalink
Create a basic node addon with zig
Browse files Browse the repository at this point in the history
This requires node headers within .

Running zig build will generate an addon.node file in the zig-out/lib folder.

This has only been tested on MacOS
  • Loading branch information
zschreur committed Oct 29, 2024
1 parent 1f86da5 commit d955934
Show file tree
Hide file tree
Showing 5 changed files with 236 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.zig-cache/
zig-out/
.zig-cache/
.cache/
82 changes: 82 additions & 0 deletions build.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
const std = @import("std");

// Although this function looks imperative, note that its job is to
// declaratively construct a build graph that will be executed by an external
// runner.
pub fn build(b: *std.Build) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});

// Standard optimization options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});

const lib = b.addStaticLibrary(.{
.name = "node-zig",
// In this case the main source file is merely a path, however, in more
// complicated build scripts, this could be a generated file.
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
});

lib.addIncludePath(.{ .src_path = .{
.owner = b,
.sub_path = ".cache/node/node-v20.18.0/include/node",
} });

// This declares intent for the library to be installed into the standard
// location when the user invokes the "install" step (the default step when
// running `zig build`).
b.installArtifact(lib);

// Creates a step for unit testing. This only builds the test executable
// but does not run it.
const lib_unit_tests = b.addTest(.{
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
});

lib_unit_tests.addIncludePath(.{ .src_path = .{
.owner = b,
.sub_path = ".cache/node/node-v20.18.0/include/node",
} });

const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests);

// Similar to creating the run step earlier, this exposes a `test` step to
// the `zig build --help` menu, providing a way for the user to request
// running the unit tests.
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_lib_unit_tests.step);

const nodeAddon = b.addSharedLibrary(.{
.name = "addon",
.target = target,
.optimize = optimize,
});

nodeAddon.linker_allow_shlib_undefined = true;

nodeAddon.linkLibrary(lib);
nodeAddon.addIncludePath(.{ .src_path = .{
.owner = b,
.sub_path = ".cache/node/node-v20.18.0/include/node",
} });
nodeAddon.linkLibC();
nodeAddon.addCSourceFile(.{
.file = .{ .src_path = .{
.owner = b,
.sub_path = "src/addon.c",
} },
.flags = &.{ "-Wall", "-fPIC" },
});

b.getInstallStep()
.dependOn(&b.addInstallArtifact(nodeAddon, .{ .dest_sub_path = "addon.node" }).step);
}
72 changes: 72 additions & 0 deletions build.zig.zon
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
.{
// This is the default name used by packages depending on this one. For
// example, when a user runs `zig fetch --save <url>`, this field is used
// as the key in the `dependencies` table. Although the user can choose a
// different name, most users will stick with this provided value.
//
// It is redundant to include "zig" in this name because it is already
// within the Zig package namespace.
.name = "node-zig",

// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",

// This field is optional.
// This is currently advisory only; Zig does not yet do anything
// with this value.
//.minimum_zig_version = "0.11.0",

// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
//.example = .{
// // When updating this field to a new URL, be sure to delete the corresponding
// // `hash`, otherwise you are communicating that you expect to find the old hash at
// // the new URL.
// .url = "https://example.com/foo.tar.gz",
//
// // This is computed from the file contents of the directory of files that is
// // obtained after fetching `url` and applying the inclusion rules given by
// // `paths`.
// //
// // This field is the source of truth; packages do not come from a `url`; they
// // come from a `hash`. `url` is just one of many possible mirrors for how to
// // obtain a package matching this `hash`.
// //
// // Uses the [multihash](https://multiformats.io/multihash/) format.
// .hash = "...",
//
// // When this is provided, the package is found in a directory relative to the
// // build root. In this case the package's hash is irrelevant and therefore not
// // computed. This field and `url` are mutually exclusive.
// .path = "foo",
//
// // When this is set to `true`, a package is declared to be lazily
// // fetched. This makes the dependency only get fetched if it is
// // actually used.
// .lazy = false,
//},
},

// Specifies the set of files and directories that are included in this package.
// Only files and directories listed here are included in the `hash` that
// is computed for this package. Only files listed here will remain on disk
// when using the zig package manager. As a rule of thumb, one should list
// files required for compilation plus any license(s).
// Paths are relative to the build root. Use the empty string (`""`) to refer to
// the build root itself.
// A directory listed here means that all files within, recursively, are included.
.paths = .{
"build.zig",
"build.zig.zon",
"src",
// For example...
//"LICENSE",
//"README.md",
},
}
6 changes: 6 additions & 0 deletions src/addon.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#include <node_api.h>
#include <stdio.h>

extern napi_value Init(napi_env env, napi_value exports);

NAPI_MODULE("addon", Init)
74 changes: 74 additions & 0 deletions src/root.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
const node_api = @cImport({
@cInclude("node_api.h");
});

const assert = @import("std").debug.assert;

const napi_status = node_api.napi_status;
const napi_env = node_api.napi_env;
const napi_callback_info = node_api.napi_callback_info;
const napi_value = node_api.napi_value;

fn add(env: napi_env, info: napi_callback_info) callconv(.C) napi_value {
var args: [2]napi_value = undefined; // must be var b/c of cast
var argc: usize = 2;
var status: node_api.napi_status = undefined;

status = node_api.napi_get_cb_info(env, info, &argc, &args, null, null);
assert(status == node_api.napi_ok);

if (argc < 2) {
_ = node_api.napi_throw_type_error(env, null, "Wrong number of arguments");
return null;
}

var valuetype0: node_api.napi_valuetype = undefined;
status = node_api.napi_typeof(env, args[0], &valuetype0);
assert(status == node_api.napi_ok);

var valuetype1: node_api.napi_valuetype = undefined;
status = node_api.napi_typeof(env, args[1], &valuetype1);
assert(status == node_api.napi_ok);

if (valuetype0 != node_api.napi_number or valuetype1 != node_api.napi_number) {
_ = node_api.napi_throw_type_error(env, null, "Wrong arguments");
return null;
}

var value0: f64 = undefined;
status = node_api.napi_get_value_double(env, args[0], &value0);
assert(status == node_api.napi_ok);

var value1: f64 = undefined;
status = node_api.napi_get_value_double(env, args[1], &value1);
assert(status == node_api.napi_ok);

var sum: napi_value = undefined;
status = node_api.napi_create_double(env, value0 + value1, &sum);
assert(status == node_api.napi_ok);

return sum;
}

fn declareNapiMethod(name: anytype, func: node_api.napi_callback) node_api.napi_property_descriptor {
return .{
.utf8name = name,
.method = func,
.attributes = node_api.napi_default,
.name = null,
.getter = null,
.setter = null,
.value = null,
.data = null,
};
}

export fn Init(env: napi_env, exports: napi_value) napi_value {
// see: https://nodejs.org/api/n-api.html#napi_property_descriptor
var addDescriptor = declareNapiMethod("add", add);

const status = node_api.napi_define_properties(env, exports, 1, &addDescriptor);
assert(status == node_api.napi_ok);

return exports;
}

0 comments on commit d955934

Please sign in to comment.