Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bindings and introspection for OCaml library

Tags:

binding

ocaml

idl

I want to write an OCaml library which will be used by other programing languages like C or even python.

I not sure it's even feasible, and i guess i need to drop some type safety and add runtime checks to the interface for dynamically typed language.

Is it doable ? Is there tools to achieve this goal to auto-generate bindings ? I think stuffs like Corba do not fit well with ocaml ABI, but I may be wrong.

EDIT : by dropping the runtime requirement and using only languages having a llvm frontend, I could use llvm as a common ABI I guess, but it seems tricky.

like image 936
Enjolras Avatar asked Dec 27 '22 15:12

Enjolras


2 Answers

OCaml has a FFI to interact with C code. The code for the binding has to be written in C, not in OCaml (which has no direct representation of C values, while C has representations of OCaml values). My advice would be:

  1. On the C side, decide what would be the best interface to export that C programmers would like (or Python programmers writing Python bindings starting from your C interface)
  2. Define a "low-level layer" on the OCaml side that gets your OCaml value as close as possible from the C representation
  3. Write some C wrappers to convert from this low-level OCaml representation to your optimal C representation

The reason for step (2) is to have the step (3) as small as possible. Manipulating OCaml values from the C side is a bit painful, in particular you risk getting the interaction with the Garbage Collector wrong, which means segfaults -- plus you don't get any type safety. So the less work you have to do on the C side, the better.

There are some projects to do some of the wrapping work for you. CamlIDL for example, and I think Swig has some support for OCaml. I have never used those, though, so I can't comment.

If you know to which high-level language you wish to convert your interface to, there may be specialized bridge that don't need a C step. For example there are libraries to interact directly with Python representations (search for Pycaml, not sure how battle-tested their are) or with the Java runtime (the OCamlJava project). A C interface is still a safe bet that will allow other people to create bridges to their own languages.

like image 81
gasche Avatar answered Jan 21 '23 12:01

gasche


It is feasible, but you need to understand involved topics, like how the GC works. Have a look at this: http://caml.inria.fr/pub/docs/manual-ocaml-4.00/manual033.html#toc148

You need to be careful about types in the stub code, but otherwise you can keep type safety.

like image 42
jrouquie Avatar answered Jan 21 '23 11:01

jrouquie