Linking and Introspection for OCaml Library

I want to write an OCaml library that will be used by other programming languages ​​such as C or even python.

I'm not sure if this is even possible, and I think I need to reset some type safety and add execution checks to the interface for a dynamically typed language.

Is this doable? Are there any tools to achieve this goal for automatic binding generation? I think things like Korba do not fit well with ocaml ABI, but I could be wrong.

EDIT: By dropping the execution request and using only llvm languages, I could use llvm as a normal ABI, I think, but it seems complicated.

+4
source share
2 answers

OCaml has FFI for interacting with C code . The binding code must be written in C, not in OCaml (which does not have a direct representation of C values, but C has representations of OCaml values). My advice:

  • On the C side, decide what the best export interface will be for C programmers (or Python programmers writing Python bindings starting from your C interface)
  • Define a "low level" on the OCaml side that gets the OCaml value as close as possible to the C view
  • Write some C wrappers to convert from this low-level OCaml view to your optimal C view

The reason for step (2) is to make step (3) as small as possible. Manipulating OCaml values ​​from the C side is a bit painful, in particular, you run the risk of mistakenly interacting with the garbage collector, which means segfaults - plus you don't get any type security. So, the less work you have to do on the C side, the better.

There are several projects that can help you do some of these jobs. CamlIDL , and I think Swig has some OCaml support. I never used them, so I can not comment.

If you know which high-level language you want to convert your interface to, there may be a specialized bridge that does not require a C-step. For example, there are libraries for interacting directly with Python views (Pycaml search, not sure how they were tested) or with the Java runtime ( OCamlJava ). The C interface is still a safe bet that will allow other people to create bridges in their languages.

+9
source

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

You must be careful with types in the stub code, but otherwise you can keep type safe.

+1
source

Source: https://habr.com/ru/post/1442298/


All Articles