Return to Ruby, Foreign Function Interface (FFI)
Ruby FFI (Foreign Function Interface) is a gem for Ruby that allows the execution of code written in other languages, such as C, directly from Ruby programs. It provides a way to dynamically load libraries, access their functions, and define custom data types. Ruby FFI eliminates the need for writing C extensions in Ruby and simplifies the process of interfacing with external libraries.
```ruby require 'ffi'
module MyLib
extend FFI::Library ffi_lib 'mylib.so'
# Define function signature attach_function :add, [:int, :int], :intend
result = MyLib.add(5, 3) puts result # Output: 8 ```
In this example, `ffi_lib` loads the shared library `mylib.so`, `attach_function` defines the `add` function with its argument and return types, and then the `add` function is called directly from Ruby.