[project @ 2002-12-12 13:32:06 by ross]
[packages/old-time.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 #ifndef __NHC__
30 , mallocForeignPtr -- :: Storable a => IO (ForeignPtr a)
31 , mallocForeignPtrBytes -- :: Int -> IO (ForeignPtr a)
32 #endif
33 )
34 where
35
36 #ifndef __NHC__
37 import Foreign.Ptr
38 import Foreign.Storable
39 import Data.Dynamic
40 #endif
41
42 #ifdef __GLASGOW_HASKELL__
43 import GHC.Base
44 import GHC.IOBase
45 import GHC.Num
46 import GHC.Ptr ( Ptr(..) )
47 import GHC.Err
48 import GHC.Show
49 #endif
50
51 #ifdef __NHC__
52 import NHC.FFI
53 ( ForeignPtr
54 , newForeignPtr
55 , addForeignPtrFinalizer
56 , withForeignPtr
57 , foreignPtrToPtr
58 , touchForeignPtr
59 , castForeignPtr
60 )
61 #endif
62
63 #ifdef __HUGS__
64 import Hugs.ForeignPtr
65 #endif
66
67 #ifndef __NHC__
68 #include "Dynamic.h"
69 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
70 #endif
71
72 #ifdef __GLASGOW_HASKELL__
73 -- |The type 'ForeignPtr' represents references to objects that are
74 -- maintained in a foreign language, i.e., that are not part of the
75 -- data structures usually managed by the Haskell storage manager.
76 -- The essential difference between 'ForeignPtr's and vanilla memory
77 -- references of type @Ptr a@ is that the former may be associated
78 -- with /finalisers/. A finaliser is a routine that is invoked when
79 -- the Haskell storage manager detects that - within the Haskell heap
80 -- and stack - there are no more references left that are pointing to
81 -- the 'ForeignPtr'. Typically, the finaliser will, then, invoke
82 -- routines in the foreign language that free the resources bound by
83 -- the foreign object.
84 --
85 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'. The
86 -- type argument of 'ForeignPtr' should normally be an instance of
87 -- class 'Storable'.
88 --
89 data ForeignPtr a
90 = ForeignPtr ForeignObj#
91 | MallocPtr (MutableByteArray# RealWorld)
92
93 instance Eq (ForeignPtr a) where
94 p == q = foreignPtrToPtr p == foreignPtrToPtr q
95
96 instance Show (ForeignPtr a) where
97 showsPrec p f = showsPrec p (foreignPtrToPtr f)
98
99
100 newForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
101 -- ^Turns a plain memory reference into a foreign object
102 -- by associating a finaliser - given by the monadic operation
103 -- - with the reference. The finaliser will be executed after
104 -- the last reference to the foreign object is dropped. Note
105 -- that there is no guarantee on how soon the finaliser is
106 -- executed after the last reference was dropped; this depends
107 -- on the details of the Haskell storage manager. The only
108 -- guarantee is that the finaliser runs before the program
109 -- terminates.
110 newForeignPtr p finalizer
111 = do fObj <- mkForeignPtr p
112 addForeignPtrFinalizer fObj finalizer
113 return fObj
114
115 -- | allocates some memory and returns a ForeignPtr to it. The memory
116 -- will be released automatically when the ForeignPtr is discarded.
117 --
118 -- @mallocForeignPtr@ is equivalent to
119 --
120 -- > do { p <- malloc; newForeignPtr p free }
121 --
122 -- although it may be implemented differently internally. You may not
123 -- assume that the memory returned by 'mallocForeignPtr' has been
124 -- allocated with C's @malloc()@.
125
126 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
127 mallocForeignPtr = doMalloc undefined
128 where doMalloc :: Storable a => a -> IO (ForeignPtr a)
129 doMalloc a = IO $ \s ->
130 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
131 (# s, MallocPtr mbarr# #)
132 }
133 where (I# size) = sizeOf a
134
135 -- | similar to 'mallocForeignPtr', except that the size of the memory required
136 -- is given explicitly as a number of bytes.
137 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
138 mallocForeignPtrBytes (I# size) = IO $ \s ->
139 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
140 (# s, MallocPtr mbarr# #)
141 }
142
143 addForeignPtrFinalizer :: ForeignPtr a -> IO () -> IO ()
144 -- ^This function adds another finaliser to the given
145 -- foreign object. No guarantees are made on the order in
146 -- which multiple finalisers for a single object are run.
147 addForeignPtrFinalizer (ForeignPtr fo) finalizer =
148 IO $ \s -> case mkWeak# fo () finalizer s of { (# s1, w #) -> (# s1, () #) }
149 addForeignPtrFinalizer (MallocPtr fo) finalizer =
150 IO $ \s -> case mkWeak# fo () finalizer s of { (# s1, w #) -> (# s1, () #) }
151
152 mkForeignPtr :: Ptr a -> IO (ForeignPtr a) {- not exported -}
153 mkForeignPtr (Ptr obj) = IO ( \ s# ->
154 case mkForeignObj# obj s# of
155 (# s1#, fo# #) -> (# s1#, ForeignPtr fo# #) )
156
157 touchForeignPtr :: ForeignPtr a -> IO ()
158 -- ^This function ensures that the foreign object in
159 -- question is alive at the given place in the sequence of IO
160 -- actions. In particular 'withForeignPtr'
161 -- does a 'touchForeignPtr' after it
162 -- executes the user action.
163 --
164 -- This function can be used to express liveness
165 -- dependencies between 'ForeignPtr's: for
166 -- example, if the finalizer for one
167 -- 'ForeignPtr' touches a second
168 -- 'ForeignPtr', then it is ensured that the
169 -- second 'ForeignPtr' will stay alive at
170 -- least as long as the first. This can be useful when you
171 -- want to manipulate /interior pointers/ to
172 -- a foreign structure: you can use
173 -- 'touchForeignObj' to express the
174 -- requirement that the exterior pointer must not be finalized
175 -- until the interior pointer is no longer referenced.
176 touchForeignPtr (ForeignPtr fo)
177 = IO $ \s -> case touch# fo s of s -> (# s, () #)
178 touchForeignPtr (MallocPtr fo)
179 = IO $ \s -> case touch# fo s of s -> (# s, () #)
180
181 withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
182 -- ^This is a way to look at the pointer living inside a
183 -- foreign object. This function takes a function which is
184 -- applied to that pointer. The resulting 'IO' action is then
185 -- executed. The foreign object is kept alive at least during
186 -- the whole action, even if it is not used directly
187 -- inside. Note that it is not safe to return the pointer from
188 -- the action and use it after the action completes. All uses
189 -- of the pointer should be inside the
190 -- 'withForeignPtr' bracket. The reason for
191 -- this unsafety is the same as for
192 -- 'foreignPtrToPtr' below: the finalizer
193 -- may run earlier than expected, because the compiler can only
194 -- track usage of the 'ForeignPtr' object, not
195 -- a 'Ptr' object made from it.
196 --
197 -- This function is normally used for marshalling data to
198 -- or from the object pointed to by the
199 -- 'ForeignPtr', using the operations from the
200 -- 'Storable' class.
201 withForeignPtr fo io
202 = do r <- io (foreignPtrToPtr fo)
203 touchForeignPtr fo
204 return r
205
206 foreignPtrToPtr :: ForeignPtr a -> Ptr a
207 -- ^This function extracts the pointer component of a foreign
208 -- pointer. This is a potentially dangerous operations, as if the
209 -- argument to 'foreignPtrToPtr' is the last usage
210 -- occurence of the given foreign pointer, then its finaliser(s) will
211 -- be run, which potentially invalidates the plain pointer just
212 -- obtained. Hence, 'touchForeignPtr' must be used
213 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
214 -- has another usage occurrence.
215 --
216 -- To avoid subtle coding errors, hand written marshalling code
217 -- should preferably use 'withForeignPtr' rather
218 -- than combinations of 'foreignPtrToPtr' and
219 -- 'touchForeignPtr'. However, the later routines
220 -- are occasionally preferred in tool generated marshalling code.
221 foreignPtrToPtr (ForeignPtr fo) = Ptr (foreignObjToAddr# fo)
222 foreignPtrToPtr (MallocPtr fo) = Ptr (byteArrayContents# (unsafeCoerce# fo))
223
224 castForeignPtr :: ForeignPtr a -> ForeignPtr b
225 -- ^This function casts a 'ForeignPtr'
226 -- parameterised by one type into another type.
227 castForeignPtr (ForeignPtr a) = ForeignPtr a
228 castForeignPtr (MallocPtr a) = MallocPtr a
229 #endif
230