I'm new here and I've tried searching for this but can't seem to find it. I'm writing nim code that interacts with a callback based C library, think functions like:
void do_the_thing(... args ..., void* cb_arg, callback_func_t cb, destroy_func_t cleanup) { ... }
The destroy_func_t callback when used in the C library is basically used to free the heap allocated cb_arg. These functions are async so the passed pointers need to live beyond the function call.
I'd like to use rawEnv and rawProc for this, something like:
proc callCFunc(... args ..., cb: proc()) =
let
arg = cb.rawEnv()
fp = cb.rawProc()
doTheThing(.. args .., arg, fp, ???)
Then have something like:
callCFunc(.. args .., proc() =
...
)
but I don't actually understand how the memory management works out here. Normally I assume the closure would be cleaned up by nim, but I essentially want to leak the closure and clean it up myself. How would I do something like that?
I think you can pass it with a ref then apply GC_ref, so that it's not freed until GC_unref is called.
proc callCFunc(... args ..., cb: ref proc()) =
GC_ref(cb)
let
arg = cb[].rawEnv()
fp = cb[].rawProc()
doTheThing(.. args .., arg, fp, ???)
GC_unref(cb)