7

GitHub - nelipuu/zbind: Zig-TypeScript binding generator

 1 year ago
source link: https://github.com/nelipuu/zbind
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Repository files navigation

zbind

zbind

zbind generates TypeScript bindings for calling Zig code compiled to native code or Wasm, in Node.js or Bun or browsers.

Example Zig code lib/main.zig:

const std = @import("std");
const zbind = @import("zbind");

pub fn hello(name: []const u8) void {
    std.debug.print("Hello, {s}!\n", .{ name });
}

pub fn main() void {}

comptime {
    zbind.init(@This());
}

It exports a Zig function hello, callable from TypeScript. A wrapper function will be exported that receives a string pointer and length in memory shared between Zig and the JavaScript engine. The empty main is needed for compiling to Wasm.

Example TypeScript code src/index.ts to call it:

import { hello } from './greet.js';

hello('World');

The automatically generated TypeScript function will encode the string as UTF-8 in a buffer directly accessible by both languages.

The Zig code requires a build.zig script to compile it:

const std = @import("std");
const zbind = @import("node_modules/zbind/zbind.zig");

pub fn build(builder: *std.Build) !void {
    _ = try zbind.build(.{ //
        .builder = builder,
        .root = std.fs.path.dirname(@src().file) orelse ".",
        .main = "lib/main.zig",
        .npm = "node_modules",
        .out_dir = "dist",
        .out_name = "addon"
    });
}

Typically only the path to main Zig entry point and output binary path and name need configuring. The zbind.build call returns a std.build.Step.Compile object for linking with other libraries if needed.

Run these shell commands to install the Zig compiler, compile the code and generate TypeScript bindings:

npm install --save zbind
npm install --save-dev @oven/zig node-api-headers

# For native
zig build -Doptimize=ReleaseFast
npx zbind dist/addon.node src/greet.ts

# For Wasm
zig build -Doptimize=ReleaseSmall -Dtarget=wasm32-wasi
npx zbind dist/addon.wasm src/greet.ts

The commands compile the Zig code to a native or Wasm binary and then call a TypeScript-based tool to inspect it and generate wrapper functions in src/greet.ts with matching types and necessary marshalling.

</div


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK