Thursday, March 12, 2009

Insane things to do with FFI

Inspired by jmettraux's FFI bindings to call the lua interpreter (http://github.com/jmettraux/rufus-lua/tree/master) from ruby using FFI, I whipped up the following:

$ cat tr.rb

require "ffi"
module Tr
extend FFI::Library
ffi_lib "#{Dir.pwd}/libtinyrb.so"
attach_function :new, :TrVM_new, [ ], :pointer
attach_function :eval, :TrVM_eval, [ :pointer, :string, :string ], :long
end
ffi = "module LibC; attach_function :cputs, :puts, [ :string ], :int;end; LibC.cputs 'Hello via TinyRuby FFI'"
vm = Tr.new
Tr.eval(vm, "puts \"Hello, World via TinyRuby puts\"", "<eval>")
Tr.eval(vm, ffi, "<eval>")

$ ruby1.9 tr.rb
Hello, World via TinyRuby puts
Hello via TinyRuby FFI


Yep, thats using FFI from ruby 1.9 to call TinyRB and having it eval some code - including some FFI code of its own.

1 comment:

jmettraux said...

Thanks for all the work on Ruby FFI ! It opens up a lot of possibilities. This tinyrb example is great, it could turned into an sandboxing mechanism...