Making Friends with FFI

Article summary

lonely_c_extIs your Ruby C Extension lonely? FFI can help.

Many Ruby programmers have found the need to make calls on C libraries. Sometimes this is for writing performance-critical code and sometimes it is to use an existing library written in C. Ruby extensions are created by writing a small amount of glue code in C. The downside is that you need to compile your C code wrapper. This requires you to either release versions of the compiled code for all platforms or force your users to have a development environment. Furthermore, the extension is only guaranteed to run on the standard Matz Ruby Implementation (MRI). This means that your shiny new extension cannot necessarily be used by other Ruby VMs such as JRuby or MacRuby.

Make Friends

If you want your C code to play nicely with the other VMs out there, then FFI (foreign function interface) is the answer. FFI is built-in to JRuby and MacRuby; MRI requires a compiled gem for FFI access. After a night of experimentation, I was able to get C code from the Chipmunk Physics library running in Ruby via FFI (chipmunk-ffi). Just tell FFI what function to attach, what arguments it takes, what the return type is, and it will take care of the rest. FFI is a great tool that any Ruby developer should have in their tool belt and consider against writing a C extension.

C code:


void cpInitChipmunk(void);

To call it from Ruby:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# sample from chipmunk-ffi

require 'ffi'
module CP
  extend FFI::Library
  # load a C library
  ffi_lib 'chipmunk'
 
  # look up a function
  attach_function :cpInitChipmunk, [], :void

  # call the new function
  cpInitChipmunk
end

More Info