I am looking to generate ruby modules from existing C libraries.
In the past, I have used Swig, and found that it was a painful task. I just want to check if there'开发者_如何学Gos something better for Ruby out there, and any gotchas.
Just need to evaluate choices, so even a simple url pointing me to the site will do!
In the past, the go-to method for binding Ruby to C (or C to Ruby, it doesn't really matter) was writing an MRI C extension by hand. SWIG basically automates that, but in a really crappy way, so that writing it by hand is usually easier, faster, more performant.
However, there is a significant problem with MRI C extensions: they are MRI C extensions. This was fine, when MRI was the only Ruby Implementation, but now we have three production-ready Ruby Implementations with another two on the way in the next couple of weeks and yet another two or three to be released later this year.
Of course, there is another problem with MRI C extensions: you have to write them in C.
A better solution is the DL library in the Ruby standard library, which allows you to bind to a dynamic library (.dll
, .so
, .dylib
) at runtime, in pure Ruby. Unfortunately, it's pretty badly documented and because of that, it is not very well supported (or completely unsupported) by several Ruby Implementations: how are you going to provide a compatible implementation if there is no documentation of what "compatible implementation" means?
Rubinius introduced the Rubinius Foreign Function Interface (FFI), which is much easier to use than DL, much easier to implement for Ruby VM writers and fully documented, specified and tested. JRuby immediately copied the API, Wayne Meissner wrote two C extensions for MRI and YARV, tinyrb supports it, IronRuby, MacRuby and MagLev will pretty soon.
So, if you use FFI, you won't have to write a single line of C, and your library will automatically work on MRI, YARV, JRuby and Rubinius and in the future also on IronRuby, MacRuby and MagLev.
精彩评论