A simple Ruby 1.9 demo C extension with a callback.
Extracted from ongoing efforts to write a Ruby interface to Apache ZooKeeper (github link soon).
There are three demos here, two using straight C extensions and one using ruby-ffi.
The C ext variations are working properly. The ruby-ffi variation works, but doesn’t use FFI fully…and I’ve temporarily broken the build for use under JRuby.
MRI + ruby-ffi is the environment I am most interested in, but the other examples might also be useful as sample code, as this area seems somewhat thinly documented. (Bug/bad style reports welcome!)
Create a localized Makefile, build the C lib, then run the Ruby code
ruby1.9 extconf.rb make ruby1.9 runcallme.rb
Install ruby-ffi from Mercurial repo (0.4.0, presently not released/rubygem’ed)
hg clone http://kenai.com/hg/ruby-ffi~mercurial cd ruby-ffi~mercurial rake1.9 gem gem1.9 install pkg/ffi-0.4.0.gem
(On OSX, add “#include <pthread.h>” to ext/ffi_c/Invoker.c before creating the gem)
Create a localized Makefile, build the C lib, then run the Ruby code
ruby1.9 extconf.rb make ruby1.9 runcallme.rb
To run under JRuby (you might need to make with MODEL=64 to build 64bit libs)
jruby runcallme.rb
(This is the unfinished part – FFI shouldn’t require this extconf stuff…and JRuby won’t even run presently due to the inappropriate build…WIP)
This started out as an attempt to make Apache ZooKeeper play with Ruby, via FFI. Everything was going well until I tried the asynchronous functions with callbacks. Sometimes the ruby code would appear to hang, sometimes the interpreter would crash.
I backed up a bit and wrote some sample code, still using FFI but not trying to talk to ZooKeeper. Same problems. This code is the FFI_lib version in this repo.
Then I decided to go straight to a C ext to see if I was using FFI incorrectly. This code is the C_ext version in this repo.