Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
callbacks from C to Caml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2006-01-31 (10:59)
From: Florent Monnier <fmonnier@l...>
Subject: callbacks from C to Caml

I'm trying to compile the simple exemple given here:
with the compilation instructions given there:
which are:
ocamlopt -output-obj -o camlcode.o unix.cmxa other .cmx and .cmxa files
cc -o myprog C objects and libraries \
        camlcode.o -L/usr/local/lib/ocaml -lunix -lasmrun

I have copy-past the OCaml code in and the C code in main.c
I use a standard GNU/Linux box [Mandriva 2006], with gcc 4.0.1
and OCaml 3.09.0

First I got errors like this:
undefined reference to `sqrt'
so I added -lm to gcc

Then those kind of errors:
undefined reference to `dlopen'
adding -ldl seems to be the solution.

Then new errors like this:
error: caml/mlvalues.h: No such file or directory
it seems that adding this fixes: -I'/usr/local/lib/ocaml'

Then the compilation is made with this:

% ocamlopt -c
% ocamlopt -output-obj -o camlcode.o  unix.cmxa  test.cmx
% gcc main.c  -o myprog.opt  camlcode.o \
        -I'/usr/local/lib/ocaml' \
        -L/usr/local/lib/ocaml \
        -lunix -lasmrun  -lm -ldl

Now the compilation is made without any error messages, but:

% ./myprog.opt
Segmentation Error

What is wrong?
Where is the error?
What should I change/correct?

Thanks in advance
% cat

let f n =
  print_string "f is applied to ";
  print_int n;

let _ =
  Callback.register "test function" f;

% cat main.c
#include <stdio.h>
#include <stdlib.h>
#include <caml/mlvalues.h>
#include <caml/callback.h>

void call_caml_f(int arg)
    static value * closure_f = NULL;
    if (closure_f == NULL) {
        /* First time around, look up by name */
        closure_f = caml_named_value("test function");
    caml_callback(*closure_f, Val_int(arg));

int main(void)

    return 0;