Cheap ForeignPtr allocation
simonmar at microsoft.com
Tue Sep 3 05:02:28 EDT 2002
> I vaguely remeber that in the context of the withForeignPtr
> discussion we where once trying to achieve some similar
> effect (but couldn't come up with something that would
> work). Do you remember?
Uh, my memory's a bit vague too :-)
For a long time we were trying to get cheap allocation/freeing for
temporary storage, i.e. a cheap alloca. We managed to achieve that when
I realised I could pull a trick with GHC's garbage collector and have
"pinned" objects as long as they don't contain any pointers into the
heap. So instead of using malloc()/free() for alloca, we allocate a
pinned ByteArray# and let the GC free it. (it needs to be pinned so
that it can be passed to foreign functions which might re-enter the RTS
and trigger GC, etc.)
This proposed extension to ForeignPtr is just taking the idea one step
further: we can use the same trick for ForeignPtrs too, at least in the
common case where you want the finalizer to free() the object again.
> Does this, then, effectively solve
> this old problem? Wouldn't you want newXXX and withXXX
> variants of the above, too?
The two functions I mentioned are all that's needed:
mallocForeignPtr :: Storable a => IO (ForeignPtr a)
mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
they both do the job of a combined malloc/newForeignPtr. withForeignPtr
still works fine with a ForeignPtr constructed this way.
More information about the FFI