Language reference
Foreign functions
Nox calls native code through extern def: a declaration of a function implemented outside Nox — in C, Zig, Rust (with a C ABI), or
the system libraries — callable from Nox with normal static typing at the boundary. This page covers extern def, raw pointers, callbacks
and the trust boundary. For richer integrations see the three APIs: the Nox Native Interface for plugins that keep
the runtime's data structures private, and the HPy/WASM bridges in Internals.
For a whole C library, noxc bindgen writes the declarations for you from its header.
extern def#
extern def malloc(n: int) -> ptr from "c"
extern def free(p: ptr) -> None from "c"
extern def sqrt(x: float) -> float from "m"extern def NAME(PARAMS) -> RETURN from "LIBRARY" [retains(p1, p2)](with_rt, which passes the hidden runtime-state pointer as the first argument, exists for the standard library's own runtime shims and is
not meant for user code.)
from "LIBRARY" says where the symbol lives:
- a file path (it contains
/or ends in.o/.a) — an object or archive that is passed to the linker:from "./add.o",from "build/libfoo.a"; - otherwise a system library name, linked as
-l<name>:"m"(libm),"c","sqlite3".
A relative file path is looked up in the current directory first, so noxc run examples/app/main.nox from the project root finds native/libfoo.o. If it is not there, noxc looks in the project root (the directory with nox.json) and passes the file to the linker by absolute path, so cd examples/app && noxc run main.nox works too. The search stops at the project root: it never walks into parent directories, and a script without a nox.json keeps the plain current-directory behaviour. An absolute path is used as written.
The function name is the C symbol and is never mangled, so extern def functions are called unqualified after an import
(Modules). A library used by several declarations is linked once.
Type mapping#
| Nox | C ABI |
|---|---|
int |
int64_t |
float |
double |
bool |
integer 0/1 |
str |
const char* — NUL-terminated UTF-8, valid for the duration of the call |
None (return) |
void |
u8 … u64, i8 … i64, usize, isize |
the same-width C integer (uint8_t, …) |
ptr, ptr[T] |
void* / T* |
(P…, ptr) -> R |
a C function pointer, see Callbacks |
dict[str, str] |
an opaque handle (runtime shims only) |
Only these types may cross the boundary; classes, lists, Optional values and so on are rejected at compile time. The return of a
str from native code is reserved for the runtime's own shims (the string must be built with the runtime's allocator); plugins that need
to return text use the Nox Native Interface.
extern def malloc(n: int) -> ptr from "c"
extern def free(p: ptr) -> None from "c"
def demo() -> int:
total: int = 0
lowlevel:
raw: ptr = malloc(16)
p: ptr[i32] = ptr[i32](ptr_to_int(raw))
ptr_write(ptr_offset(p, 0), i32(7))
ptr_write(ptr_offset(p, 1), i32(35))
total = int(ptr_read(ptr_offset(p, 0))) + int(ptr_read(ptr_offset(p, 1)))
free(raw)
return total
print(demo())42A call to a native function that returns a fixed-width integer keeps its type (print(f(u8(41))) prints 42).
Calling your own native code#
// add.c — cc -c add.c -o add.o
#include <stdint.h>
int64_t c_add(int64_t a, int64_t b) { return a + b; }extern def c_add(a: int, b: int) -> int from "add.o"
print(c_add(2, 40)) # 42The same mechanism links a Zig object (zig build-obj), a static archive, or a system library — to Nox they are indistinguishable.
Ownership across the call: retains and @ffi.escape#
By default the compiler assumes native code does not keep the pointers and strings it is given beyond the call, so Nox values may be
freed or reused immediately after. If a function stores an argument (a registry, a handle that outlives the call), list the
parameter in retains(…) or decorate the declaration with @ffi.escape("param", …); @ffi.noescape("param") states the default
explicitly. Contradictory annotations are a compile error.
extern def take_list(xs: list[int]) -> None from "libexample.a" retains(xs)
@ffi.escape("xs")
extern def keep_ref(xs: ptr) -> None from "libexample.a"Errors#
An extern def call has no exception channel of its own, but most C APIs follow one of three conventions. Declare which with @ffi.errors and
every call raises a Nox exception on failure instead of returning a code you must remember to check:
class SysError(Exception):
pass
def describe(code: int) -> str:
return "code " + str(code)
@ffi.errors(raises=SysError, ok=0, errno=True, message="describe")
extern def chdir(path: str) -> int from "c" # 0 = success, -1 = failure with errno set
@ffi.errors(raises=SysError, ok_min=0)
extern def dup(fd: int) -> int from "c" # >= 0 = success
@ffi.errors(raises=SysError, null_is_error=True, errno=True)
extern def fopen(path: str, mode: str) -> ptr from "c" # NULL = failure| Argument | Meaning |
|---|---|
raises=E |
the exception class raised on failure (required); it is built from one message string |
ok=V / ok_min=V / null_is_error=True |
the success test, exactly one: result == V; result >= V; result is not NULL/0 |
errno=True |
append strerror(errno) to the message (needs import nox.ffi; the value is read right after the call) |
message="fn" |
append fn(code) where def fn(code: int) -> str is a top-level function of yours |
The raised message reads chdir failed (code -1): describe(-1): No such file or directory. The result type must be an integer (ok=/ok_min=) or a ptr/integer
(null_is_error=True); @ffi.errors cannot be combined with @ffi.callback. Calls are compiled through a small wrapper the compiler writes for you, so the
raw declaration keeps its C symbol name. For APIs with other conventions (an out-parameter, a separate get_last_error()), wrap the call in a Nox function
that checks it and raises.
Callbacks#
Native code may call back into Nox through an ordinary top-level function, using the trailing-userdata convention that most C libraries
(qsort_r, GLib, libuv) follow: the callback's last parameter is a void* that the library hands back untouched. Mark the declaration
with @ffi.callback("cb", "userdata"), naming the callback parameter and the userdata parameter; the compiler fills userdata itself
(you do not write that argument at the call site) and generates the trampoline.
def add_ints(a: int, b: int) -> int:
return a + b
@ffi.callback("cb", "userdata")
extern def c_apply(cb: (int, int, ptr) -> int, a: int, b: int, userdata: ptr) -> int from "add.o"
print(c_apply(add_ints, 3, 4))Rules: the callback type's last parameter must be ptr; every parameter and the result must be int, float, bool or ptr; the target must
be a plain top-level, non-async, non-extern def, passed by name, or a nox.ffi.Callback[F] handle that wraps a lambda, closure or bound method (see below). An exception escaping the callback
terminates the program.
The userdata does not have to be the callback's last parameter: @ffi.callback("cb", "userdata", ud_index=0) says it is parameter 0 of the callback type (C APIs such as sqlite3_exec put it
first). Pass None where the callback goes to give the library a NULL function pointer (and a NULL userdata) when it accepts "no callback".
Stored callbacks#
The native side may keep the callback and call it later, from any later point of the program: register it in one call (reg_set(on_event)),
fire it from another (reg_fire(20)), replace it by registering a different function. The compiler passes the same hidden userdata both times, so
nothing else is needed. Two rules keep this safe: call the stored function only on a thread Nox started (the main thread or one of its own worker
threads) — never from an OS thread the native library created itself — and never after the program has finished (an event loop that outlives
main). To pass a lambda, closure or bound method, wrap it in a nox.ffi.Callback[F] handle and give the handle where the callback goes; close it with close() when the library is done with it (nox.ffi).
Raw pointers#
ptr is an opaque address; ptr[T] is a typed address. They are only usable in lowlevel code and exist
for FFI, kernels and device access:
| Operation | Meaning |
|---|---|
ptr[T](addr) |
a typed pointer from an int address |
ptr_to_int(p), ptr_from_int(n) |
address ↔ integer |
ptr_offset(p, i) |
p + i elements (typed) |
ptr_read(p), ptr_write(p, v) |
typed load / store |
ptr_read_volatile, ptr_write_volatile |
loads/stores the optimiser must not elide (memory-mapped I/O) |
memory_fence(), compiler_fence() |
ordering barriers |
ptr_of(xs) |
the data pointer of a list[int], list[float] or a list of fixed-width integers, as ptr[T] — zero-copy hand-over to native code (see below) |
detach(x), adopt(p) |
turn a managed object into a raw pointer, and take a raw pointer back as a managed object of a given class |
Typed reads and writes are type-checked: ptr_write(p, v) requires v to have the pointee type. The nox.mem module wraps
the common patterns (copy, move, set, volatile access) so ordinary code rarely needs a lowlevel block of its own.
Passing a list to native code without copying#
ptr_of(xs) (inside lowlevel) gives the address of a list's elements, laid out contiguously at their natural width (list[int] as 8-byte integers, list[u8] as bytes, list[float] as doubles, and so on), typed as ptr[T]. Native code can then read or fill the list in place:
extern def memset(p: ptr, c: int, n: int) -> ptr from "c"
buf: list[u8] = [u8(0), u8(0), u8(0), u8(0)]
lowlevel:
memset(ptr_from_int(ptr_to_int(ptr_of(buf))), 255, 4)
print(buf[0]) # 255Rules: the argument must be a variable or a field (not a call result, whose list would be freed with the temporary); only list[int], list[float] and lists of fixed-width integers are accepted. The pointer is valid until the list is released or grows (append moves the elements to a bigger buffer; the list itself stays put, so call ptr_of again after growing), exactly like any other lowlevel pointer, and lies inside the trust boundary. Compared with copying the elements into a native buffer, this costs nothing per element (0.08 ns/element against 0.36 ns in the FFI benchmark).
Sizes and layouts#
sizeof(T), alignof(T) and offsetof(T, "field") work for every type; @repr("C") and @packed give classes a defined layout to share
with C structs (Classes).
The trust boundary#
extern def is raw native code execution. The compiler marshals types and tracks reference counts around the call, but it cannot
constrain what the native function does: it runs with the full authority of the process — memory access, files, network — outside Nox's
type and ownership guarantees. Consequently:
- A bug in native code (bad alignment, an out-of-bounds write, retaining a pointer it was told not to) can corrupt the whole program.
lowlevelblocks are part of the same boundary: they relax the allocation strategy, butextern defcalls inside them are no safer.- A dependency listed in
nox.jsonmay declare its ownextern defs; adding it means trusting its native code (Security). - The standard library's
nox.fsandnox.osperform no path validation; sanitise untrusted paths yourself.
Nox deliberately has no "safe mode" for extern def in 2.0 — a sandbox needs a dedicated security design.
Other foreign-code mechanisms#
- Nox Native Interface (NNI) — a stable C ABI with opaque handles for plugins that must not depend on the runtime's layouts (NNI, Plugin API).
- HPy / CPython extensions — Python C extensions load through an opaque-handle compatibility layer; a raw
PyObject*never crosses (Internals). - WebAssembly — a WASM module can be imported like a native library; importing a WASM module is separate from compiling Nox to WASM (
--target wasm32-wasi, WebAssembly).