Friday, August 29, 2008

FFI callback hotness

I just finished implementing FFI callbacks for JRuby, and it has some slick syntax:

module LibC
extend FFI::Library
callback :qsort_cmp, [ :pointer, :pointer ], :int
attach_function :qsort, [ :pointer, :int, :int, :qsort_cmp ], :int
end

p = MemoryPointer.new(:int, 2)
p.put_array_of_int32(0, [ 1 , 2 ])

cmp = proc do |p1, p2|
i1 = p1.get_int32(0)
i2 = p2.get_int32(0)
i1 < i2 ? -1 : i1 > i2 ? 1 : 0
end
LibC.qsort(p, 2, 4, cmp)

Functions that take a callback as the last argument are able to automatically use a block if it is present instead of passing a proc, so qsort can be called like this:

LibC.qsort(p, 2, 4) do |p1, p2|
i1 = p1.get_int32(0)
i2 = p2.get_int32(0)
i1 < i2 ? -1 : i1 > i2 ? 1 : 0
end

1 comment:

Roger Pack said...

Oh wow that is wildly cool