Addr# field in ForeignPtr

Roman Leshchinskiy rl at
Wed Jun 1 09:29:33 CEST 2011

Hi all,

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:

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.

Alternatively, I could define my own version of ForeignPtr if only ForeignPtrContents was exported (abstractedly would be enough).


More information about the Glasgow-haskell-users mailing list