Author: Christian.Queinnec@lip6.fr

## Introduction

Developing programs in a given language very often requires one to integrate libraries written in other languages. The two main reasons for this are:

- to use libraries that cannot be written in the language, thus extending its functionality;
- to use high-performance libraries already implemented in another language.

A program then becomes an assembly of software components written in various languages, where each component has been written in the language most appropriate for the part of the problem it addresses. Those software components interoperate by exchanging values and requesting computations.
The Objective CAML language offers such a mechanism for interoperability with the C language. This mechanism allows Objective CAML code to call C functions with Caml-provided arguments, and to get back the result of the computation in Objective CAML. The converse is also possible: a C program can trigger an Objective CAML computation, then work on its result.
The choice of C as interoperability language is justified by the following reasons:

- it is a standardized language (ISO C);
- C is a popular implementation language for operating systems (Unix, Windows, MacOS, etc.);
- a great many libraries are written in C;
- most programming languages offer a C interface, thus it is possible to interface Objective CAML with these languages by going through C.

The C language can therefore be viewed as the esperanto of programming languages.
Cooperation between C and Objective CAML raises a number of difficulties that we review below.

- Machine representation of data
  For instance, values of base types (int, char, float) have different machine representations in the two languages. This requires conversion between the representations, in both directions. The same holds for data structures such as records, sum types1, or arrays.
- The Objective CAML garbage collector
  Standard C does not provide garbage collection. (However, garbage collectors are easily written in C.) Moreover, calling a C function from Objective CAML must not modify the memory in ways incompatible with the Objective CAML GC.
- Aborted computations
  Standard C does not support exceptions, and provides different mechanisms for aborting computations. This complicates Objective CAML's exception handling.
- Sharing common resources
  For instance, files and other input-output devices are shared between Objective CAML and C, but each language maintains its own input-output buffers. This may violate the proper sequencing of input-output operations in mixed programs.

Programs written in Objective CAML benefit from the safety of static typing and automatic memory management. This safety must not be compromised by improper use of C libraries and interfacing with other languages through C. The programmer must therefore adhere to rather strict rules to ensure that both languages coexist peacefully.