Introduction

⊕ This document is available as a pdf here





Conceptual difference between calling and FFI.

Theorem : There are tasks such that there are languages such that there are people who prefer said language for said task.

: There are tasks such that there are languages such that there are people who prefer said language for said task. Proof : left as an exercise for the reader.

: left as an exercise for the reader. Problem: how to interface separate pieces of code at low cost?

Here come FFIs, or how to compile pieces of code from different languages so that you don’t have to rely on forking, subprocesses, JSON / MessagePack / Cap'n Proto , etc.

One language will declare the availability of some functionality to the external world, another will declare its use of some external functionality, both will be compiled together and the resulting binary will not distinguish who’s who and just run fast. Some manual fiddling may be required to get the memory representation to match, but often it’s just a question of shifting by a few bytes one way or another.

In the present document we focus on interfacing OCaml [1], Rust [2] and C [3] but more languages support this out of the box [4–6]. More specifically, we’ll see how we can make OCaml functions available to either C or Rust , in two different ways.

Disclaimer: this has only been tested on GNU/Linux, with

OCaml >= 4.06 dune >= 1.0

Rust 1.25.0 to 1.29.1

gcc 8.1

We hope it generalizes!