2013/12/25 Estevo euccastro@gmail.com
Is it that.. you find it tricky to get in place a particular sequence of C
FFI structure release function invocation on their GC???
It's not tricky if you know what you're doing. But if you are going to publish a library that exposes C bindings, you really don't want to have to be warning people against holding weak references to these foreign objects, lest they get a segfault or memory corruption.
I have never been aware of anything like that. Can you provide a proof of concept example code that shows how weak references to a FFI object would be inconsistent?
I guess the inconsistencies possible would be that the FFI object would not GC so you run out of heap, or that the weak reference would drop too early - do you see any other type of inconsistency that would need to be evaluated?
Something along the lines that if you have a C structure A that contains in
it a reference to another C structure B, and you want Gambit's GC to automatically take care of this relationship in the sense that it will not release B before A??
Yes, with the nuance that the C structure B is contained in A, not just referenced from it. So it doesn't make sense to free B at all. Another use case is that A is a union and B is another pointer to A's data. You want to free A only once.
But yes, the main point is that you want A to stick around while you have a reference to B. This kind of sanity you take for granted in the Scheme world, thanks to garbage collection. What I want is to be able to treat C objects similarly, without having to do unnecessary copies.
Aha.
You can implement this kind of behavior in Gambit (i.e. B is referenced to by or actually contained in A so you want freeing of B to be conditioned to the freeing of A happening before) yourself, for instance by
1) ensuring you have a reference to B in some vector or alike, one that guaranteedly will stick around until A is freed. Also, you could
2) use the "refcount" facility that Gambit exports to the C world, to keep B's refcount +1 as long as A refers to it, and then have A's release procedure -1 its refcount on invocation.
These would both be solid abstractions.
What practical task are you solving?
Perhaps in the module you're writing you don't expose the C defines to your users anyhow, so for instance using declare not collect-dead-variables or what its name is, would make 1) work out well. Anyhow I guess 2) is general.
There should be more solutions in the box too - any thoughts from other users?
What are your thoughts now?
Best regards, Mikael