Skip to main content
Bun’s Foreign Function Interface (FFI) lets you call native libraries directly from JavaScript without writing bindings. It supports C ABI-compatible functions from any language.

Basic Usage

Opening Libraries

Platform-Specific Extensions

Absolute and Relative Paths

System Libraries

FFI Types

Primitive Types

Strings

Pointers

Function Pointers

Working with Pointers

Reading Memory

Writing Memory

Pointer Casting

C Compiler (TinyCC)

Bun includes TinyCC for compiling C code at runtime:

Including Headers

Linking Libraries

Multiple Source Files

Performance Optimization

Use Native Types

Prefer native sizes for best performance:

Batch Operations

Minimize FFI calls by batching:

Reuse Buffers

Real-World Examples

SQLite

Image Processing (stb_image)

Rust Interop

Memory Management

Manual Allocation

C Allocation

Memory Leaks

Error Handling

Check Return Values

Try-Catch

errno

Platform Differences

Windows

macOS Code Signing

Dynamic libraries must be signed:

Best Practices

  1. Check library existence
  2. Type safety
  3. Resource cleanup
  4. Document ABIs

Debugging

Performance

FFI is extremely fast in Bun:
  • Overhead: ~5-10ns per call
  • Zero-copy for buffers
  • JIT-compiled trampolines
  • SIMD optimization for bulk transfers
Benchmark: