OCaml FFI for interoperability with C

ffi
c
ocaml
compilation

#1

Hello.
I’m trying to link OCaml with unit tests in C and got a problem with registering callback.
When I try to get registered callback from OCaml in C(using caml_named_value()) I get null pointer.
Compiling OCaml with:
ocamlfind ocamlopt -o out.o -package num,core -output-obj -thread -linkpkg $(shell ocamldep -sort $(TEMP_DIR)/*.mli $(TEMP_DIR)/*.ml)
Then linking with C using:
gcc -o ex *.c out.o -Wall -DCAML_NAME_SPACE=caml -lpthread -Iocamlc -where-I.. -I. -Locamlopt -where-lunix -lm -ldl -lbigarray -lthreadsnat -lasmrun -Lopam var num:lib-lnums
If I need to post any other specification (e.g. of my pc, versions) please let me know.


#2

Obvious question: did you check that Callback.register has been executed?


#3

When you compile OCaml code with -output-obj, you are responsible for calling caml_startup to initialize the Caml runtime and execute any initialization code. See Sec 20.7.5 of the manual https://caml.inria.fr/pub/docs/manual-ocaml/intfc.html for more info.


#4

How can I check this?


#5

For example, you find code where Callback.register is called and add printf there.
As @nojb said, this code will probably not beingh executed unless you did caml_startup from the C side.


#6

I did call caml_startup in my main C function and I already added printf to check if it’s being called, but nothing gets printed in stdout. So what am I doing wrong here, any ideas?


#7

(Just a note to make sure you’re flushing stdout before drawing conclusions. I have learned this the hard way. A reasonably nice way to flush stdout is to use the %! specifier:

Printf.printf "This location was reached\n%!"

J)