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.
2. Compile the C Library
Compile this code into a shared library. On Unix-based systems (Linux, macOS), you can use the following command:
On Windows, you would use:
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:
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:
You should see the output:
You can explore the code by visiting my GitHub repository.
Sponsored Links
- Register to Digital Ocean cloud with this link and get $200 credit
- Looking for cheap CDN? Bunny is the answer
- Alternative Cloud besides AWS and Digital Ocean