[project @ 2003-01-22 10:55:56 by ross]
[ghc-base.git] / Foreign / ForeignPtr.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module      :  Foreign.ForeignPtr
5 -- Copyright   :  (c) The University of Glasgow 2001
6 -- License     :  BSD-style (see the file libraries/base/LICENSE)
7 -- 
8 -- Maintainer  :  ffi@haskell.org
9 -- Stability   :  provisional
10 -- Portability :  portable
11 --
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.
15 --
16 -----------------------------------------------------------------------------
17
18 module Foreign.ForeignPtr
19         ( 
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
28
29 #ifndef __NHC__
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)
34 #endif
35         ) 
36         where
37
38 #ifndef __NHC__
39 import Foreign.Ptr
40 import Foreign.Storable
41 import Data.Dynamic
42 #endif
43
44 #ifdef __GLASGOW_HASKELL__
45 import GHC.Base
46 import GHC.IOBase
47 import GHC.Num
48 import GHC.Ptr  ( Ptr(..) )
49 import GHC.Err
50 import GHC.Show
51 #endif
52
53 #ifdef __NHC__
54 import NHC.FFI
55   ( ForeignPtr
56   , newForeignPtr
57   , addForeignPtrFinalizer
58   , withForeignPtr
59   , foreignPtrToPtr
60   , touchForeignPtr
61   , castForeignPtr
62   )
63 #endif
64
65 #ifdef __HUGS__
66 import Hugs.ForeignPtr
67 #endif
68
69 #ifndef __NHC__
70 #include "Dynamic.h"
71 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
72 #endif
73
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.
86 --
87 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'.  The
88 -- type argument of 'ForeignPtr' should normally be an instance of
89 -- class 'Storable'.
90 --
91 data ForeignPtr a 
92   = ForeignPtr ForeignObj#
93   | MallocPtr  (MutableByteArray# RealWorld)
94
95 instance Eq (ForeignPtr a) where 
96     p == q  =  foreignPtrToPtr p == foreignPtrToPtr q
97
98 instance Show (ForeignPtr a) where
99     showsPrec p f = showsPrec p (foreignPtrToPtr f)
100
101
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
111 -- terminates.
112 newForeignPtr p finalizer
113   = do fObj <- mkForeignPtr p
114        addForeignPtrFinalizer fObj finalizer
115        return fObj
116
117 -- | allocates some memory and returns a ForeignPtr to it.  The memory
118 -- will be released automatically when the ForeignPtr is discarded.
119 --
120 -- @mallocForeignPtr@ is equivalent to
121 --
122 -- >    do { p <- malloc; newForeignPtr p free }
123 -- 
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()@.
127
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# #)
134           }
135           where (I# size) = sizeOf a
136
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# #)
143   }
144
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, () #) }
153
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# #) )
158
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.
165 -- 
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, () #)
182
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.
198 --
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
202 -- 'Storable' class.
203 withForeignPtr fo io
204   = do r <- io (foreignPtrToPtr fo)
205        touchForeignPtr fo
206        return r
207
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.
217 --
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))
225
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
231 #endif
232
233 #ifndef __NHC__
234 mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)
235 mallocForeignPtrArray  = doMalloc undefined
236   where
237     doMalloc            :: Storable a => a -> Int -> IO (ForeignPtr a)
238     doMalloc dummy size  = mallocForeignPtrBytes (size * sizeOf dummy)
239
240 mallocForeignPtrArray0      :: Storable a => Int -> IO (ForeignPtr a)
241 mallocForeignPtrArray0 size  = mallocForeignPtrArray (size + 1)
242 #endif