[Haskell-cafe] Semantics of ForeignPtr Finalizers

wren ng thornton wren at freegeek.org
Sun Jun 19 14:13:11 CEST 2011


On 6/19/11 3:52 AM, Bas van Dijk wrote:
> Hello,
> I have a question about the semantics of finalizers of ForeignPtrs: If
an in scope value has a reference to a ForeignPtr is the foreign object
always kept alive, even if that reference is not used? Or do I always
need to wrap each computation, which needs to have the foreign object
alive, inside withForeignPtr?

I know that the Ptr obtained by withForeignPtr will _not_ keep the foreign
object alive (though withForeignPtr itself will be sure to keep it alive
until the function using the Ptr exits). For instance, this shows up with
ByteStrings if you try to save the Ptr somewhere and then use it after
withForeignPtr exits.

I believe that ForeignPtr itself does promise to keep the foreign object
alive, since it's what holds the finalizers. The documentation claims that
the finalizers are run only once the ForeignPtr becomes unreachable, which
implies that keeping the ForeignPtr is sufficient to keep the foreign
object alive. I haven't used ForeignPtr for truly foreign objects, only
for pseudo-foreign objects like ByteString, but in my experience just
having the ForeignPtr is enough to keep the target alive.

-- 
Live well,
~wren




More information about the Haskell-Cafe mailing list