1 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
4 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
5 <title>The GHC Commentary - why we have <tt>ForeignPtr</tt></title>
8 <body BGCOLOR="FFFFFF">
10 <h1>On why we have <tt>ForeignPtr</tt></h1>
12 <p>Unfortunately it isn't possible to add a finalizer to a normal
13 <tt>Ptr a</tt>. We already have a generic finalization mechanism:
14 see the Weak module in package lang. But the only reliable way to
15 use finalizers is to attach one to an atomic heap object - that
16 way the compiler's optimiser can't interfere with the lifetime of
19 <p>The <tt>Ptr</tt> type is really just a boxed address - it's
23 data Ptr a = Ptr Addr#
26 <p>where <tt>Addr#</tt> is an unboxed native address (just a 32-
27 or 64- bit word). Putting a finalizer on a <tt>Ptr</tt> is
28 dangerous, because the compiler's optimiser might remove the box
31 <p><tt>ForeignPtr</tt> is defined like this
34 data ForeignPtr a = ForeignPtr ForeignObj#
37 <p>where <tt>ForeignObj#</tt> is a *boxed* address, it corresponds
38 to a real heap object. The heap object is primitive from the
39 point of view of the compiler - it can't be optimised away. So it
40 works to attach a finalizer to the <tt>ForeignObj#</tt> (but not
41 to the <tt>ForeignPtr</tt>!).
43 <p>There are several primitive objects to which we can attach
44 finalizers: <tt>MVar#</tt>, <tt>MutVar#</tt>, <tt>ByteArray#</tt>,
45 etc. We have special functions for some of these: eg.
46 <tt>MVar.addMVarFinalizer</tt>.
48 <p>So a nicer interface might be something like
51 class Finalizable a where
52 addFinalizer :: a -> IO () -> IO ()
54 instance Finalizable (ForeignPtr a) where ...
55 instance Finalizable (MVar a) where ...
58 <p>So you might ask why we don't just get rid of <tt>Ptr</tt> and
59 rename <tt>ForeignPtr</tt> to <tt>Ptr</tt>. The reason for that
60 is just efficiency, I think.
64 Last modified: Wed Sep 26 09:49:37 BST 2001