1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
4 -- Module : Foreign.ForeignPtr
5 -- Copyright : (c) The University of Glasgow 2001
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : ffi@haskell.org
9 -- Stability : provisional
10 -- Portability : portable
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.
16 -----------------------------------------------------------------------------
18 module Foreign.ForeignPtr
20 -- * Finalised data pointers
21 ForeignPtr -- abstract, instance of: Eq, Ord, Show
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
30 , mallocForeignPtr -- :: Storable a => IO (ForeignPtr a)
31 , mallocForeignPtrBytes -- :: Int -> IO (ForeignPtr a)
32 , mallocForeignPtrArray -- :: Storable a => Int -> IO (ForeignPtr a)
33 , mallocForeignPtrArray0 -- :: Storable a => Int -> IO (ForeignPtr a)
40 import Foreign.Storable
44 #ifdef __GLASGOW_HASKELL__
48 import GHC.Ptr ( Ptr(..) )
57 , addForeignPtrFinalizer
66 import Hugs.ForeignPtr
71 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
74 #ifdef __GLASGOW_HASKELL__
75 -- |The type 'ForeignPtr' represents references to objects that are
76 -- maintained in a foreign language, i.e., that are not part of the
77 -- data structures usually managed by the Haskell storage manager.
78 -- The essential difference between 'ForeignPtr's and vanilla memory
79 -- references of type @Ptr a@ is that the former may be associated
80 -- with /finalisers/. A finaliser is a routine that is invoked when
81 -- the Haskell storage manager detects that - within the Haskell heap
82 -- and stack - there are no more references left that are pointing to
83 -- the 'ForeignPtr'. Typically, the finaliser will, then, invoke
84 -- routines in the foreign language that free the resources bound by
85 -- the foreign object.
87 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'. The
88 -- type argument of 'ForeignPtr' should normally be an instance of
92 = ForeignPtr ForeignObj#
93 | MallocPtr (MutableByteArray# RealWorld)
95 instance Eq (ForeignPtr a) where
96 p == q = foreignPtrToPtr p == foreignPtrToPtr q
98 instance Ord (ForeignPtr a) where
99 compare p q = compare (foreignPtrToPtr p) (foreignPtrToPtr q)
101 instance Show (ForeignPtr a) where
102 showsPrec p f = showsPrec p (foreignPtrToPtr f)
105 newForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
106 -- ^Turns a plain memory reference into a foreign object
107 -- by associating a finaliser - given by the monadic operation
108 -- - with the reference. The finaliser will be executed after
109 -- the last reference to the foreign object is dropped. Note
110 -- that there is no guarantee on how soon the finaliser is
111 -- executed after the last reference was dropped; this depends
112 -- on the details of the Haskell storage manager. The only
113 -- guarantee is that the finaliser runs before the program
115 newForeignPtr p finalizer
116 = do fObj <- mkForeignPtr p
117 addForeignPtrFinalizer fObj finalizer
120 -- | allocates some memory and returns a ForeignPtr to it. The memory
121 -- will be released automatically when the ForeignPtr is discarded.
123 -- @mallocForeignPtr@ is equivalent to
125 -- > do { p <- malloc; newForeignPtr p free }
127 -- although it may be implemented differently internally. You may not
128 -- assume that the memory returned by 'mallocForeignPtr' has been
129 -- allocated with C's @malloc()@.
131 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
132 mallocForeignPtr = doMalloc undefined
133 where doMalloc :: Storable a => a -> IO (ForeignPtr a)
134 doMalloc a = IO $ \s ->
135 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
136 (# s, MallocPtr mbarr# #)
138 where (I# size) = sizeOf a
140 -- | similar to 'mallocForeignPtr', except that the size of the memory required
141 -- is given explicitly as a number of bytes.
142 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
143 mallocForeignPtrBytes (I# size) = IO $ \s ->
144 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
145 (# s, MallocPtr mbarr# #)
148 addForeignPtrFinalizer :: ForeignPtr a -> IO () -> IO ()
149 -- ^This function adds another finaliser to the given
150 -- foreign object. No guarantees are made on the order in
151 -- which multiple finalisers for a single object are run.
152 addForeignPtrFinalizer (ForeignPtr fo) finalizer =
153 IO $ \s -> case mkWeak# fo () finalizer s of { (# s1, w #) -> (# s1, () #) }
154 addForeignPtrFinalizer (MallocPtr fo) finalizer =
155 IO $ \s -> case mkWeak# fo () finalizer s of { (# s1, w #) -> (# s1, () #) }
157 mkForeignPtr :: Ptr a -> IO (ForeignPtr a) {- not exported -}
158 mkForeignPtr (Ptr obj) = IO ( \ s# ->
159 case mkForeignObj# obj s# of
160 (# s1#, fo# #) -> (# s1#, ForeignPtr fo# #) )
162 touchForeignPtr :: ForeignPtr a -> IO ()
163 -- ^This function ensures that the foreign object in
164 -- question is alive at the given place in the sequence of IO
165 -- actions. In particular 'withForeignPtr'
166 -- does a 'touchForeignPtr' after it
167 -- executes the user action.
169 -- This function can be used to express liveness
170 -- dependencies between 'ForeignPtr's: for
171 -- example, if the finalizer for one
172 -- 'ForeignPtr' touches a second
173 -- 'ForeignPtr', then it is ensured that the
174 -- second 'ForeignPtr' will stay alive at
175 -- least as long as the first. This can be useful when you
176 -- want to manipulate /interior pointers/ to
177 -- a foreign structure: you can use
178 -- 'touchForeignObj' to express the
179 -- requirement that the exterior pointer must not be finalized
180 -- until the interior pointer is no longer referenced.
181 touchForeignPtr (ForeignPtr fo)
182 = IO $ \s -> case touch# fo s of s -> (# s, () #)
183 touchForeignPtr (MallocPtr fo)
184 = IO $ \s -> case touch# fo s of s -> (# s, () #)
186 withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
187 -- ^This is a way to look at the pointer living inside a
188 -- foreign object. This function takes a function which is
189 -- applied to that pointer. The resulting 'IO' action is then
190 -- executed. The foreign object is kept alive at least during
191 -- the whole action, even if it is not used directly
192 -- inside. Note that it is not safe to return the pointer from
193 -- the action and use it after the action completes. All uses
194 -- of the pointer should be inside the
195 -- 'withForeignPtr' bracket. The reason for
196 -- this unsafety is the same as for
197 -- 'foreignPtrToPtr' below: the finalizer
198 -- may run earlier than expected, because the compiler can only
199 -- track usage of the 'ForeignPtr' object, not
200 -- a 'Ptr' object made from it.
202 -- This function is normally used for marshalling data to
203 -- or from the object pointed to by the
204 -- 'ForeignPtr', using the operations from the
207 = do r <- io (foreignPtrToPtr fo)
211 foreignPtrToPtr :: ForeignPtr a -> Ptr a
212 -- ^This function extracts the pointer component of a foreign
213 -- pointer. This is a potentially dangerous operations, as if the
214 -- argument to 'foreignPtrToPtr' is the last usage
215 -- occurence of the given foreign pointer, then its finaliser(s) will
216 -- be run, which potentially invalidates the plain pointer just
217 -- obtained. Hence, 'touchForeignPtr' must be used
218 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
219 -- has another usage occurrence.
221 -- To avoid subtle coding errors, hand written marshalling code
222 -- should preferably use 'withForeignPtr' rather
223 -- than combinations of 'foreignPtrToPtr' and
224 -- 'touchForeignPtr'. However, the later routines
225 -- are occasionally preferred in tool generated marshalling code.
226 foreignPtrToPtr (ForeignPtr fo) = Ptr (foreignObjToAddr# fo)
227 foreignPtrToPtr (MallocPtr fo) = Ptr (byteArrayContents# (unsafeCoerce# fo))
229 castForeignPtr :: ForeignPtr a -> ForeignPtr b
230 -- ^This function casts a 'ForeignPtr'
231 -- parameterised by one type into another type.
232 castForeignPtr (ForeignPtr a) = ForeignPtr a
233 castForeignPtr (MallocPtr a) = MallocPtr a
237 mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)
238 mallocForeignPtrArray = doMalloc undefined
240 doMalloc :: Storable a => a -> Int -> IO (ForeignPtr a)
241 doMalloc dummy size = mallocForeignPtrBytes (size * sizeOf dummy)
243 mallocForeignPtrArray0 :: Storable a => Int -> IO (ForeignPtr a)
244 mallocForeignPtrArray0 size = mallocForeignPtrArray (size + 1)