[ocaml-ctypes] ocaml as callback to C code with event loop

Serge Sivkov ssp.mryau at gmail.com
Fri May 12 10:46:07 BST 2017


Hello,

here is minimal example, which works without any problems on x86 and raises
CallToExpiredClosure on ARM:
https://github.com/mryau/ctypes-mintest

WBR, ssp

2017-05-11 16:37 GMT+05:00 Jeremy Yallop <yallop at gmail.com>:

> On 11 May 2017 at 10:20, Serge Sivkov <ssp.mryau at gmail.com> wrote:
> > thank for your reply, it allow me partially resolve problem: code works
> on
> > x86 without any problems (yet with Gc.compact() calls insert after each
> line
> > of code). But ARM version allways raises CallToExpiredClosure on the
> first
> > call to callback.
> > I've tried next variants to store callback if struct field:
> > - existing toplevel function by name
> > - store function name to toplevel ref and save it to struct field by
> > !ref_name
> > - by register closure to function (fun a b c d -> top_level_function a b
> c
> > d) with Ctypes.Root.create
> > - by store same closure to Hashtbl.
> > - by register finaliser with Gc.finalise for closure (and it has not been
> > called)
> > All this variants work on x86 and do not work on ARM, i.e. first call to
> > OCaml callback from C raises CallToExpiredClosure.
> > It seems I don't understand problem at all.
> >
> > So here is base questions:
> > - in case I store in C struct field existing toplevel function by name,
> may
> > it be GC'ed?
>
> Yes.  The only way to prevent a value from being collected is to
> ensure that it's visible to the GC, which requires keeping a reference
> to it in an OCaml object.  The GC doesn't scan C memory, such as
> struct fields, so storing a function in a struct field won't stop it
> being collected.
>
> > -what may cause CallToExpiredClosure raise too if I has only one
> callback to
> > call and at C side this struct in GDB seems to be correct?
>
> If there's an OCaml reference to the function passed to C then
> CallToExpiredClosure should never occur.  But it has to be exactly the
> same function -- for example, storing a function in a struct field,
> then reading from the struct field will create a new copy of the
> function, which won't prevent the original from being collected.
>
> If you have a (smallish) running example somewhere of the code that's
> causing problems I'd be happy to take a look.
>
> Kind regards,
>
> Jeremy.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.ocaml.org/pipermail/ctypes/attachments/20170512/e842a84c/attachment.html>


More information about the Ctypes mailing list