Bun

FFI

使用內建的 bun:ffi 模組,可有效率地從 JavaScript 呼叫原生函式庫。它支援支援 C ABI 的語言(例如 Zig、Rust、C/C++、C#、Nim、Kotlin 等)。

用法(bun:ffi

若要列印 sqlite3 的版本號碼

import { dlopen, FFIType, suffix } from "bun:ffi";

// `suffix` is either "dylib", "so", or "dll" depending on the platform
// you don't have to use "suffix", it's just there for convenience
const path = `libsqlite3.${suffix}`;

const {
  symbols: {
    sqlite3_libversion, // the function to call
  },
} = dlopen(
  path, // a library name or file path
  {
    sqlite3_libversion: {
      // no arguments, returns a string
      args: [],
      returns: FFIType.cstring,
    },
  },
);

console.log(`SQLite 3 version: ${sqlite3_libversion()}`);

效能

根據 我們的基準測試bun:ffi 比透過 Node-API 的 Node.js FFI 快約 2-6 倍。

Bun 會產生並即時編譯 C 繫結,可有效率地將值轉換為 JavaScript 型別和原生型別。為了編譯 C,Bun 內嵌 TinyCC,這是一個小而快的 C 編譯器。

用法

Zig

// add.zig
pub export fn add(a: i32, b: i32) i32 {
  return a + b;
}

若要編譯

zig build-lib add.zig -dynamic -OReleaseFast

傳遞共用函式庫的路徑和要匯入到 dlopen 的符號對應

import { dlopen, FFIType, suffix } from "bun:ffi";
const { i32 } = FFIType;

const path = `libadd.${suffix}`;

const lib = dlopen(path, {
  add: {
    args: [i32, i32],
    returns: i32,
  },
});

console.log(lib.symbols.add(1, 2));

Rust

// add.rs
#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
    a + b
}

若要編譯

rustc --crate-type cdylib add.rs

C++

#include <cstdint>

extern "C" int32_t add(int32_t a, int32_t b) {
    return a + b;
}

若要編譯

zig build-lib add.cpp -dynamic -lc -lc++

FFI 型別

下列 FFIType 值受支援。

FFITypeC 型別別名
cstringchar*
function(void*)(*)()fn, callback
ptrvoid*pointer, void*, char*
i8int8_tint8_t
i16int16_tint16_t
i32int32_tint32_t, int
i64int64_tint64_t
i64_fastint64_t
u8uint8_tuint8_t
u16uint16_tuint16_t
u32uint32_tuint32_t
u64uint64_tuint64_t
u64_fastuint64_t
f32floatfloat
f64doubledouble
boolbool
charchar

字串

JavaScript 字串和類似 C 的字串不同,這會使使用原生函式庫的字串變得複雜。

JavaScript 字串和 C 字串有何不同?

為了解決這個問題,bun:ffi 匯出 CString,它擴充 JavaScript 內建的 String 以支援以 null 結束的字串並新增一些額外功能

class CString extends String {
  /**
   * Given a `ptr`, this will automatically search for the closing `\0` character and transcode from UTF-8 to UTF-16 if necessary.
   */
  constructor(ptr: number, byteOffset?: number, byteLength?: number): string;

  /**
   * The ptr to the C string
   *
   * This `CString` instance is a clone of the string, so it
   * is safe to continue using this instance after the `ptr` has been
   * freed.
   */
  ptr: number;
  byteOffset?: number;
  byteLength?: number;
}

要從以 null 結束的字串指標轉換為 JavaScript 字串

const myString = new CString(ptr);

要從具有已知長度的指標轉換為 JavaScript 字串

const myString = new CString(ptr, 0, byteLength);

new CString() 建構函式會複製 C 字串,因此在 ptr 已釋放後,可以安全地繼續使用 myString

my_library_free(myString.ptr);

// this is safe because myString is a clone
console.log(myString);

returns 中使用時,FFIType.cstring 會將指標轉換為 JavaScript 字串。在 args 中使用時,FFIType.cstringptr 相同。

函式指標

注意 — 目前不支援非同步函式。

若要從 JavaScript 呼叫函式指標,請使用 CFunction。這在使用 Bun 搭配 Node-API (napi) 且已載入一些符號時很有用。

import { CFunction } from "bun:ffi";

let myNativeLibraryGetVersion = /* somehow, you got this pointer */

const getVersion = new CFunction({
  returns: "cstring",
  args: [],
  ptr: myNativeLibraryGetVersion,
});
getVersion();

若有多個函式指標,可以使用 linkSymbols 一次定義所有函式指標

import { linkSymbols } from "bun:ffi";

// getVersionPtrs defined elsewhere
const [majorPtr, minorPtr, patchPtr] = getVersionPtrs();

const lib = linkSymbols({
  // Unlike with dlopen(), the names here can be whatever you want
  getMajor: {
    returns: "cstring",
    args: [],

    // Since this doesn't use dlsym(), you have to provide a valid ptr
    // That ptr could be a number or a bigint
    // An invalid pointer will crash your program.
    ptr: majorPtr,
  },
  getMinor: {
    returns: "cstring",
    args: [],
    ptr: minorPtr,
  },
  getPatch: {
    returns: "cstring",
    args: [],
    ptr: patchPtr,
  },
});

const [major, minor, patch] = [
  lib.symbols.getMajor(),
  lib.symbols.getMinor(),
  lib.symbols.getPatch(),
];

回呼函式

使用 JSCallback 建立 JavaScript 回呼函式,可以傳遞給 C/FFI 函式。C/FFI 函式可以呼叫 JavaScript/TypeScript 程式碼。這對於非同步程式碼或任何時候從 C 呼叫 JavaScript 程式碼時很有用。

import { dlopen, JSCallback, ptr, CString } from "bun:ffi";

const {
  symbols: { search },
  close,
} = dlopen("libmylib", {
  search: {
    returns: "usize",
    args: ["cstring", "callback"],
  },
});

const searchIterator = new JSCallback(
  (ptr, length) => /hello/.test(new CString(ptr, length)),
  {
    returns: "bool",
    args: ["ptr", "usize"],
  },
);

const str = Buffer.from("wwutwutwutwutwutwutwutwutwutwutut\0", "utf8");
if (search(ptr(str), searchIterator)) {
  // found a match!
}

// Sometime later:
setTimeout(() => {
  searchIterator.close();
  close();
}, 5000);

使用完 JSCallback 後,應呼叫 close() 來釋放記憶體。

⚡️效能提示 — 為了稍微提升效能,請直接傳遞 JSCallback.prototype.ptr,而不是 JSCallback 物件

const onResolve = new JSCallback(arg => arg === 42, {
  returns: "bool",
  args: ["i32"],
});
const setOnResolve = new CFunction({
  returns: "bool",
  args: ["function"],
  ptr: myNativeLibrarySetOnResolve,
});

// This code runs slightly faster:
setOnResolve(onResolve.ptr);

// Compared to this:
setOnResolve(onResolve);

指標

Bun 將 指標 表示為 JavaScript 中的 數字

64 位元指標如何放入 JavaScript 數字中?

TypedArray 轉換為指標

import { ptr } from "bun:ffi";
let myTypedArray = new Uint8Array(32);
const myPtr = ptr(myTypedArray);

從指標轉換為 ArrayBuffer

import { ptr, toArrayBuffer } from "bun:ffi";
let myTypedArray = new Uint8Array(32);
const myPtr = ptr(myTypedArray);

// toArrayBuffer accepts a `byteOffset` and `byteLength`
// if `byteLength` is not provided, it is assumed to be a null-terminated pointer
myTypedArray = new Uint8Array(toArrayBuffer(myPtr, 0, 32), 0, 32);

若要從指標讀取資料,您有兩個選項。對於長期指標,請使用 DataView

import { toArrayBuffer } from "bun:ffi";
let myDataView = new DataView(toArrayBuffer(myPtr, 0, 32));

console.log(
  myDataView.getUint8(0, true),
  myDataView.getUint8(1, true),
  myDataView.getUint8(2, true),
  myDataView.getUint8(3, true),
);

對於短期指標,請使用 read

import { read } from "bun:ffi";

console.log(
  // ptr, byteOffset
  read.u8(myPtr, 0),
  read.u8(myPtr, 1),
  read.u8(myPtr, 2),
  read.u8(myPtr, 3),
);

read 函式的行為類似於 DataView,但通常較快,因為它不需要建立 DataViewArrayBuffer

FFITyperead 函式
ptrread.ptr
i8read.i8
i16read.i16
i32read.i32
i64read.i64
u8read.u8
u16read.u16
u32read.u32
u64read.u64
f32read.f32
f64read.f64

記憶體管理

bun:ffi 沒有幫你管理記憶體。你必須在用完記憶體後釋放它。

從 JavaScript

如果你想追蹤 TypedArray 何時不再從 JavaScript 使用,你可以使用 FinalizationRegistry

從 C、Rust、Zig 等

如果你想追蹤 TypedArray 何時不再從 C 或 FFI 使用,你可以傳遞一個回呼函式和一個可選的內容指標給 toArrayBuffertoBuffer。這個函式會在稍後某個時間點被呼叫,也就是垃圾收集器釋放底層 ArrayBuffer JavaScript 物件時。

預期的簽章與 JavaScriptCore 的 C API 相同。

typedef void (*JSTypedArrayBytesDeallocator)(void *bytes, void *deallocatorContext);
import { toArrayBuffer } from "bun:ffi";

// with a deallocatorContext:
toArrayBuffer(
  bytes,
  byteOffset,

  byteLength,

  // this is an optional pointer to a callback
  deallocatorContext,

  // this is a pointer to a function
  jsTypedArrayBytesDeallocator,
);

// without a deallocatorContext:
toArrayBuffer(
  bytes,
  byteOffset,

  byteLength,

  // this is a pointer to a function
  jsTypedArrayBytesDeallocator,
);

記憶體安全性

極度不建議在 FFI 外部使用原始指標。Bun 的未來版本可能會新增一個 CLI 標記來停用 bun:ffi

指標對齊

如果一個 API 期望指標的大小與 charu8 不同,請確保 TypedArray 也有相同的尺寸。u64*[8]u8* 由於對齊方式的不同,並非完全相同。

傳遞指標

在 FFI 函式需要指標的地方,傳遞一個大小相等的 TypedArray

import { dlopen, FFIType } from "bun:ffi";

const {
  symbols: { encode_png },
} = dlopen(myLibraryPath, {
  encode_png: {
    // FFIType's can be specified as strings too
    args: ["ptr", "u32", "u32"],
    returns: FFIType.ptr,
  },
});

const pixels = new Uint8ClampedArray(128 * 128 * 4);
pixels.fill(254);
pixels.subarray(0, 32 * 32 * 2).fill(0);

const out = encode_png(
  // pixels will be passed as a pointer
  pixels,

  128,
  128,
);

自動產生的包裝函式 會將指標轉換為 TypedArray

困難模式

讀取指標

const out = encode_png(
  // pixels will be passed as a pointer
  pixels,

  // dimensions:
  128,
  128,
);

// assuming it is 0-terminated, it can be read like this:
let png = new Uint8Array(toArrayBuffer(out));

// save it to disk:
await Bun.write("out.png", png);