Calling native code
Specified by VIP-81. The runtime calls native code under Bun, and under Node started with
--experimental-ffi.
A foreign block declares the functions of a C-ABI shared library, and a @repr("C") schema declares a struct with C layout. The compiler checks every signature, and the runtime loads the library and calls it with no N-API, no node-gyp and no npm dependency. Use it to call C, Zig, Rust or Go code that exports C functions.
Declare a struct and a library
// image.vibe
import { Capability } from "vibelang-runtime/ffi"
error ImageDecodeError {
code: number
}
@repr("C")
export schema ImageHeader {
readonly width: u32
readonly height: u32
readonly channels: u8
}
export foreign "c" from "libimage" {
pure fn image_pixel_count(hdr: ptr<ImageHeader>): u64
effect fn image_decode(
input: slice<u8>,
out_hdr: mut ptr<ImageHeader>,
out_pixels: mut slice<u8>
): void ! ImageDecodeError
}
export effect function decode(input: Uint8Array) {
const header = ImageHeader.alloc()
const pixels = new Uint8Array(1024)
try image_decode(input, header, pixels)
return { header: ImageHeader.read(header), count: image_pixel_count(header) }
}
export effect function main(input: Uint8Array) {
provide Capability.allowAll {
return try decode(input)
}
}ImageHeader is both a type and a value. The value knows the layout the C compiler gives the struct: ImageHeader.size is 12, ImageHeader.align is 4 and ImageHeader.offsets.channels is 8. ImageHeader.alloc(fields) makes a zeroed buffer of that size, ImageHeader.read(buffer) reads the fields back, and ImageHeader.write(buffer, fields) sets them.
The library name gets the host's suffix, so "libimage" is libimage.so on Linux, libimage.dylib on macOS and libimage.dll on Windows. The runtime looks in the directories of the VIBE_FFI_LIBRARY_PATH environment variable first, then leaves the name to the system loader. The library loads on the first call and stays loaded.
The types of a signature
| Vibe ABI type | C | In VibeLang |
|---|---|---|
bool | bool | boolean |
i8 u8 i16 u16 i32 u32 f32 f64 | the fixed-width type | number |
i64 u64 isize usize | the 64-bit type | bigint |
cstring | const char* | string |
ptr<T>, mut ptr<T> | const T*, T* | a Uint8Array over the memory, or an address |
slice<T>, mut slice<T> | a pointer and a size_t element count, two arguments | the typed array of T: Uint8Array for u8, Uint32Array for u32, Float64Array for f64, BigInt64Array for i64 |
void | void | a result only |
A slice passes its pointer and its length together, so the native side never has to guess a size. The length counts elements of T, so a slice takes the typed array of T: a Uint8Array passed to a slice<u32> is a type error. At run time the view's elements must be T's width: a view of another width (a DataView counts as bytes) is refused before the native call, never reinterpreted, and so is a view that does not hold a whole number of aligned Ts. usize and isize are as wide as the target's pointer: their slices take BigUint64Array and BigInt64Array, and under a 4-byte pointer the runtime refuses those views before the native call. The element is one of u8, i8, u16, i16, u32, i32, u64, i64, usize, isize, f32 and f64; any other is EK8101. A mut parameter needs a buffer you may write: passing a Readonly<Uint8Array> is EK8105. A @repr("C") schema crosses a signature behind ptr<T>, never by value.
In a @repr("C") schema a pointer-like field holds an address, not a buffer: a ptr<T> or cstring field reads and writes as a bigint, and a slice<T> field as { ptr: bigint, len: bigint }.
Import a native source
// math.c
#include <stdint.h>
int32_t add_i32(int32_t a, int32_t b) { return a + b; }// sum.vibe
import { Capability } from "vibelang-runtime/ffi"
import { add_i32 } from "./math.c" with { type: "ffi" }
export effect function sum() {
provide Capability.allowAll {
return add_i32(2, 3)
}
}The compiler reads the exported functions of a .c, .zig, .rs or .go file and checks every call against them (EK8103). When it writes the module's JavaScript it builds the source into a shared library under .vibe/ffi-cache, with cc, zig build-lib, rustc --crate-type cdylib or go build -buildmode=c-shared, and binds each imported name to it. Every emit builds the source again, so the library follows its headers, the files it imports and the toolchain, not only the source file; the library is named by the hash of its own bytes. The bindings are made before the module's first statement runs, wherever the import is written. A source that does not build, or whose toolchain is not installed, is EK8103 on the import. So is a name the built library does not export, such as a function the source declares and never defines. Checking alone, as an editor does, builds nothing. Add .vibe/ to .gitignore.
Import the functions by name: a default import or import * as math is EK8103, because a native library has no such value to bind. An imported function is called like a pure fn: synchronously, under the Capability.Ffi of the Effect that calls it. Its signature belongs to the function, so a copy (const plus = add_i32), a property or an argument that holds it is checked at its calls like the import.
pure fn and effect fn
A pure fn is an ordinary synchronous call that returns its result. An effect fn returns an Effect: run it with try. It requires Capability.Ffi and can fail with FfiCallError, both from vibelang-runtime/ffi.
An effect fn may declare one error class after !. The native function then takes one more trailing argument, a pointer to { int32_t code; const uint8_t* msg_ptr; size_t msg_len; }. When it sets a non-zero code, the call fails with that class, built from { code, message }.
Capability.allowAll, Capability.denyAll and Capability.allowPaths(globs) are layers. Without a grant the library never loads and the call fails with code 5801. A pure fn has no requirement to carry the capability, so every call checks the capability of the Effect it runs in. A library another fiber already loaded gives a caller without a grant no access.
What the compiler checks
| Code | Mistake |
|---|---|
EK8101 | A type the ABI cannot pass, such as Map<string, number>, in a signature or a @repr("C") schema. |
EK8102 | A @repr("C") schema field that is recursive or has no fixed size. Use ptr<T> or slice<T>. |
EK8103 | A call of a function imported with with { type: "ffi" } that does not match the native source, a name the source does not export or define, a default or namespace import, or a source that does not build. |
EK8104 | A pure fn that declares an error with !. Only an effect fn has an error channel. |
EK8105 | An immutable buffer passed to a mut slice<T> or mut ptr<T> parameter. |
Limits today
- Bun has a backend, and so does a Node that has the experimental
node:ffibuiltin: start it with--experimental-ffi. Node 26.14 has the builtin; Node 24 does not. Under a Node without it, Deno andvibe runa call fails withFfiLoadError, reason"unsupported-runtime". - An
effect fnruns on the calling thread. The worker pool and the cancellation token VIP-81 describes are not built. - A native source import builds for the machine that compiles it. The emitted module names the built library relative to itself, so ship
.vibe/ffi-cachebeside your output in the same layout, or put the libraries' directory inVIBE_FFI_LIBRARY_PATH. Cross-compiling for other targets is not built. - The signature of a native source import is read from the text of its exported functions. Parameters are checked; the result is not typed yet, so annotate it where you use it.
.vibe/ffi-cachekeeps every library it has built. Each edit of a native source or of a file it includes adds one, and nothing removes the old ones: delete the directory before a release build so that only the current libraries ship.- On macOS the C and Zig builds state the library's install name so that an unchanged source builds the same file. That is not verified on a Mac; a Go source there may get a new library name on every build.
- A native source import needs ES module output. In a module that compiles to CommonJS, TypeScript rejects the import attribute (
TS2856). - Under
node:ffia callback lives in the newest open library. That library stays open, after you close it, until its callbacks are closed. - Layout assumes a 64-bit target.