library.registerCallback([signature,] callback)


创建由 JavaScript 函数支持的本地回调指针。

🌐 Creates a native callback pointer backed by a JavaScript function.

当省略 signature 时,回调使用默认的 void () 签名。

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

返回值是作为 bigint 的回调指针地址。它可以传递给期望回调指针的本地函数。

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

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

const lib = new DynamicLibrary(`./mylib.${suffix}`);

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

回调受到以下限制:

🌐 Callbacks are subject to the following restrictions:

  • 它们必须在创建它们的同一系统线程上被调用。
  • 它们不得抛出异常。
  • 他们不能食言。
  • 它们必须返回与声明的返回类型兼容的值。
  • 他们在运行时不得在其拥有的库上调用 library.close()。
  • 他们在运行时绝不能注销自己。

从回调内部关闭拥有的库或注销当前正在执行的回调是不支持且危险的。这样做可能会导致进程崩溃、产生错误的输出或损坏内存。

🌐 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.

如果在回调执行期间运行回调的线程被停止,例如被 worker.terminate()、Worker 中的 process.exit() 或主线程退出停止,只有该线程会停止。回调会返回到本地代码但没有值:非空返回值会被初始化为零,所以本地代码会收到 0、false 或空指针。如果本地代码没有处理这种值,例如解引用返回的空指针,可能会导致进程崩溃。

🌐 If the thread running a callback is stopped while the callback executes, for example by worker.terminate(), by process.exit() in a Worker, or by the main thread exiting, only that thread stops. The callback returns to native code without a value: non-void return values are zero-initialized, so native code receives 0, false, or a null pointer. Native code that does not handle such a value, for example by dereferencing a returned null pointer, can crash the process.