yallop / ocaml-ctypes

Library for binding to C libraries using pure OCaml
MIT License
363 stars 95 forks source link

Usage from C #768

Closed NicolasT closed 3 months ago

NicolasT commented 3 months ago

Consider the following:

type t = unit ptr
let t : t typ = ptr void

let cb (t : t) = ()

Type t represents a struct t * defined in some C library. In this C code, I somehow get a reference to cb, and have a struct t *t available. Now I want to caml_callback this cb closure, passing in t (the C pointer). Is this possible?

When declaring a stub for a function which takes a t, the generated C code contains void *x2 = CTYPES_ADDR_OF_FATPTR(x1), so it appears in the C code doing the caml_callback I somehow need to wrap my struct t pointer in a "fat pointer" (a record with 3 fields). However, where CTYPES_FROM_PTR and CTYPES_TO_PTR exist, there seems to be no equivalent for these "fat pointers".

Am I overlooking something? Or should I somehow not use unit ptr and instead try something using Ctypes_ptr.voidp?

yallop commented 3 months ago

Now I want to caml_callback this cb closure, passing in t (the C pointer). Is this possible?

It's probably easier to call cb through a C function pointer. There are some examples in the test-funptrs and test-higher_order test suites:

https://github.com/yallop/ocaml-ctypes/tree/master/tests/test-funptrs https://github.com/yallop/ocaml-ctypes/tree/master/tests/test-higher_order