How can we make OCaml libraries useful outside of the OCaml ecosystem?

It appears the leading FFT implementation is written in OCaml, but it can be used via C bindings. How is the C library generated?
Another option might be https://github.com/xavierleroy/ocamlmpi, and process input passed. Or HTTP, but that is quite a bit of overhead.

The idea is to use OCaml to build a library, but to make it useful to a broader audience. Any suggestions or pointers?

1 Like

If you’re talking about FFTW, isn’t that a case where the Ocaml code is used to -assemble- the C implementation (that’s what I remember from when I looked at it ages ago) ? The actual code that is generated, is C code, IIRC.

Also: there’s Js_of_ocaml and Bucklescript, right? Those allow Ocaml to be used from other language runtimes. But if what you mean is “how to use Ocaml code compiled and running in the standard Ocaml runtime,” then … that’s really, really hard. The MSFT CLR was all about this. IIRC somebody did an Ocaml->CLR backend 15yr ago or so?

Unless you actually -share- runtimes (and GC heaps), it’s -painful- to glue together languages. Sure, it can be done (that’s what FFIs are about, at some level) but they’re never straightforward, and there are always compromises and gotchas.

The ctypes bindings generator is relatively straightforward to use. The worst part, that has nothing to do with ctypes is structured data.

I made https://github.com/vyos/libvyosconfig/ (which is bindings for https://github.com/vyos/vyos1x-config) specifically to be able to use that OCaml code from Python. Since the C ABI is merely a medium there, I ended up passing some things as JSON strings and decoding them on the other end.

If you are to make it usable from C, you need to drop much lower, and use more impedance matching on the other end.

It’s possible (albeit a bit obscure) to create a .so file containing OCaml code which is callable via C. We do it here: https://github.com/libguestfs/nbdkit/tree/master/plugins/ocaml

I’m not totally convinced that you could have more than one such .so file linked / dlopened by the same main program, especially if they were built with differing versions of OCaml (and therefore would have conflicting runtimes), but TBH I didn’t need to do that or try it.

Also a bit more automation would help. This is possible in OCaml, but it’s easy from Rust or Golang.

2 Likes