How to Call C Code from Ruby Using FFI
- Categories:
- tutorial
In this tutorial, we’ll create a small C library that provides a function to add two integers, and then we’ll use FFI in Ruby to call that function.
1. Create the C Library
First, we’ll write a simple C library with a function to add two integers.
// myadder.c
#include <stdio.h>
// Function to add two integers
int add(int a, int b) {
return a + b;
}
2. Compile the C Library
Compile this code into a shared library. On Unix-based systems (Linux, macOS), you can use the following command:
gcc -shared -o libadder.so -fPIC myadder.c
On Windows, you would use:
gcc -shared -o adder.dll myadder.c
3. Use FFI in Ruby
Now, we’ll write Ruby code to use the ffi
gem to call the add
function from our C library. If you haven’t already installed the ffi
gem, you can do so using:
gem install ffi
# caller.rb
require 'ffi'
module Adder
extend FFI::Library
# Load the shared library
ffi_lib './libadder.so' # Use 'libadder.dll' on Windows
# Attach the add function
# Maps the `add` function from the C library to Ruby.
# The arguments and return type are specified in the array (`[:int, :int]`
# for two integers and `:int` for the return type).
attach_function :add, [:int, :int], :int
end
# Use the add function
result = Adder.add(3, 7)
puts "The result of adding 3 and 7 is: #{result}"
Running the Example
Ensure that the compiled shared library (libadder.so
or adder.dll
) is in the same directory as your Ruby script or in a directory included in your library path.
Run your Ruby script:
ruby caller.rb
You should see the output:
The result of adding 3 and 7 is: 10
You can explore the code by visiting my GitHub repository.