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
Calling OCaml from C - nothing shown on stdout
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Andreas Sommer <AndiDog@w...>
Subject: Calling OCaml from C - nothing shown on stdout
Hi everybody,

I'm trying to call a OCaml function from C code. This is the OCaml file:

    open Printf

    let hello () =
        Printf.fprintf stdout "%s" "test"
    let () =
        let oc = open_out "/tmp/testfile" in
        Printf.fprintf oc "test";
        close_out oc;
        Printf.fprintf stdout "Caml main function\n";
        Callback.register "Hello callback" hello;
        Printf.fprintf stdout "%s" "Finished with OCaml initialization"

and this is the C file:

    #include <stdio.h>
    #include <caml/memory.h>
    #include <caml/mlvalues.h>
    #include <caml/callback.h>

    void helloWrapper()
        static value *closure_f = NULL;

        if(closure_f == NULL)
            closure_f = caml_named_value("Hello callback");
            printf("Closure pointer: %p\n", closure_f);
        caml_callback(*closure_f, Val_unit);

    int main(int argc, char **argv)

        printf("calling wrapper\n");

        return 0;

Everything seems to work: The file "/tmp/testfile" is created correctly
(so the OCaml function did get called), and the C program ends with
"Done.", *but* nothing is printed from the OCaml fprintf functions.

I am linking the executable with

    $(OCAMLOPT) -output-obj -o test_obj.o
    $(CC) -c linkwiththis.c -o linkwiththis.o -I"`$(OCAMLC) -where`"
    $(CC) linkwiththis.o test_obj.o $(NATIVECCLIBS) -lasmrun -o
    camltestprogram -L"`$(OCAMLC) -where`"

What am I doing wrong - how can I make OCaml print to stdout correctly?

Best regards,