This repository shows how to use ocaml-ctypes to turn OCaml code into a shared library that can be used from C. In keeping with the general philosophy of ocaml-ctypes, this involves writing no C code at all. The example here exposes a simple interface to the XML parsing functionality in the OCaml library Xmlm.
There are two main files involved in building the library:
-
bindings.ml
uses ocaml-ctypes to define a C-compatible interface to Xmlm. The central component in the interface is a structure type that holds callbacks for each event that might occur during XML parsing. On the C side these callbacks are function pointers; on the OCaml side they appear as regular OCaml functions. In addition to the struct definition, theBindings
module exposes a single function to C, for parsing XML from a file. -
generate.ml
is an OCaml program that generates C source and header files from the definitions in theBindings
module, and an OCaml module that can be used to link the generated code with the code inBindings
. (Seeapply_bindings.ml
for the actual linking.)
The prerequisites for building the library are OCaml 4.02.2, ocaml-ctypes (0.4.0 or later), Xmlm and ocamlfind. OPAM users can install the prerequisites by issuing the following commands:
opam update
opam switch 4.02.2
eval `opam config env`
opam install ctypes-foreign ctypes xmlm
When you type make
the following things will happen:
- The stub generator executable will be built from
bindings.ml
andgenerate.ml
. - The stub generator will be run to produce a C header
xmlm.h
, a C source filexmlm.c
, and an OCaml modulexmlm_bindings.ml
. - The shared library will be built from the freshly-generated
xmlm.c
andxmlm_bindings.ml
, together withbindings.ml
andapply_bindings.ml
.
Typing make test
causes the following additional steps to take place: