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)
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 Show (ForeignPtr a) where
99 showsPrec p f = showsPrec p (foreignPtrToPtr f)
102 newForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
103 -- ^Turns a plain memory reference into a foreign object
104 -- by associating a finaliser - given by the monadic operation
105 -- - with the reference. The finaliser will be executed after
106 -- the last reference to the foreign object is dropped. Note
107 -- that there is no guarantee on how soon the finaliser is
108 -- executed after the last reference was dropped; this depends
109 -- on the details of the Haskell storage manager. The only
110 -- guarantee is that the finaliser runs before the program
112 newForeignPtr p finalizer
113 = do fObj <- mkForeignPtr p
114 addForeignPtrFinalizer fObj finalizer
117 -- | allocates some memory and returns a ForeignPtr to it. The memory
118 -- will be released automatically when the ForeignPtr is discarded.
120 -- @mallocForeignPtr@ is equivalent to
122 -- > do { p <- malloc; newForeignPtr p free }
124 -- although it may be implemented differently internally. You may not
125 -- assume that the memory returned by 'mallocForeignPtr' has been
126 -- allocated with C's @malloc()@.
128 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
129 mallocForeignPtr = doMalloc undefined
130 where doMalloc :: Storable a => a -> IO (ForeignPtr a)
131 doMalloc a = IO $ \s ->
132 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
133 (# s, MallocPtr mbarr# #)
135 where (I# size) = sizeOf a
137 -- | similar to 'mallocForeignPtr', except that the size of the memory required
138 -- is given explicitly as a number of bytes.
139 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
140 mallocForeignPtrBytes (I# size) = IO $ \s ->
141 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
142 (# s, MallocPtr mbarr# #)
145 addForeignPtrFinalizer :: ForeignPtr a -> IO () -> IO ()
146 -- ^This function adds another finaliser to the given
147 -- foreign object. No guarantees are made on the order in
148 -- which multiple finalisers for a single object are run.
149 addForeignPtrFinalizer (ForeignPtr fo) finalizer =
150 IO $ \s -> case mkWeak# fo () finalizer s of { (# s1, w #) -> (# s1, () #) }
151 addForeignPtrFinalizer (MallocPtr fo) finalizer =
152 IO $ \s -> case mkWeak# fo () finalizer s of { (# s1, w #) -> (# s1, () #) }
154 mkForeignPtr :: Ptr a -> IO (ForeignPtr a) {- not exported -}
155 mkForeignPtr (Ptr obj) = IO ( \ s# ->
156 case mkForeignObj# obj s# of
157 (# s1#, fo# #) -> (# s1#, ForeignPtr fo# #) )
159 touchForeignPtr :: ForeignPtr a -> IO ()
160 -- ^This function ensures that the foreign object in
161 -- question is alive at the given place in the sequence of IO
162 -- actions. In particular 'withForeignPtr'
163 -- does a 'touchForeignPtr' after it
164 -- executes the user action.
166 -- This function can be used to express liveness
167 -- dependencies between 'ForeignPtr's: for
168 -- example, if the finalizer for one
169 -- 'ForeignPtr' touches a second
170 -- 'ForeignPtr', then it is ensured that the
171 -- second 'ForeignPtr' will stay alive at
172 -- least as long as the first. This can be useful when you
173 -- want to manipulate /interior pointers/ to
174 -- a foreign structure: you can use
175 -- 'touchForeignObj' to express the
176 -- requirement that the exterior pointer must not be finalized
177 -- until the interior pointer is no longer referenced.
178 touchForeignPtr (ForeignPtr fo)
179 = IO $ \s -> case touch# fo s of s -> (# s, () #)
180 touchForeignPtr (MallocPtr fo)
181 = IO $ \s -> case touch# fo s of s -> (# s, () #)
183 withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
184 -- ^This is a way to look at the pointer living inside a
185 -- foreign object. This function takes a function which is
186 -- applied to that pointer. The resulting 'IO' action is then
187 -- executed. The foreign object is kept alive at least during
188 -- the whole action, even if it is not used directly
189 -- inside. Note that it is not safe to return the pointer from
190 -- the action and use it after the action completes. All uses
191 -- of the pointer should be inside the
192 -- 'withForeignPtr' bracket. The reason for
193 -- this unsafety is the same as for
194 -- 'foreignPtrToPtr' below: the finalizer
195 -- may run earlier than expected, because the compiler can only
196 -- track usage of the 'ForeignPtr' object, not
197 -- a 'Ptr' object made from it.
199 -- This function is normally used for marshalling data to
200 -- or from the object pointed to by the
201 -- 'ForeignPtr', using the operations from the
204 = do r <- io (foreignPtrToPtr fo)
208 foreignPtrToPtr :: ForeignPtr a -> Ptr a
209 -- ^This function extracts the pointer component of a foreign
210 -- pointer. This is a potentially dangerous operations, as if the
211 -- argument to 'foreignPtrToPtr' is the last usage
212 -- occurence of the given foreign pointer, then its finaliser(s) will
213 -- be run, which potentially invalidates the plain pointer just
214 -- obtained. Hence, 'touchForeignPtr' must be used
215 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
216 -- has another usage occurrence.
218 -- To avoid subtle coding errors, hand written marshalling code
219 -- should preferably use 'withForeignPtr' rather
220 -- than combinations of 'foreignPtrToPtr' and
221 -- 'touchForeignPtr'. However, the later routines
222 -- are occasionally preferred in tool generated marshalling code.
223 foreignPtrToPtr (ForeignPtr fo) = Ptr (foreignObjToAddr# fo)
224 foreignPtrToPtr (MallocPtr fo) = Ptr (byteArrayContents# (unsafeCoerce# fo))
226 castForeignPtr :: ForeignPtr a -> ForeignPtr b
227 -- ^This function casts a 'ForeignPtr'
228 -- parameterised by one type into another type.
229 castForeignPtr (ForeignPtr a) = ForeignPtr a
230 castForeignPtr (MallocPtr a) = MallocPtr a
234 mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)
235 mallocForeignPtrArray = doMalloc undefined
237 doMalloc :: Storable a => a -> Int -> IO (ForeignPtr a)
238 doMalloc dummy size = mallocForeignPtrBytes (size * sizeOf dummy)
240 mallocForeignPtrArray0 :: Storable a => Int -> IO (ForeignPtr a)
241 mallocForeignPtrArray0 size = mallocForeignPtrArray (size + 1)