Blog Post: Simple Example where Ocaml calls a C function

While there a great deal of techniques and ressources that help to connect Ocaml with C, I had hard time to find a very simple example that shows how you can call a C function from Ocaml.

Read the rest on Simple Example where Ocaml calls a C function

PS. I would like to create a follow up post that shows how to call a C function that is part of C library. Help greatly appreciated

4 Likes

Looks good! It is always useful to have these kinds of simple examples available.

Just a tiny comment: the CAMLprim macro is something used in the compiler codebase, but does not actually do anything for user code (even if some people like to keep it anyway as a kind of reminder that the function is exposed as an OCaml primitive).

Cheers,
Nicolas

1 Like

My favourite example at the moment is this one from Retrofitting Effect Handlers onto OCaml. It shows OCaml calling C, C calling an OCaml callback and exceptions crossing those boundaries.

$ cat meander.ml
external ocaml_to_c
         : unit -> int = "ocaml_to_c"
exception E1
exception E2
let c_to_ocaml () = raise E1
let _ = Callback.register
          "c_to_ocaml" c_to_ocaml
let omain () =
  try (* h1 *)
    try (* h2 *) ocaml_to_c ()
    with E2 -> 0
  with E1 -> 42
let _ = assert (omain () = 42)
#include <caml/mlvalues.h>
#include <caml/callback.h>

value ocaml_to_c (value unit) {
    caml_callback(*caml_named_value
                  ("c_to_ocaml"), Val_unit);
    return Val_int(0);
}

Compile it with OCaml 5.2:

$ ocamlopt --version
5.2.0
$ ocamlopt meander_c.c meander.ml -o meander.exe
$ ./meander.exe
$ echo $?
0

Bonus you can use GDB/LLDB on this to set breakpoints in both OCaml and C.

3 Likes

Thanks for your comment and suggestion, I updated an improved version withouth CAMLPrim, and also mentioned your comment (hope that this is OK):

Basic Ocaml ffi with c library (update)

2 Likes

Thanks for your comment. I put in on my TODO list to things to study …