Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement interop between OCaml and C++?

Tags:

c++

interop

ocaml

I want to create a bridge between OCaml and C++. For instance I want to use some constructions written in OCaml in C++.

How can I achieve this? Are there any libraries, bindings for this?

like image 320
MainstreamDeveloper00 Avatar asked Mar 03 '13 13:03

MainstreamDeveloper00


2 Answers

You should read the relevant part of the language manual: Interfacing C with OCaml. It is quite detailed even if, by nature, painfully low-level.

If you don't need tight communication between C++ and OCaml code (eg. you interface GUI code and computation code, but the computationally intensive kernel of your application does not cross application boundaries, or at least the cost of communication is expected to be neglectible compared to time spent on either side), I would recommend that you explore simpler ways, where C++ and OCaml code run in separate processes, and exchange information through message passing (in whatever format that is most convenient to define: text, s-expressions, binary format, JSON, etc.). I would only try to bridge code in the same process if I'm sure the simpler approach cannot work.

Edit: since I wrote this answer last year, the Ctypes library emerged, from Jeremy Yallop; it is a very promising approach that may be significantly simpler than directly interfacing C with OCaml.

like image 111
gasche Avatar answered Nov 11 '22 05:11

gasche


The easiest way to do this is in two steps: OCaml → C and then C → C++ using the extern keyword. I do this extensively in my COH*ML project which binds OCaml with the Coherence library in C++. For example in OCaml I have:

type coh_ptr  (* Pointer to a Cohml C++ object *)
external coh_getcache: string -> coh_ptr = "caml_coh_getcache"

Then in C++, first a C function:

extern "C" {
  value caml_coh_getcache(value cn) {
    CAMLparam1(cn);
    char* cache_name = String_val(cn);
    Cohml* c;
    try {
      c = new Cohml(cache_name);
    } catch (Exception::View ce) {
      raise_caml_exception(ce);
    }
    value v = caml_alloc_custom(&coh_custom_ops, sizeof(Cohml*), 0, 1);
    Cohml_val(v) = c;
    CAMLreturn(v);
  }
}

And finally the C++ implementation:

Cohml::Cohml(char* cn) {
  String::View vsCacheName = cn;
  hCache = CacheFactory::getCache(vsCacheName);
}

Going the other way is basically the same principle.

like image 22
Gaius Avatar answered Nov 11 '22 06:11

Gaius