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.

在已挂载的 虚拟文件系统 内部的 path 是支持的:操作系统的动态加载器无法打开虚拟路径,因此库的字节会从 VFS 读取,并从一个私有的、自动清理的临时映像加载,而 lib.path 会继续报告虚拟路径。真实文件系统上的库不受影响,会直接加载。

🌐 A path inside a mounted virtual file system is supported: the operating system's dynamic loader cannot open a virtual path, so the library's bytes are read from the VFS and loaded from a private, self-cleaning temporary image instead, while lib.path keeps reporting the virtual path. Libraries on the real file system are unaffected and load directly.

当省略 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, suffix } from 'node:ffi';

{
  using handle = dlopen(`./mylib.${suffix}`, {
    add_i32: { arguments: ['int32', 'int32'], return: 'int32' },
  });
  console.log(handle.functions.add_i32(20, 22));
} // handle.lib.close() is invoked automatically here. 
import { dlopen, suffix } from 'node:ffi';

const { lib, functions } = dlopen(`./mylib.${suffix}`, {
  add_i32: { arguments: ['int32', 'int32'], return: 'int32' },
  string_length: { arguments: ['pointer'], return: 'uint64' },
});

console.log(functions.add_i32(20, 22)); 
const { dlopen, suffix } = require('node:ffi'); const { lib, functions } = dlopen(`./mylib.${suffix}`, { add_i32: { arguments: ['int32', 'int32'], return: 'int32' }, string_length: { arguments: ['pointer'], return: 'uint64' }, }); console.log(functions.add_i32(20, 22));