跳转到主要内容
CFunction 将原始 C 函数指针包装为可调用的 ArkTS 函数。

示例

import ffi from 'liblibrary.so';
import { CFunction, FFIType } from 'arkffi';

const handle = ffi.load('libffi_target.so');
const ptr = ffi.getSymbolPtr(handle, 'add');

const add = CFunction({
  args: [FFIType.double, FFIType.double],
  returns: FFIType.double,
  ptr: ptr,
});

add(2.0, 3.0); // → 5.0
add.close();
ffi.close(handle);

语法

function CFunction(def: {
  args: string[];
  returns: string;
  ptr: number;
}): {
  (...args: any[]): number;
  close(): void;
};

参数

参数类型说明
def.argsstring[]C 函数参数类型编码,支持 FFIType.callback(调用时自动从 JSCallback 中提取 .ptr
def.returnsstringC 函数返回类型编码
def.ptrnumber原始函数指针地址

回调类型参数

当参数类型为 FFIType.callback'k')时,传入的 JSCallback 会被自动提取其 .ptr
let fn = CFunction({
  args: [FFIType.callback, FFIType.int32],
  returns: FFIType.int32,
  ptr: applyPtr,
});
fn(cb, 21); // cb.ptr 自动作为第一个参数传入

获取指针

使用 ffi.getSymbolPtr(handle, name)
import { CFunction, FFIType } from 'arkffi';
import ffi from 'liblibrary.so';

const handle = ffi.load('lib.so');
const ptr = ffi.getSymbolPtr(handle, 'calculate');
const fn = CFunction({ args: [FFIType.int32, FFIType.double], returns: FFIType.double, ptr });
fn(42, 3.14);
fn.close();
ffi.close(handle);