ruby-bindgen generates Ruby files that use the FFI gem to call C library functions. FFI allows Ruby to directly load and call functions from C shared libraries without writing a C extension. This means:
- No compilation step - Ruby loads the library at runtime
- Easier distribution - No need to compile native code for each platform
- Simpler development - No C code to write or debug
If a library provides a C API then use it!
ruby-bindgen supports the following FFI features:
- Functions via
attach_function, including variadic functions (:varargs). Functions takingva_listparameters are skipped sinceva_listcannot be constructed from Ruby. - Structs map to
FFI::Struct - Unions map to
FFI::Union - Enums map to FFI enum types
- Callbacks for function pointer types
- Typedefs are preserved
- Forward declarations map to opaque pointer types
- Global variables via
attach_variable - Constants from
constvariables (see Constants and Macros)
See Getting Started for a step-by-step guide to creating your first FFI bindings.
See FFI Output for details on the generated files.
The test suite includes bindings generated from some popular C libraries:
| Library | Description |
|---|---|
| PROJ | Coordinate transformation library |
| SQLite | Database engine |
| libclang | C/C++ parsing library |
See test/headers/c for the input headers and test/bindings/c for the generated Ruby bindings.
Since C is procedural rather than object-oriented, you may wish to wrap the generated FFI bindings in Ruby classes to provide a more idiomatic API:
require_relative 'generated/mylib_ffi'
class MyLibWrapper
def initialize
@handle = Mylib.create_handle()
end
def process(data)
Mylib.process_data(@handle, data)
end
def close
Mylib.destroy_handle(@handle)
end
end