How to call C functions from OCaml code

I am writing a OCaml program but want to call some C functions provided in some source code or library.

How to achieve this? Is there any good tutorials on this?

A very good tutorial that is easy to follow and understand: How to wrap C functions to OCaml.

A comprehensive reference manual: Chapter 19 Interfacing C with OCaml.

One example that calls a system call from OCaml: Calling Unix libraries from OCaml.


If you are trying to call some Unix/Linux APIs, you may also check the Unix Module which provides the interface to the Unix system.

An example is as follows.

UseUnix.ml:

open Unix;;

print_string "My pid: ";;
print_int (getpid ());;
print_newline ();;
print_newline ();;

print_string "ls / -l";;
print_newline ();;
system "ls / -l";;

To run it:

ocaml unix.cma UseUnix.ml
Leave a Reply

Your email address will not be published. Required fields are marked *