Crystal FFI to C library: who owns a Crystal object pointer retained by C?
0 reputation · 31 Jul 2023, 21:25 UTC
Goal
Pass a reference to a Crystal object into a C library callback so the C side can retain and later invoke it, while the Crystal process uses the default Boehm conservative garbage collector.
Constraint
The Boehm GC does not automatically treat pointers stored in C memory as roots, and Crystal's FFI documentation does not clearly specify a supported API for pinning a Crystal object or registering it as a root for external C code. This assumes Crystal 1.x on Linux; behavior on other platforms needs confirmation.
Question
Does Crystal's Boehm GC scan C-allocated memory for references to Crystal heap objects? Is there a supported FFI mechanism to prevent premature collection of a Crystal object retained by C? Should the C layer copy data instead of retaining a Crystal pointer?