[ocaml-ctypes] Passing Caml function to C

Jeremy Yallop yallop at gmail.com
Thu Dec 28 16:44:30 GMT 2017


On 28 December 2017 at 13:05, john skaller <skaller at internode.on.net> wrote:
> There’s some machinery for this but .. well I am suspicious :)
>
> How can this possibly work?
>
> Caml functions are closures,  the only way you could pass
> a closure would be to generate a thunk. I’m suspicious that
> this doesn’t work in general. And you would need to find
> a place to put the thunk which the OS allows you to execute.

Serge Sivkov has explained how things work using OCaml's standard
Callback module.  Ctypes provides a slightly different mechanism.

The interface is the 'funptr' function that builds a typed description
of a C function pointer:

   http://ocamllabs.io/ocaml-ctypes/Foreign.html#VALfunptr

The implementation of funptr uses the closure functions in the libffi
library to dynamically generate function pointers

   http://www.chiark.greenend.org.uk/doc/libffi-dev/html/The-Closure-API.html

There's also a second implementation of funptr in progress that
provides a simpler mechanism for the case where the OCaml function to
be passed to C is known at code-generation time.

Kind regards,

Jeremy


More information about the Ctypes mailing list