ffi.dlopen(path[, definitions])


  • path <string> | <null> 动态库的路径,或使用 null 从当前进程镜像解析符号。
  • definitions <Object> 符号定义需立即解析。
  • 返回:<Object>

加载动态库并解析所请求的函数定义。

🌐 Loads a dynamic library and resolves the requested function definitions.

在 Windows 上不支持传递 null

🌐 On Windows passing null is not supported.

当省略 definitions 时,functions 会作为一个空对象返回,直到显式解析符号为止。

🌐 When definitions is omitted, functions is returned as an empty object until symbols are resolved explicitly.

返回的对象包含:

🌐 The returned object contains:

  • lib DynamicLibrary 已加载的库句柄。
  • functions <Object> 所请求符号的可调用封装器。

返回的对象还实现了显式资源管理协议,因此可以与 using 声明一起使用。释放返回的对象会关闭库句柄。

🌐 The returned object also implements the explicit resource management protocol, so it can be used with the using declaration. Disposing the returned object closes the library handle.

import { dlopen } from 'node:ffi';

{
  using handle = dlopen('./mylib.so', {
    add_i32: { parameters: ['i32', 'i32'], result: 'i32' },
  });
  console.log(handle.functions.add_i32(20, 22));
} // handle.lib.close() is invoked automatically here. 
import { dlopen } from 'node:ffi';

const { lib, functions } = dlopen('./mylib.so', {
  add_i32: { parameters: ['i32', 'i32'], result: 'i32' },
  string_length: { parameters: ['pointer'], result: 'u64' },
});

console.log(functions.add_i32(20, 22)); 
const { dlopen } = require('node:ffi'); const { lib, functions } = dlopen('./mylib.so', { add_i32: { parameters: ['i32', 'i32'], result: 'i32' }, string_length: { parameters: ['pointer'], result: 'u64' }, }); console.log(functions.add_i32(20, 22));