Hacker News new | ask | show | jobs
by vasi 5591 days ago
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...

3 comments

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.

The LuaJit FFI includes a C parser so you can pretty much just paste in the header file. http://luajit.org/ext_ffi_tutorial.html - its not complete yet but seems pretty nice. You could do something like that for Ruby. For Lua it is also much faster than using the standard C bindings as the optimizer can see what is going on.

Having an FFI like this in a language is a really nice feature.

Wow, BridgeSupport looks amazing! I've always fantasized adding some minimal .h parsing to determine function call prototypes for node-ffi, but it's hellish to try to interpret all the typedefs and includes.