Array operations and pinning

Simon Marlow simonmar at
Wed Nov 2 07:39:37 EST 2005

On 02 November 2005 11:15, Rene de Visser wrote:

> Where is the documentation on how pinning works in the GHC garbage
> collector (from a GHC users point of view).
> I have copied the following code from array/IO.hs and am thinking
> that it is assuming that the array is pinned? What triggers the
> pinning? 

Actually this code does not assume that any memory is pinned.  It is ok
to pass the underlying ByteArr# directly to C, as long as the C call is
annotated "unsafe", which means that GC cannot happen while the call is

If you want to pass ByteArr# to a "safe" C call, then you have to
allocate the ByteArr# using newPinnedByteArray#.  This is the only way
to get a pinned object in GHC, and the only kind of pinned object that
is supported is a MutByteArr# or ByteArr# (this is to simplify the GC;
it doesn't need to traverse pinned objects because they don't contain
any pointers, all it needs to do is remember that the memory block they
occupy is still alive).

Note that all this is GHC-specific; the right high-level interface to
allocating pinned memory is mallocForeignPtr.

> On a second note.
> Why is the type signiture so constricted. The code below works on any
> IOUArray (which is very usefull, not just on Int Word8). Naturally
> this assumes the particular in memory array layout that GHC uses on a
> particular platform, so would not be compatible (probably) with other
> Haskell compilers.

I think the type is right - it makes it clear that the representation
being written to the file is an array of bytes.  You can use
castIOUArray, although that isn't ideal (it doesn't change the bounds).
We should do something better here.


More information about the Glasgow-haskell-users mailing list