ffi (Foreign Function Interface) enables Ruby to call functions in native C libraries without writing C extensions. It provides a dynamic approach to interfacing with C code, allowing developers to load shared libraries and invoke their functions directly from Ruby. The gem eliminates the need for compiled Ruby extensions when wrapping existing C libraries, making native library integration more accessible and portable.
The gem uses libffi under the hood to handle calling conventions, type marshalling, and memory management between Ruby and C. It supports structs, unions, pointers, callbacks, and most C data types with automatic conversion between Ruby and C representations. ffi includes a DSL for defining library interfaces, handling function signatures, and managing memory lifetimes. It works across platforms without recompilation, as the FFI definitions are pure Ruby code that adapts to the host system's calling conventions.
ffi is widely used for wrapping system libraries, graphics libraries, and other native code without maintaining platform-specific compiled extensions. Popular gems like childprocess, rbnacl, and many others use ffi to interface with native libraries. It's particularly valuable for prototyping native library bindings, accessing platform-specific APIs, and maintaining gems that need to work across Ruby implementations (MRI, JRuby, TruffleRuby) without separate native extensions for each.
gem install ffi Run this gem instantly in your browser without any installation:
Open in RunRuby.dev →All 109 versions available for installation