[ocaml-ctypes] Static function callback.

Jeremy Yallop yallop at gmail.com
Wed Feb 1 15:22:05 GMT 2017


On 31 January 2017 at 22:31, Romain Beauxis <romain.beauxis at gmail.com> wrote:
> I am playing with a binding for OSX's SecureTransport API. The API
> abstracts away the underlying socket implementation and, thus,
> requires to pass (static) callbacks, which is where I am having
> trouble..
>
> Here are the relevant part of the code:
>
> let fd_read = (...)
>
> let fd_write = (...)
>
> let _set_io_funcs = foreign ~from:lib "SSLSetIOFuncs"
>   (ptr void @-> fd_io_typ @-> fd_io_typ @-> returning int)

Assuming that fd_io_typ is defined something like this

   let fd_io_typ =
     funptr (connection_ref @-> ptr void @-> ptr size_t @-> returning
oss_status)

and that fd_read and fd_write are actually top-level (i.e. "static")
functions then you shouldn't need to do anything special.  Top-level
functions stay alive for the duration of the program, so there's no
danger of their being prematurely collected.

>   let read = Root.create fd_read in

I'm not sure that the Root module is really what you need here.  Root
is useful for passing pointers to OCaml values to C when the OCaml
part of the program doesn't keep a reference to the values.  But in
this case the OCaml program should always have a reference to fd_read
and fd_write.  So I suspect the problem may lie elsewhere.

> I've tried my best to make sure that the passed callback would be
> immune to Gc issues. Unfortunately, I am still experiencing issues
> with them which, I think, relate to the Gc messing with those.

> Besides using C stubs (which I am trying to avoid as an exercise
> here), is there anything else that I could do to make this work?

One useful trick for tracking down GC issues is to add calls to
Gc.compact to your program, so that objects that are collected too
early are collected even earlier.


More information about the Ctypes mailing list