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

Serge Sivkov ssp.mryau at gmail.com
Thu May 4 18:50:23 BST 2017


Hello,

I'm write program which uses C library with main event loop. So, I call
init function of this library from ocaml code, register callback and call
main loop of this library. After that monent, ocaml code will be called
only from this library.

Here is some relevant lines of code:

let bus_handler = ptr void @-> size_t @-> ptr (ptr void) @-> ptr size_t @->
returning int

type handlers
let handlers: handlers structure typ = structure "handlers_t"

let topic_name = field handlers "topic_name" string
let topic_handler = field handlers "topic_handler" (funptr
~thread_registration:true bus_handler)
let topic_type = field handlers "topic_type" int
let () = seal handlers

let bus_init = foreign "bus_init" (int @-> ptr (ptr void) @-> returning int)
let loop = foreign "loop" (ptr void @-> returning int)
let register_server = foreign "register_server" (ptr void @-> string @->
ptr handlers @-> size_t @-> returning int)

let floop fhandler name () =
        let handler = make handlers in
        let () = (
                setf handler topic_name name;
                setf handler topic_handler fhandler;
                setf handler topic_type 0
        ) in
        let () = (
                (* Gc.compact (); #1 *)
                let r = bus_init 1 bus_ptr in
                Printf.printf "bus_init: %d\n" r
        ) in
        let r1 = register_server (!@ bus_ptr) name (addr handler) (of_int
1) in
        (* let () = Gc.compact () in #2 *)
        loop (!@ bus_ptr)

In case I comment out both calls to Gc.compact I see

Cannot find handler (Resource temporarily unavailable)
Cannot get address handler item (Resource temporarily unavailable)

after 100-200 test calls on x86 and I get CallToExpiredClosure on ARM just
on the first test call.
In case I uncomment #1 or #2 code line with Gc.compact call I got same
error (Cannot find handler ...) on first test call on x86 too. I've added

        let addr1 = Root.create fhandler in
        let addr2 = Root.create handler in

to begin of floop function but nothing changed on program behaviour under
tests.
How can I protect struct handler and fhandler function pointer from garbage
collection?

WBR, ssp
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.ocaml.org/pipermail/ctypes/attachments/20170504/8ca7f899/attachment.html>


More information about the Ctypes mailing list