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 } = require('node:ffi');

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

const callback = lib.registerCallback(
  { parameters: ['i32'], result: 'i32' },
  (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.