Receive events from a C library

I have a library which emits events by calling a callback. I want to handle these events within my OCaml code, translating them into React.event if possible. Event callback is being called in a separate pthread. I expect it to call an OCaml callback asynchronously, though it doesn’t work.

I could write a blocking wrapper, but it would block my main OCaml thread and I could not wrap a function calling to OCaml into a Lwt_preemptive.

How to wrap something like this:

void event_source ((void)(*f)(void*)) {
       while (TRUE) {
               ...
               f (data);
      }
}

in OCaml so it could be used within a Lwt scheduled asynchronous program?

1 Like

You may be able to draw inspiration from ocaml-fdb, which tackles a similar challenge wrapping libfdb.

With libfdb, you register callbacks with the library, which are then invoked from a separate thread. Like you, I wanted to integrate with Lwt (and Async). ocaml-fdb uses Ctypes for the bindings, and automatically acquires the runtime lock for the OCaml callback. Lwt_unix.{make_notification,send_notification} (docs) is then used to run a function on the Lwt main thread rather than the libfdb thread. You can find more details in this issue from the Lwt Github repo.

Hope it helps :slight_smile:

4 Likes

That definitely helps, thanks. I recalled another lwt event loop wrapper, the gtk’s glib library. These two examples look sufficient.