How to keep a value live over a C binding?

If a C binding is the last function to use a value, how can we avoid that the value is GC’ed before? Or, in other words, how to keep that value live across the C function call? What does the GC assume about C functions using values?

I read with some worry in this pull request that Sys.opaque_identity cannot be used for it:

Liveness sees through it: Sys.opaque_identity x is not enough to keep x from being GC’d.

1 Like

In the scope of a C function, the liveness of a value should be handled by the use of the Camlparam$n, Camllocal and Camlreturn macros. If the C side of a programs needs to own OCaml values with a longer lifetimes, it needs to register them as a GC roots. For more details, the manual has a section about living in harmony with the GC.

Thank you - this makes sense. We had some problems with this in the past with bindings generated by C types but I see that the GC should have enough information to keep parameters alive.

With ctypes specifically, there was a at some point a gotcha with strings were it was quite easy to forget to transfer ownership from OCaml to C.