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.mluses 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, the
Bindingsmodule exposes a single function to C, for parsing XML from a file.
generate.mlis an OCaml program that generates C source and header files from the definitions in the
Bindingsmodule, and an OCaml module that can be used to link the generated code with the code in
apply_bindings.mlfor the actual linking.)
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
- The stub generator will be run to produce a C header
xmlm.h, a C source file
xmlm.c, and an OCaml module
- The shared library will be built from the freshly-generated
xmlm_bindings.ml, together with
make test causes the following additional steps to take place:
- A test program, written in C, will be built by compiling test.c and linking it with the shared library.
- The test program will be run on the sample XML file ocaml.svg