[Haskell-cafe] Semantics of ForeignPtr Finalizers

Bas van Dijk v.dijk.bas at gmail.com
Sun Jun 19 14:47:57 CEST 2011

On 19 June 2011 14:13, wren ng thornton <wren at freegeek.org> wrote:
> 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.

Right, that was also my thinking when designing the usb library. What
made me doubt this was the implementation of storable vectors:


Note that a storable vector stores both a foreign pointer and a
pointer (presumably so that you don't need to add an offset to the
pointer, inside the foreign pointer, each time you use it):

data Vector a = Vector !(Ptr a) !Int !(ForeignPtr a)

Now, if we follow the above semantics we don't need to call
withForeignPtr when we need to read the memory because the foreign
pointer is referenced by the vector.
However the vector library still calls withForeignPtr. For example:

  basicUnsafeIndexM (Vector p _ fp) i = return
                                      . unsafeInlineIO
                                      $ withForeignPtr fp $ \_ ->
                                        peekElemOff p i

So is the withForeignPtr redundant so that this function can be
rewritten to just:

  basicUnsafeIndexM (Vector p _ _) i = return
                                      . unsafeInlineIO
                                        peekElemOff p i



More information about the Haskell-Cafe mailing list