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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With