OCaml FFI for interoperability with C



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.


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


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.


How can I check this?


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.


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?


(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%!"