跳轉到主要內容
JSCallback 包裝 ArkTS 函數,使其可用於期望函數指針的 C 代碼。

示例

import { JSCallback, FFIType } from 'arkffi';

const cb = new JSCallback(
  (a: number, b: number): number => a + b,
  { args: [FFIType.int32, FFIType.int32], returns: FFIType.int32 },
);

cb.call(2, 3); // → 5
cb.ptr;        // → 槽位句柄
cb.close();

構造函數

constructor(
  callback: (...args: any[]) => any,
  def: {
    args: string[];
    returns: string;
    threadsafe?: boolean;
  },
);
參數類型默認值說明
callbackFunction要包裝的 ArkTS 函數
def.argsstring[]C 函數參數類型編碼
def.returnsstringC 函數返回類型編碼
def.threadsafebooleanfalse是否可從任意線程調用

屬性

ptr

get ptr(): number;
返回可用於原生 C 代碼的函數指針地址。
  • 非線程安全:返回槽位句柄(小整數)。
  • 線程安全:返回真實的可執行蹦牀函數地址,可傳給 C 函數作爲回調參數。

getHandle()

getHandle(): number;
返回內部槽位句柄,可用於 ffi.invokeCallback()ffi.callCallbackThreadSafe()

threadsafe

readonly threadsafe: boolean;
回調是否以線程安全模式創建。

方法

call()

call(...args: any[]): any;
調用 ArkTS 回調。
cb.call(7);  // → 70

close()

close(): void;
釋放回調資源。
cb.close();
cb.call(1); // 拋出異常

線程安全回調

const cb = new JSCallback(fn, {
  args: [FFIType.int32],
  returns: FFIType.double,
  threadsafe: true,
});
cb.threadsafe; // → true

閉包捕獲

let factor = 10;
const cb = new JSCallback(
  (x: number): number => x * factor,
  { args: [FFIType.int32], returns: FFIType.int32 },
);
cb.call(5); // → 50
factor = 20;
cb.call(5); // → 100
cb.close();