node:ffi on top of ffi
Node 26 has an experimental node:ffi. Its
API is not bun:ffi's, which is what the module ffi follows, and two names
mean different things in them (toArrayBuffer(pointer, length) against
toArrayBuffer(ptr, byteOffset, byteLength)). So the Node API is a separate
module, node/ffi.js, installed next to ffi:
import { dlopen, getInt32, setInt32 } from 'node/ffi';
const { lib, functions } = dlopen('libm.so.6', {
cos: { arguments: ['float64'], return: 'float64' },
});
functions.cos(0); // 1
lib.close();What it has
node:ffi | Here |
|---|---|
dlopen(path, definitions) | { lib, functions }, closable with using |
dlclose(handle), dlsym(handle, name) | a DynamicLibrary or a raw handle; dlsym gives a bigint |
class DynamicLibrary | getFunction, getFunctions, getSymbol, getSymbols, registerCallback, unregisterCallback, refCallback, unrefCallback, close, [Symbol.dispose] |
fn.pointer | the function's address as a bigint |
getInt8 ... getFloat64, setInt8 ... setFloat64 | read and write under Node's names |
toString, toBuffer, toArrayBuffer | (pointer[, length[, copy]]) as in Node: a copy unless copy is false |
exportString, exportBuffer, exportArrayBuffer, exportArrayBufferView | copy into native memory, with a length check |
getRawPointer(source) | the address of a buffer, as a bigint |
suffix | "so", "dylib" or "dll" |
Where it follows Node, not ffi
- A pointer is always a
bigint,0nfor NULL (ffigives anumberornull). A pointer argument takes abigint,null, a buffer, a typed array or aDataView. - A 64-bit integer is a
bigint; 8, 16 and 32-bit integers and floats arenumbers.boolis au8number andcharani8. stringas an argument is a UTF-8 string for the duration of the call; as a return it is the address, like every pointer.buffer,arraybufferandfunctionare pointers.toBuffergives aUint8Array, as QuickJS has noBuffer.- The type names are Node's (
int32,float64,string, ...), and a signature is{ arguments, return }.
What is not there
getCurrentEventLoop()and the permission flags.- A callback is not checked: it may throw, return a promise, or close its own
library, which Node calls undefined behavior. It has to run on the thread
that made it, as for
JSCallback. refCallbackandunrefCallbackchange nothing that matters: a callback lives untilunregisterCallback()orlib.close(), however it is referenced (see Lifetime), where Node lets an unreferenced one be collected.
Not in node:ffi, but here
Structs by value, variables,
variadic functions, errno() and cc() are
in ffi, not in this module's Node API; import them from "ffi".