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
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)
38 import Foreign.Storable
42 #ifdef __GLASGOW_HASKELL__
46 import GHC.Ptr ( Ptr(..) )
55 , addForeignPtrFinalizer
64 import Hugs.ForeignPtr
69 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
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.
85 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'. The
86 -- type argument of 'ForeignPtr' should normally be an instance of
90 = ForeignPtr ForeignObj#
91 | MallocPtr (MutableByteArray# RealWorld)
93 instance Eq (ForeignPtr a) where
94 p == q = foreignPtrToPtr p == foreignPtrToPtr q
96 instance Show (ForeignPtr a) where
97 showsPrec p f = showsPrec p (foreignPtrToPtr f)
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
110 newForeignPtr p finalizer
111 = do fObj <- mkForeignPtr p
112 addForeignPtrFinalizer fObj finalizer
115 -- | allocates some memory and returns a ForeignPtr to it. The memory
116 -- will be released automatically when the ForeignPtr is discarded.
118 -- @mallocForeignPtr@ is equivalent to
120 -- > do { p <- malloc; newForeignPtr p free }
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()@.
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# #)
133 where (I# size) = sizeOf a
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# #)
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, () #) }
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# #) )
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.
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, () #)
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.
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
202 = do r <- io (foreignPtrToPtr fo)
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.
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))
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