Ruby’s New FFI Library: Calling External Libraries Just Got A Whole Lot Easier
One of the largest problems plaguing Ruby implementations [..] is the ever-painful story of "extensions". In general, these take the form of a dynamic library, usually written in C, that plugs into and calls Ruby's native API as exposed through ruby.h and libruby.
The many compiled bridges between external libraries and Ruby pose a problem for alternate implementations like JRuby, because of the complexity involved in exposing internals of the implementation or expensive serialization in both directions. Instead, an interface is necessary so that instead of developing libraries that act only as unique bridges to others, we can just have one library that provides the interface to any arbitrary library of our choice.
Ruby already has a library called "dl" that makes it possible to dynamically link external libraries with Ruby. It's a bit arcane though, and Charles points out that it's not widely used "because of real or perceived bugs." Given this, and given the need for an implementation that can be compatible with JRuby, Wayne Meissner has developed "FFI", a new Ruby library that provides "Foreign Function Interface" features to Ruby.
A basic demonstration of a Ruby script that uses C's getpid function should be enough to demonstrate the simplicity of FFI:
require 'ffi' module GetPid extend FFI::Library attach_function :getpid, , :uint end puts GetPid.getpid
The best part? FFI is available for Ruby 1.9, Ruby 1.8.6 and 1.8.7 (just
gem install ffi), as well as JRuby 1.1.4 (and above) and Rubinius (Rubinius's implementation is separate to Wayne's, but works similarly). Wayne has also written a blog post with his side of the story. He says he's waiting to "see how people are actually using it in the real world."
This FFI implementation has the hallmarks of becoming a new Ruby standard for calling out to external, compiled libraries. Let's get behind it, start using it, and crank out some code to see how it operates!