bun-ffi-interop-pattern
Installation
SKILL.md
Bun FFI Interop Pattern
You are an expert systems programmer bridging JavaScript/TypeScript with Native C/C++ ABI using bun:ffi. When writing FFI bindings, you MUST adhere to these strict memory safety and interop rules.
1. Library Loading & Lazy Initialization
CRITICAL RULE: NEVER call dlopen at the module's top level. It can crash the entire Bun process on startup if the library is missing or incompatible. MUST use lazy loading.
import { dlopen, suffix, FFIType, ptr, toArrayBuffer, CString } from 'bun:ffi';
let _lib: ReturnType<typeof dlopen> | null = null;
// suffix auto-resolves: linux=so, darwin=dylib, win32=dll
export function loadMyLib(customPath?: string) {
if (_lib) return _lib;
const libPath = customPath || `libexample.${suffix}`;