> ## Documentation Index
> Fetch the complete documentation index at: https://docs.arkffi.hmbill.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# JSCallback

> 將 ArkTS 函數包裝爲 C 回調

`JSCallback` 包裝 ArkTS 函數，使其可用於期望函數指針的 C 代碼。

## 示例

```typescript theme={null}
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();
```

## 構造函數

```typescript theme={null}
constructor(
  callback: (...args: any[]) => any,
  def: {
    args: string[];
    returns: string;
    threadsafe?: boolean;
  },
);
```

| 參數               | 類型         | 默認值     | 說明            |
| ---------------- | ---------- | ------- | ------------- |
| `callback`       | `Function` | —       | 要包裝的 ArkTS 函數 |
| `def.args`       | `string[]` | —       | C 函數參數類型編碼    |
| `def.returns`    | `string`   | —       | C 函數返回類型編碼    |
| `def.threadsafe` | `boolean`  | `false` | 是否可從任意線程調用    |

## 屬性

### `ptr`

```typescript theme={null}
get ptr(): number;
```

返回可用於原生 C 代碼的函數指針地址。

* **非線程安全**：返回槽位句柄（小整數）。
* **線程安全**：返回真實的可執行蹦牀函數地址，可傳給 C 函數作爲回調參數。

### `getHandle()`

```typescript theme={null}
getHandle(): number;
```

返回內部槽位句柄，可用於 `ffi.invokeCallback()` 和 `ffi.callCallbackThreadSafe()`。

### `threadsafe`

```typescript theme={null}
readonly threadsafe: boolean;
```

回調是否以線程安全模式創建。

## 方法

### `call()`

```typescript theme={null}
call(...args: any[]): any;
```

調用 ArkTS 回調。

```typescript theme={null}
cb.call(7);  // → 70
```

### `close()`

```typescript theme={null}
close(): void;
```

釋放回調資源。

```typescript theme={null}
cb.close();
cb.call(1); // 拋出異常
```

## 線程安全回調

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

## 閉包捕獲

```typescript theme={null}
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();
```
