Vesa Karvonen wrote:
On Thu, Feb 14, 2008 at 7:00 PM, Joel Stanley jstanley@galois.com wrote:
Is there a finalizer registration mechanism available in Poly/ML that I can use to invoke appropriate tear-down functions in the C library when Poly/ML is done with the wrapped vol? If not, is there a weak pointer mechanism available that would allow me to accomplish the same?
I don't know, but a quick grep over Poly/ML's code base reveals that gc.cpp mentions weak references a number of times.
I looked at this recently as the result of an email from Makarius. Poly/ML has weak references within the run-time system but these aren't available to ML. Internally they are used to recover unreferenced files and also in the C interface library to recover unreferenced C objects. I looked at MLton's weak references and considered doing something like that. In Poly/ML the contents of a weak reference, the token that is used to determine when the value was no longer used elsewhere, would have to be a ref since it requires pointer equality. So "weak" would have a type something like: weak: 'a ref -> 'a ref option ref
It would be used in a situation such as val token = ref 1 val weakRef = weak token Return "token" to the surrounding code.
weakRef contains SOME token until token is no longer reachable except from weakRef. Some point after that the garbage collector would set it to NONE.
while isSome(! weakRef) do wait..; (* weakRef is now NONE. *) Execute tear-down code.
It would require the ability to register functions to be called some time after a garbage collection to check the state of the weak references. An alternative would be for the run-time system to broadcast on a global condition variable after each garbage-collection so waking up any threads that needed to check for weak references that had disappeared. Since the post-GC functions would have to run on a separate thread that might actually simplify things.
Finalisation is also a possibility and could probably be written on top of these.
I do know, however, that MLton (http://mlton.org) supports both finalizers (http://mlton.org/MLtonFinalizable) and weak pointers (http://mlton.org/MLtonWeak). MLton also provides a straightforward low-level FFI (http://mlton.org/ForeignFunctionInterface) and ML-NLFFI (http://mlton.org/MLNLFFI). MLton's library repository (http://mlton.org/cgi-bin/viewsvn.cgi/mltonlib/trunk/) contains a few libraries (e.g. bindings to SQLite, SDL, and Windows API) making use of finalizers and both FFIs.
It would be nice to have a port of ML-NLFFI to Poly/ML, which, I believe, should be doable on top of Poly/ML's existing FFI.
A cursory look at this mentions generating code which could complicate things. The Poly/ML FFI only generates code for callbacks from C to ML. In other situations it effectively interprets the call.
David.