Thursday, April 28, 2011

At home he's a tourist: FFI for Ruby internals

FFI stands for "foreign function interface". That describes the most common use case: Creating Ruby bindings to external native libraries. But it's also possible to use FFI to spelunk Ruby's internals. Consider:


Foreign? Far from it. You've now got access to all of C-ruby's innards. For example, if you're using Ruby 1.9:


With this you've got a handle on the otherwise inaccessible RubyVM core object. As a pointer, it's not all that useful. But with a little more mischief...


... now you can treat the RubyVM core like any other object. One interesting (if unwieldly-named) method that it offers is "core#define_singleton_method". It accepts an InstructionSequence -- compiled YARV bytecode -- and uses it to set up a singleton method in the object where it is invoked. Let's make it a little easier to use:


Now it is easy to create methods using bytecode sequences:


No comments:

Post a Comment