Version française
Home     About     Download     Resources     Contact us    
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: -- (:)
From: Florent Monnier <fmonnier@l...>
Subject: callbacks from C to Caml
Hi,

I'm trying to compile the simple exemple given here:
http://caml.inria.fr/pub/docs/manual-ocaml/manual032.html#htoc235
with the compilation instructions given there:
http://caml.inria.fr/pub/docs/manual-ocaml/manual032.html#htoc238
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 test.ml 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  test.ml
% 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 test.ml

let f n =
  print_string "f is applied to ";
  print_int n;
  print_newline();

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)
{
    call_caml_f(2);
    call_caml_f(5);

    return 0;
}