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