Skip to content

FFI Output

ruby-bindgen generates a project file, an optional version file and one FFI binding file per header. The project file first loads the target library and then binding files.

flowchart LR
    subgraph Input
        H1["mylib.h"]
        H2["mylib_extra.h"]
        CF["ffi-bindings.yaml"]
    end

    H1 & H2 & CF --> RB["ruby-bindgen"]

    subgraph "FFI Output"
        P["mylib_ffi.rb"]
        V["mylib_version.rb"]
        C1["mylib.rb"]
        C2["mylib_extra.rb"]
    end

    RB --> P & V & C1 & C2

Given a project named mylib that matches mylib.h and mylib_extra.h:

output/
  mylib_ffi.rb        # project file: require 'ffi', library preamble, require_relatives
  mylib_version.rb    # version file: stub for runtime version detection (only with version_check)
  mylib.rb            # content from mylib.h
  mylib_extra.rb      # content from mylib_extra.h (reopens module)

Project file (mylib_ffi.rb)

# This file was generated by ruby-bindgen. Please do not edit by hand.
require 'ffi'

module Mylib
  extend FFI::Library

  def self.library_names
    ["mylib"]
  end

  def self.search_names
    # Cross-platform library name generation
    # Handles .so, .dylib, .dll variants
  end

  ffi_lib self.search_names
end

require_relative './mylib'
require_relative './mylib_extra'

Version file (mylib_version.rb)

When version_check is configured, a version file is generated with a stub method that you must implement to return the runtime library version. This file is preserved on subsequent runs so your implementation is not overwritten. See Version Guards for details.

module Mylib
  def self.mylib_version
    # Return the runtime library version as an integer.
    # Example: 90602 for version 9.6.2
    raise NotImplementedError, "Implement mylib_version to return the runtime library version number"
  end
end

Content file (mylib.rb)

module Mylib
  # Structs
  class MyStruct < FFI::Struct
    layout :field1, :int,
           :field2, :double
  end

  # Enums
  MY_ENUM = enum(
    :value_one, 0,
    :value_two, 1
  )

  # Callbacks
  callback :my_callback, [:int, :pointer], :void

  # Functions
  attach_function :my_function, :my_function, [:int, :string], :int
end