跳转到主要内容
dlopen 加载共享库并返回带类型化符号的 Library 实例。

语法

function dlopen<Fns extends Record<string, FFIFunction>>(
  libName: string,
  defs: Fns,
): Library<Fns>;

示例

import { dlopen, FFIType } from 'arkffi';

const lib = dlopen('libffi_target.so', {
  add:     { args: [FFIType.double, FFIType.double],     returns: FFIType.double },
  compute: { args: [FFIType.int32, FFIType.double, FFIType.CString], returns: FFIType.double },
});

lib.symbols.add(2.0, 3.0);
lib.symbols.compute(0, 4.0, 'square');
lib.close();

参数

参数类型说明
libNamestring.so 库的路径或名称
defsRecord<string, FFIFunction>函数名到类型定义的映射

FFIFunction

interface FFIFunction {
  args: string[];        // 参数类型编码
  returns: string;       // 返回类型编码
  threadsafe?: boolean;  // 用于 JSCallback 定义
}

类型推断

dlopen 使用 TypeScript 泛型推断 symbols 的结构,为所有定义的函数名提供 IDE 自动补全。
import { dlopen, FFIType } from 'arkffi';

const lib = dlopen('lib.so', {
  myFunc: { args: [FFIType.double, FFIType.double], returns: FFIType.double },
});
lib.symbols.myFunc(2.0, 3.0); // 自动补全

返回值

返回 Library 实例。