[project @ 2002-05-10 08:38:53 by simonmar]
[ghc-base.git] / Foreign / ForeignPtr.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module      :  Foreign.ForeignPtr
5 -- Copyright   :  (c) The University of Glasgow 2001
6 -- License     :  BSD-style (see the file libraries/base/LICENSE)
7 -- 
8 -- Maintainer  :  ffi@haskell.org
9 -- Stability   :  provisional
10 -- Portability :  portable
11 --
12 -- The 'ForeignPtr' type and operations.  This module is part of the
13 -- Foreign Function Interface (FFI) and will usually be imported via
14 -- the "Foreign" module.
15 --
16 -----------------------------------------------------------------------------
17
18 module Foreign.ForeignPtr
19         ( 
20         -- * Finalised data pointers
21           ForeignPtr,            -- abstract, instance of: Eq
22         , newForeignPtr          -- :: Ptr a -> IO () -> IO (ForeignPtr a)
23         , addForeignPtrFinalizer -- :: ForeignPtr a -> IO () -> IO ()
24         , withForeignPtr         -- :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
25         , foreignPtrToPtr        -- :: ForeignPtr a -> Ptr a
26         , touchForeignPtr        -- :: ForeignPtr a -> IO ()
27         , castForeignPtr         -- :: ForeignPtr a -> ForeignPtr b
28         ) 
29         where
30
31 import Foreign.Ptr
32 import Data.Dynamic
33
34 #ifdef __GLASGOW_HASKELL__
35 import GHC.Base
36 import GHC.IOBase
37 import GHC.Num
38 import GHC.Ptr  ( Ptr(..) )
39 import GHC.Err
40 #endif
41
42 #include "Dynamic.h"
43 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
44
45 #ifdef __GLASGOW_HASKELL__
46 -- |The type 'ForeignPtr' represents references to objects that are
47 -- maintained in a foreign language, i.e., that are not part of the
48 -- data structures usually managed by the Haskell storage manager.
49 -- The essential difference between 'ForeignPtr's and vanilla memory
50 -- references of type @Ptr a@ is that the former may be associated
51 -- with /finalisers/. A finaliser is a routine that is invoked when
52 -- the Haskell storage manager detects that - within the Haskell heap
53 -- and stack - there are no more references left that are pointing to
54 -- the 'ForeignPtr'.  Typically, the finaliser will, then, invoke
55 -- routines in the foreign language that free the resources bound by
56 -- the foreign object.
57 --
58 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'.  The
59 -- type argument of 'ForeignPtr' should normally be an instance of
60 -- class 'Storable'.
61 --
62 data ForeignPtr a = ForeignPtr ForeignObj#
63
64 instance CCallable (ForeignPtr a)
65
66 eqForeignPtr  :: ForeignPtr a -> ForeignPtr a -> Bool
67 eqForeignPtr (ForeignPtr fo1#) (ForeignPtr fo2#) = eqForeignObj# fo1# fo2#
68
69 instance Eq (ForeignPtr a) where 
70     p == q = eqForeignPtr p q
71     p /= q = not (eqForeignPtr p q)
72
73 newForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
74 -- ^Turns a plain memory reference into a foreign object
75 -- by associating a finaliser - given by the monadic operation
76 -- - with the reference.  The finaliser will be executed after
77 -- the last reference to the foreign object is dropped.  Note
78 -- that there is no guarantee on how soon the finaliser is
79 -- executed after the last reference was dropped; this depends
80 -- on the details of the Haskell storage manager. The only
81 -- guarantee is that the finaliser runs before the program
82 -- terminates.
83 newForeignPtr p finalizer
84   = do fObj <- mkForeignPtr p
85        addForeignPtrFinalizer fObj finalizer
86        return fObj
87
88 addForeignPtrFinalizer :: ForeignPtr a -> IO () -> IO ()
89 -- ^This function adds another finaliser to the given
90 -- foreign object.  No guarantees are made on the order in
91 -- which multiple finalisers for a single object are run.
92 addForeignPtrFinalizer (ForeignPtr fo) finalizer = 
93   IO $ \s -> case mkWeak# fo () finalizer s of { (# s1, w #) -> (# s1, () #) }
94
95 mkForeignPtr :: Ptr a -> IO (ForeignPtr a) {- not exported -}
96 mkForeignPtr (Ptr obj) =  IO ( \ s# ->
97     case mkForeignObj# obj s# of
98       (# s1#, fo# #) -> (# s1#,  ForeignPtr fo# #) )
99
100 touchForeignPtr :: ForeignPtr a -> IO ()
101 -- ^This function ensures that the foreign object in
102 -- question is alive at the given place in the sequence of IO
103 -- actions. In particular 'withForeignPtr'
104 -- does a 'touchForeignPtr' after it
105 -- executes the user action.
106 -- 
107 -- This function can be used to express liveness
108 -- dependencies between 'ForeignPtr's: for
109 -- example, if the finalizer for one
110 -- 'ForeignPtr' touches a second
111 -- 'ForeignPtr', then it is ensured that the
112 -- second 'ForeignPtr' will stay alive at
113 -- least as long as the first.  This can be useful when you
114 -- want to manipulate /interior pointers/ to
115 -- a foreign structure: you can use
116 -- 'touchForeignObj' to express the
117 -- requirement that the exterior pointer must not be finalized
118 -- until the interior pointer is no longer referenced.
119 touchForeignPtr (ForeignPtr fo) 
120    = IO $ \s -> case touch# fo s of s -> (# s, () #)
121
122 withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
123 -- ^This is a way to look at the pointer living inside a
124 -- foreign object.  This function takes a function which is
125 -- applied to that pointer. The resulting 'IO' action is then
126 -- executed. The foreign object is kept alive at least during
127 -- the whole action, even if it is not used directly
128 -- inside. Note that it is not safe to return the pointer from
129 -- the action and use it after the action completes. All uses
130 -- of the pointer should be inside the
131 -- 'withForeignPtr' bracket.  The reason for
132 -- this unsafety is the same as for
133 -- 'foreignPtrToPtr' below: the finalizer
134 -- may run earlier than expected, because the compiler can only
135 -- track usage of the 'ForeignPtr' object, not
136 -- a 'Ptr' object made from it.
137 --
138 -- This function is normally used for marshalling data to
139 -- or from the object pointed to by the
140 -- 'ForeignPtr', using the operations from the
141 -- 'Storable' class.
142 withForeignPtr fo io
143   = do r <- io (foreignPtrToPtr fo)
144        touchForeignPtr fo
145        return r
146
147 foreignPtrToPtr :: ForeignPtr a -> Ptr a
148 -- ^This function extracts the pointer component of a foreign
149 -- pointer.  This is a potentially dangerous operations, as if the
150 -- argument to 'foreignPtrToPtr' is the last usage
151 -- occurence of the given foreign pointer, then its finaliser(s) will
152 -- be run, which potentially invalidates the plain pointer just
153 -- obtained.  Hence, 'touchForeignPtr' must be used
154 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
155 -- has another usage occurrence.
156 --
157 -- To avoid subtle coding errors, hand written marshalling code
158 -- should preferably use 'withForeignPtr' rather
159 -- than combinations of 'foreignPtrToPtr' and
160 -- 'touchForeignPtr'.  However, the later routines
161 -- are occasionally preferred in tool generated marshalling code.
162 foreignPtrToPtr (ForeignPtr fo) = Ptr (foreignObjToAddr# fo)
163
164 castForeignPtr :: ForeignPtr a -> ForeignPtr b
165 -- ^This function casts a 'ForeignPtr'
166 -- parameterised by one type into another type.
167 castForeignPtr (ForeignPtr a) = ForeignPtr a
168 #endif
169