rocaml allows you to write Ruby extensions in Objective Caml.
Developing Ruby extensions with rocaml is easier and more convenient
writing a plain old C extension because rocaml performs Ruby <-> OCaml
conversions for a wide range of types, including abstract types and
tuples, variants and records of values of any supported type (e.g.
arrays of variants of tuples of …).
Moreover, exceptions raised in the OCaml code are captured by the
extension and raised inside Ruby.
Making an extension with rocaml involves two steps:
- implementing the desired functionality in Objective Caml, and
the functions to be exported (using Callback.register : string -> 'a
or the included camlp4 extension)
- creating the extconf.rb file (just modify the sample extconf.rb
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. **
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
RubyInline. The advantages of rocaml (and of Objective Caml) usually
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,
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)
Here’s the interface declaration in your extconf.rb:
fun “fib”, INT => INT
That’s it. The extension can be built like any run-of-the-mill C
The resulting Ruby extension that can be used as usual:
p Fib.fib 10
You can get rocaml at http://eigenclass.org/hiki/rocaml
rocaml is distributed under the same terms as Ruby.
rocaml copyright © 2007 Mauricio F. [email protected]