Reorganisation of the source tree
[ghc-hetmet.git] / docs / comm / rts-libs / foreignptr.html
1 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
2 <html>
3   <head>
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>
6   </head>
7
8   <body BGCOLOR="FFFFFF">
9
10     <h1>On why we have <tt>ForeignPtr</tt></h1>
11
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
17     the object.
18
19     <p>The <tt>Ptr</tt> type is really just a boxed address - it's
20     defined like
21
22     <pre>
23 data Ptr a = Ptr Addr#
24 </pre>
25
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
29     altogether.
30
31     <p><tt>ForeignPtr</tt> is defined like this
32
33     <pre>
34 data ForeignPtr a = ForeignPtr ForeignObj#
35 </pre>
36
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>!).
42
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>.
47
48     <p>So a nicer interface might be something like
49
50 <pre>
51 class Finalizable a where
52    addFinalizer :: a -> IO () -> IO ()
53
54 instance Finalizable (ForeignPtr a) where ...
55 instance Finalizable (MVar a) where ...
56 </pre>
57
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.
61
62     <p><small>
63 <!-- hhmts start -->
64 Last modified: Wed Sep 26 09:49:37 BST 2001
65 <!-- hhmts end -->
66     </small>
67   </body>
68 </html>