MregisterCallback
Bun

method

ffi.DynamicLibrary.registerCallback

callback: () => void
): bigint;

Creates a native callback pointer backed by a JavaScript function.

When signature is omitted, the callback uses a default void () signature.

The return value is the callback pointer address as a bigint. It can be passed to native functions expecting a callback pointer.

const { DynamicLibrary } = require('node:ffi');

const lib = new DynamicLibrary('./mylib.so');

const callback = lib.registerCallback(
  { arguments: ['i32'], return: 'i32' },
  (value) => value * 2,
);

Callbacks are subject to the following restrictions:

  • They must be invoked on the same system thread where they were created.
  • They must not throw exceptions.
  • They must not return promises.
  • They must return a value compatible with the declared return type.
  • They must not call library.close() on their owning library while running.
  • They must not unregister themselves while running.

Closing the owning library or unregistering the currently executing callback from inside the callback is unsupported and dangerous. Doing so may crash the process, produce incorrect output, or corrupt memory.

signature: T,
): bigint;

Creates a native callback pointer backed by a JavaScript function.

When signature is omitted, the callback uses a default void () signature.

The return value is the callback pointer address as a bigint. It can be passed to native functions expecting a callback pointer.

const { DynamicLibrary } = require('node:ffi');

const lib = new DynamicLibrary('./mylib.so');

const callback = lib.registerCallback(
  { arguments: ['i32'], return: 'i32' },
  (value) => value * 2,
);

Callbacks are subject to the following restrictions:

  • They must be invoked on the same system thread where they were created.
  • They must not throw exceptions.
  • They must not return promises.
  • They must return a value compatible with the declared return type.
  • They must not call library.close() on their owning library while running.
  • They must not unregister themselves while running.

Closing the owning library or unregistering the currently executing callback from inside the callback is unsupported and dangerous. Doing so may crash the process, produce incorrect output, or corrupt memory.