Thank you Guillaume.
Luca de Alfaro a écrit :
I am trying another approach... it might make more sense for me to embed the
Ocaml into C++.
This is not the way you'll get the most help out of this list. People are more familiar with making C bindings. Making C++ bindings is rather close to it.You need to construct them from C side, and it's more a pain than taking C structs and wrapping them into OCaml.
I have read the instructions, and it seems feasible, except that I have a
few questions:
- All I need to pass, as arguments, are int, float, string, and arrays of
these. Any example of how to deal with the arrays?
The manual describes the structure of OCaml values rather precisely. There are also some pages by Richard Jones on his blog which explain rather nicely the internals of OCaml values. One advice: stick to the macros provided. Do not try to construct manually, say, OCaml strings on the C side. Use caml_copy_string and friends.
- How can I return arrays, in a way that C or C++ understands? How can I
return tuples, i.e., how can I return multiple values from Ocaml to C?
These are documented in the manual and in Richard Jones' blog.
For couples, you can do
value couple = caml_alloc(2, 0);
Store_field(couple, 0, my_ocaml_val);
Store_field(couple, 1, my_other_ocml_val);
For arrays, you'll have seamless integration by using Bigarrays.
- Finally, do I need to worry about the Ocaml garbage collector, if I
call Ocaml from C/C++? Will it run every now and then? How can the garbage
collector know whether a value returned by an Ocaml function is still being
used in C/C++? How can I tell it that it is no longer used?
Essentially, the garbage collector will run potentially each time you allocate an OCaml value. caml_copy_string? the GC may run.
You have to register values being used on the C side as a GC root. It's easier and more documented to do it the other way round by calling C++ from OCaml.No.
The problem I am trying to solve seems to be a can of worms from whichever
angle I take it...
The solution I proposed with Swig is very verbose, but it is a clean solution if you do it manually.
You have Makefile compilation instructions to compile C++ with OCaml (the main issue with C++ and the extern "C" is essentially the name mangling of symbols provided by your C++ object files. All the rest is pretty similar to C. This is really the *main* point).
You have at the end of my last email and example of how to construct an object and feed it back to OCaml. It may not be really clean, it lacks finalisers, but these last two points are stuff that you're going to have to deal with anyway if you're going with the OCaml/C interface. Look up "custom blocks" and finalisation in the OCaml manual section concerning the C interface.
Luca
All the best,