Hello. Not sure if this should have gone to beginners or the regular
list. Also not sure if its been answered before. If so, please
redirect me! I did a bunch of searching both on google and in the lists
and couldn't find the answers I needed. So here goes.
I have written a blob of code in Ocaml that I like very much. I'd love
to keep it in ocaml and not have to worry about things like memory leaks
and so on. However, much of what I do is in C and can't be in Ocaml.
So I am investigating packing my nice Ocaml code into a library and
writing C bindings so that I can talk to it.
Virtually all of the tutorials out there and documentation cover how to
create Ocaml bindings to a C library. I don't want to do that. The few
examples I have found that are relevant are toy ones. How to write C
bindings to an Ocaml "fib" function, e.g. In particular, I have found
none that cover how to obtain pointers to OCaml function return values
that are not strings or ints, how to store them in C-land, and how to pass
them back to Ocaml as parameters.
Let's take as a concrete example the following: creating C bindings for
a simple hash table mapping string keys to integer values. If I can
generate bindings for this that work I should be able to do so for the
library I really care about.
Here's what I put together for the hash table slightly-less-than-toy
example. It doesn't even compile. [Oddly, with very similar incantations
my own code does compiles but then segfaults inside one of the Ocaml fns.]
Any help much appreciated!
-Tim
1. The implementation.
% cat ht.ml
type ht = (string,int) Hashtbl.t
let create () : ht = Hashtbl.create 100
let add (table:ht) key valu = Hashtbl.add table key valu
let mem (table:ht) key = Hashtbl.mem table key
let remove (table:ht) key = if (Hashtbl.mem table key) then
Hashtbl.remove table key
let _ = Callback.register "create" create
let _ = Callback.register "add" add
let _ = Callback.register "mem" mem
let _ = Callback.register "remove" remove
2. The wrappers
% cat ht_wrap.c
#include <caml/mlvalues.h>
#include <caml/callback.h>
#include <caml/alloc.h>
void *ht_create (void) {
static value *create_closure = NULL;
if (create_closure == NULL)
create_closure = caml_named_value("create");
return ((void *) (caml_callback(*create_