
FFI and Ruby 1.9.2 | - LiveTheDream
http://engineering.attinteractive.com/2010/09/ffi-and-ruby-1-9-2/
======
daemin
That's actually pretty neat.

Though it might be just me, being spoiled by ActiveRecord, but wouldn't it be
awesome to just instantiate an object that automatically reads the exported
functions in a library and makes them available to Ruby? Like what
ActiveRecord does with database tables.

I guess if no one else thinks of it I could do it sometime.

~~~
vasi
This is a lot harder than it sounds. A library doesn't contain any indication
of the type of the functions inside, just their names. You could instead read
the header to get the types, but that requires that the development package is
installed, oh and also you have to be able to parse arbitrary C code. Yikes!

Thankfully, someone's done a great part of the work. MacRuby and PyObjC need
to be able to call C functions, so Apple threw together BridgeSupport:
<http://bridgesupport.macosforge.org/trac/wiki> . It uses the clang front-end
to parse headers, and outputs an XML file with the function info. It would be
really cool if you could do this on non-Mac platforms, presumably it wouldn't
be terribly much work...

~~~
daemin
True, I forgot about that, that only the names of functions are called. Though
I don't think it would be that hard to create some sort of binary/assembly
code parser to run over a library to extract out the number of parameters &
return values for a function. In general all C like languages share a similar
calling structure when viewed in assembly.

The tricky part as I see it would be to identify the parameter types, which
could be done with some sort of heuristic that analyses the functions called
on each parameter, or more easily by parsing a header file provided with the
library.

Then you would have a tool that takes in a header and a library and spits out
a class that wraps that library automatically. However it wouldn't be nearly
as clean, transparent, or neat as what ActiveRecord does. Still would be a
useful tool to have.

