Join GitHub today
GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together.Sign up
Obtaining an OCaml closure from C #5415
Original bug ID: 5415
The manual, section 18.7.2, describes a way to obtain an OCaml closure using Callback.register. However, this is not always desirable. Take the example of a C function, say [root], finding a root of a function [f: float -> float]. Passing [f] through Callback.register means that the code will not work when using [root] from different threads. More important even is that [f] cannot call [root] (which is sometimes the case)! Therefore, it would be nice if the manual were saying that an alternative way, as the one described below, is guaranteed to work.
CAMLexport value root(value vf, value x)
P.S. Of course one could create a new string on each call of [root], appending a number to a given prefix. This is both heavy and impractical given the poor C string handling library.
Comment author: @lefessan
You can simplify this code to:
value root(value vf, value x)
I thought it was clear in the manual that caml_callback(...) can be used on functional values received from OCaml, i.e. closures, but maybe adding another example can make things easier to understand.
Comment author: @Chris00
It was not really clear because there is a section "Registering Caml closures for use in C functions" that starts with "The main difficulty with the callback functions described above is obtaining a closure to the Caml function to be called." followed by a description of how to do it — implying that there is no other way.
Comment author: @gasche
Nitpicking: "There are two ways to obtain closures of OCaml functions.", rather than "for obtaining ...".
I also found the manual quite clear. I'm not sure your proposed modification would make it clearer (in section 18.7.2 you describe "two ways", but only the second is actually relevant to the subsection, as the other needs no registration mechanism).
I believe the documentation could be better clarified by simply providing an example in section 18.7.1 (Applying Caml closures from C). Why not the example you suggest -- though I personally find it a bit strange that you export as
Comment author: @Chris00
I have taken your remarks into account in the new version I uploaded. I supposed I put too much emphasis on "The main difficulty..." which was for me casting some doubt (especially for newcomers) whether the simple way of obtaining a closure is officially supported — after all, it implies we do not really need the registration mechanism when the main program is in OCaml.