A modular foreign function interface
Science of Computer Programming
Foreign function interfaces (FFIs) between high-level languages and system libraries typically intertwine the actions of describing the interface of a system library and selecting a binding strategy for linking to it. This tight coupling makes it difficult for programmers to switch between different binding strategies, and discourages the development of new approaches to binding, since more exotic approaches are unlikely to attract sufficient users to justify the cost of development. We present
... Cmeleon, a replacement for the standard OCaml FFI that exposes typed constructors that correspond to the operations of the type algebra of C, and binding strategies that interpret this type structure as separate program stages. Cmeleon parameterises external calls across binding strategies, isolating interface descriptions from choices relating to call construction (code generation vs dynamic call frames), concurrency style (blocking, cooperatively or preemptively threaded), and separation (in-process, address space or a network connection). This flexibility enables significant code reuse of bindings in many different contexts, from rapid interactive development in a REPL to production deployments with generated code and privilege separation. Cmeleon has been used for the past two years to bind to a broad variety of real-world OCaml libraries, and entirely supplants the need for the low-level C FFI for the vast majority of applications.