Bind to any runtime. Never return
any.
anybind is a modern, header-only C++ binding library for every runtime that implements Node-API: Node.js, Electron, Bun, Deno, React Native (via Node-API for Hermes), HarmonyOS ArkTS, and embedded JS engines. It is inspired by nanobind and pybind11, and it generates accurate TypeScript declarations straight from your C++ signatures.
Status: pre-alpha. The API will change. Not ready for production use.
#include <anybind/anybind.h>
int add(int a, int b) { return a + b; }
ANYBIND_MODULE(example, m) {
m.def("add", &add);
m.def("greet", [](const std::string& who) { return "hello, " + who; });
}cmake_minimum_required(VERSION 3.21)
project(example CXX)
execute_process(COMMAND node -p "require('anybind').cmakeModule"
OUTPUT_VARIABLE ANYBIND_CMAKE OUTPUT_STRIP_TRAILING_WHITESPACE)
include(${ANYBIND_CMAKE})
anybind_add_module(example example.cpp)
anybind_generate_dts(example) # writes build/example.d.ts during the buildconst m = require("./build/example.node");
m.add(1, 2); // 3
m.add("1", 2); // TypeError: argument 1: expected number// build/example.d.ts
export function add(arg0: number, arg1: number): number;
export function greet(arg0: string): string;anybind_generate_dts compiles the binding for the build host with a recording Node-API
implementation and runs its initialization, so no JS runtime is needed and the addon itself
can be cross-compiled (the generator then runs through CMAKE_CROSSCOMPILING_EMULATOR, or
comes from a host build of the project). To read the declarations from a built addon
instead, run npx anybind-stubgen build/example.node example.d.ts.
Export a default-constructible C++ class with class_<T>:
struct Counter {
static int default_step() { return 1; }
void add(int delta) { count += delta; }
int value() const { return count; }
void set_value(int next) { count = next; }
bool empty() const { return count == 0; }
private:
int count = 0;
};
ANYBIND_MODULE(example, m) {
using namespace anybind::literals;
anybind::class_<Counter>(m, "Counter")
.def_static("defaultStep", &Counter::default_step)
.def_property_readonly_static("initialValue", [] { return 0; })
.def("add", &Counter::add, "delta"_a = Counter::default_step())
.def_property("value", &Counter::value, &Counter::set_value)
.def_property_readonly("empty", &Counter::empty);
}Each new Counter() creates a separate native instance. The JavaScript wrapper owns
that instance and destroys it when collected or when its environment shuts down.
Instance methods live on the prototype and use the native instance supplied as this.
Call the static method as Counter.defaultStep(). Static methods can share a name
with instance methods and have their own overloads.
Register multiple methods under the same JavaScript name to expose overloads.
For an overloaded C++ member, use static_cast to select each member pointer.
export class Counter {
constructor();
static defaultStep(): number;
static readonly initialValue: number;
add(delta?: number): void;
value: number;
readonly empty: boolean;
}Reading counter.value calls the getter and assigning counter.value = 3 calls the
setter on that instance. A getter and setter with different JavaScript types generate
separate TypeScript get and set declarations.
Read a static property on the constructor, for example Counter.initialValue.
Use def_property_readonly_static(name, getter) for a read-only property or
def_property_static(name, getter, setter) for a writable one. The getter takes
no arguments and the setter takes the assigned value.
To bind a constructor with parameters, give its C++ argument types with
init<Args...>{}. Append overloads with .def():
struct Label {
explicit Label(int id);
Label(std::string text, int width);
};
ANYBIND_MODULE(example, m) {
using namespace anybind::literals;
anybind::class_<Label>(m, "Label", anybind::init<int>{}, "id"_a)
.def(anybind::init<std::string, int>{}, "text"_a, "width"_a = 12);
}This accepts new Label(7), new Label("intro"), and new Label("intro", 24).
Calls are positional. Names appear in diagnostics and in the generated declarations.
Argument conversion, default values and overload selection follow the same rules
as m.def(). To expose a zero-argument overload as well, add .def(anybind::init<>{}).
Once a class is bound, functions, methods and constructors can take and return it. Parameters accept instances of the class and its registered descendants, including JavaScript subclasses.
| C++ parameter | JavaScript argument | Behaviour |
|---|---|---|
T&, const T& |
an instance | refers to the wrapped object, no copy |
T |
an instance | a copy |
T*, const T* |
an instance or null |
null becomes nullptr |
Register the base class first, then call .base<Base>() on the derived binding.
Here, Shape is a public, unambiguous base of Circle.
anybind::class_<Shape>(m, "Shape").def("area", &Shape::area);
anybind::class_<Circle>(m, "Circle").base<Shape>();In JavaScript, new Circle() instanceof Shape is true. Instances inherit
methods and accessors through Shape.prototype, and the constructor inherits
static members from Shape. A derived binding can override an inherited member.
Choose a return policy immediately after the callable and before any named arguments. For a writable property, put it after the setter. The policy applies to the getter.
| C++ return | Default behaviour |
|---|---|
T* |
JS adopts the allocation. |
T&, const T& |
JS gets an independent copy. |
T, T&& |
The value moves into a new JS instance. |
std::unique_ptr<T, D> |
The wrapper takes the holder and preserves its deleter. |
std::shared_ptr<T> |
The wrapper shares the existing control block. |
Null pointers and empty smart pointers become JS null, with type T | null.
Transfer a fresh allocation only once. JS deletes it when the wrapper is collected.
For a direct pointer return, return_value_policy::take_ownership spells out the default.
Use copy for an independent copy and move to move the pointee into a new wrapper.
Repeated conversions can produce distinct JS wrappers.
using policy = anybind::return_value_policy;
anybind::class_<Document, std::shared_ptr<Document>>(m, "Document")
.def_property_readonly("root", &Document::root, policy::reference_internal);
m.def("activeDocument", &active_document, policy::reference);
m.def("openDocument", &open_document); // returns std::shared_ptr<Document>Use reference for a borrowed pointer or lvalue reference whose native owner
will outlive every JS use. Use reference_internal on an instance method or
getter for a member of the receiver. The child wrapper keeps the JS receiver
alive, including through a chain of such returns. The C++ member must still
remain at a stable address. Borrowing a const T gives a read-only native view.
Setters, non-const methods and conversions to mutable references or pointers
raise a JS TypeError on this view.
class_<T> uses std::unique_ptr<T> for objects constructed by JS. Spell
this as class_<T, std::unique_ptr<T>> or select class_<T, std::shared_ptr<T>>
to allow C++ to retain a shared owner after a JS call. A std::shared_ptr<T>
parameter accepts a shared-held wrapper or null. Borrowed and unique-held
wrappers can be passed to C++ by pointer or reference. Unique ownership
transfers from C++ to JS through an rvalue unique_ptr. This also works for
elements of returned containers. Raw pointer elements and raw pointers passed
to JS callbacks are borrowed; use smart pointers to convey ownership there.
Use enum_<E> to export the named values of a C++ enum:
enum class Color { Red, Green };
ANYBIND_MODULE(example, m) {
anybind::enum_<Color>(m, "Color").value("Red", Color::Red).value("Green", Color::Green);
}JavaScript reads Color.Red as 0. Members are enumerable and read-only.
Values must be safe JavaScript integers. Names with the same numeric value
are preserved as separate properties and share one literal in the generated type:
export declare const Color: {
readonly Red: 0;
readonly Green: 1;
};
export type Color = 0 | 1;Bound functions can take and return the enum type. A C++ signature such as
Color echo(Color color) becomes echo(color: Color): Color. Both directions
accept only registered numeric values. An invalid argument raises a JavaScript
TypeError; a C++ value that is not registered raises an Error when it is
converted to JavaScript. The same membership check applies when a call uses a
native default, including an enum inside a container or a bound struct.
For bit flags, pass anybind::flags. Any integer in range of the underlying
type then converts in both directions, so combinations such as Read | Write
work, and the generated type is number:
enum class Perm : uint32_t { Read = 1, Write = 2 };
anybind::enum_<Perm>(m, "Perm", anybind::flags).value("Read", Perm::Read).value("Write", Perm::Write);- Any runtime. Uses only the ABI-stable Node-API C interface. No V8 internals, no
node-addon-apidependency. - Never
any. TypeScript declarations are generated from C++ types. - Small and fast to compile. Header-only, C++17, minimal template bloat.
- Modern C++. C++20 coroutines ↔ Promises, zero-copy TypedArrays (planned).
Done so far: free functions and lambdas (bool, arithmetic types, std::string), argument
type checking, C++ exceptions → JS errors, named arguments with defaults, .d.ts
generation, and Windows support.
Next is 0.1.0, the first release meant for real use: classes, STL types, bigint,
callbacks, zero-copy buffers and async. See ROADMAP.md for the full plan and
release criteria.
From a fresh checkout, use the Node.js version in .nvmrc and its bundled npm
(with nvm, run nvm install and nvm use). With Python 3 available, run:
npm run setup:devSetup checks Node.js and npm, installs the pinned native tools in .venv, and
runs npm ci. Run it again after a tool version or dependency changes.
Activate .venv in your development shell with . .venv/bin/activate on
POSIX or .venv\Scripts\Activate.ps1 in Windows PowerShell.
For Visual Studio 2026 with CMake 3.31, use a Developer PowerShell and set
$env:CMAKE_GENERATOR = 'NMake Makefiles' before configuring a fresh build.
npm test # builds the test addons and runs the suite
npm run check:dts # type-checks the build-time declarations
npm run lint # checks formatting and lint rules with Biome
npm run check:format # checks C/C++ formatting with the pinned clang-format
npm run format:cpp # formats the C/C++ sources with itSetup enables the repository's pre-commit hook for this clone. If a custom hooks path or existing hooks are present, setup prints how to chain the check. The hook runs Biome on staged JS, TS, JSON and YAML files and clang-format on added or modified C++ lines. Fix reported issues and stage the intended changes. The hook uses the tools installed by setup, including when committing from an IDE. Rerun setup if you move Node.js. If you move the checkout, recreate its virtual environment at the new path.
Format C++ sources with npm run format:cpp, which uses the pinned clang-format;
an editor's own clang-format may produce different output. CI checks every C/C++
file with the pinned version. To keep git blame past formatting-only commits, run
git config blame.ignoreRevsFile .git-blame-ignore-revs. The CI declaration job
builds and tests with the contributor toolchain. The platform matrix also tests
the CMake and C++ compilers supplied by the runners.
Addon consumers require CMake ≥ 3.21, a C++17 compiler (MSVC or clang-cl on
Windows), and Node.js ≥ 18. Node-API headers come from the
node-api-headers package, so no
Node.js source headers need to be installed.