Bun FFI (Foreign Function Interface)
Bun provides FFI (Foreign Function Interface) functionality that allows direct calling of native libraries written in C/C++/Rust. This chapter introduces Bun FFI usage.
FFI Introduction
FFI allows JavaScript to call native code directly without writing Node.js native plugins or WebAssembly.
Advantages
- High Performance: Direct native code calls, no IPC overhead
- Simple: No need to compile binding code
- Flexible: Can call any C ABI compatible library
Limitations
- Need to understand the target library's C API
- Memory management requires special attention
- Different platforms may require different library files
Basic Usage
Loading Dynamic Libraries
System Libraries
Data Types
FFIType Types
Type Examples
Pointer Operations
Creating Pointers
Reading Pointer Data
Passing Buffers
String Handling
C Strings
Encoders
Structs
Passing Structs
Struct Arrays
Callback Functions
JavaScript Callbacks
Practical Examples
Calling SQLite (Without Built-in)
Calling System APIs
Calling Rust Libraries
Error Handling
Checking Return Values
Closing Libraries
Performance Considerations
Avoiding Frequent Calls
Caching Function References
Summary
This chapter covered:
- ✅ FFI basic concepts and usage
- ✅ Data type mapping
- ✅ Pointer and buffer operations
- ✅ String handling
- ✅ Struct passing
- ✅ Callback functions
- ✅ Calling Rust library examples
Next Steps
Continue reading Performance Optimization to learn about Bun's performance tuning techniques.