Developing Ruby extensions with rocaml is easier and more convenient than
writing a plain old C extension because rocaml performs Ruby<->OCaml conversions
for a wide range of types, including abstract types and arrays, tuples,
variants and records of values of any supported type (e.g. arrays of arrays of
variants of tuples of ...). Moreover, exceptions raised in the OCaml code are captured by the generated extension and raised inside Ruby.
Making an extension with rocaml involves two steps:
implementing the desired functionality in Objective Caml, and registering the functions to be exported (using Callback.register : string -> 'a -> unit or the included camlp4 extension)
creating the extconf.rb file (just modify the sample extconf.rb distributed with rocaml) defining the interface of your Objective Caml code.
At no point is there any need to write a single line of C code when using rocaml.
The mandatory trivial example
This example doesn't do justice to the usefulness of rocaml because the extension is beyond trivial and you could as well have written it in C using RubyInline. The advantages of rocaml (and of Objective Caml) usually become visible when the extension takes more than two lines (take a look at the 3-line Marshal replacement that is 3 times faster than Ruby's, though...). Here follows a minimal example however, merely to show how easily rocaml extensions can be made.
Here's the OCaml code placed in fib.ml:
let rec fib n = if n < 2 then 1 else fib (n-1) + fib (n-2)
export fib
Here's the interface declaration in your extconf.rb:
Interface.generate("fib") do
def_module("Fib") do
fun "fib", INT => INT
end
end
That's it. The extension can be built like any run-of-the-mill C extension
with
ruby extconf.rb
make
The resulting Ruby extension that can be used as usual: