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