Addr# field in ForeignPtr

Simon Marlow marlowsd at gmail.com
Wed Jun 1 12:07:28 CEST 2011


On 01/06/2011 08:29, Roman Leshchinskiy wrote:

> GHC defines ForeignPtr as:
>
> data ForeignPtr a = ForeignPtr Addr# ForeignPtrContents
>          -- we cache the Addr# in the ForeignPtr object, but attach
>          -- the finalizer to the IORef (or the MutableByteArray# in
>          -- the case of a MallocPtr).  The aim of the representation
>          -- is to make withForeignPtr efficient; in fact, withForeignPtr
>          -- should be just as efficient as unpacking a Ptr, and multiple
>          -- withForeignPtrs can share an unpacked ForeignPtr.  Note
>          -- that touchForeignPtr only has to touch the ForeignPtrContents
>          -- object, because that ensures that whatever the finalizer is
>          -- attached to is kept alive.
>
> Is it ok to modify the Addr# field? Or do the libraries assume that
> it always points to the start of the block described by
> ForeignPtrContents? Changing the Addr# field would be quite useful
> for pointing to the middle of a memory block. For instance, Storable
> vectors are currently defined as:

It should be fine to use whatever Addr# you like.  The only requirement 
is that calling touch# on the ForeignPtrContents is enough to keep the 
memory alive.

> data Vector a = Vector {-# UNPACK #-} !(Ptr a)
>                         {-# UNPACK #-} !Int
>                         {-# UNPACK #-} !(ForeignPtr a)
>
> If I could use the Addr# field of the ForeignPtr, I could get rid of the Ptr.

Good idea!

Cheers,
	Simon



More information about the Glasgow-haskell-users mailing list