[project @ 2002-04-24 16:31:37 by simonmar]
[packages/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/core/LICENSE)
7 --
8 -- Maintainer : ffi@haskell.org
9 -- Stability : provisional
10 -- Portability : portable
11 --
12 -- $Id: ForeignPtr.hs,v 1.4 2002/04/24 16:31:44 simonmar Exp $
13 --
14 -- This module defines foreign pointers, i.e. addresses with associated
15 -- finalizers.
16 --
17 -----------------------------------------------------------------------------
18
19 module Foreign.ForeignPtr
20 ( ForeignPtr, -- abstract, instance of: Eq
21 , newForeignPtr -- :: Ptr a -> IO () -> IO (ForeignPtr a)
22 , addForeignPtrFinalizer -- :: ForeignPtr a -> IO () -> IO ()
23 , withForeignPtr -- :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
24 , foreignPtrToPtr -- :: ForeignPtr a -> Ptr a
25 , touchForeignPtr -- :: ForeignPtr a -> IO ()
26 , castForeignPtr -- :: ForeignPtr a -> ForeignPtr b
27 )
28 where
29
30 import Foreign.Ptr
31 import Data.Dynamic
32
33 #ifdef __GLASGOW_HASKELL__
34 import GHC.Base
35 import GHC.IOBase
36 import GHC.Num
37 import GHC.Err
38 #endif
39
40 #include "Dynamic.h"
41 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
42
43 #ifdef __GLASGOW_HASKELL__
44 data ForeignPtr a = ForeignPtr ForeignObj#
45 instance CCallable (ForeignPtr a)
46
47 eqForeignPtr :: ForeignPtr a -> ForeignPtr a -> Bool
48 eqForeignPtr (ForeignPtr fo1#) (ForeignPtr fo2#) = eqForeignObj# fo1# fo2#
49
50 instance Eq (ForeignPtr a) where
51 p == q = eqForeignPtr p q
52 p /= q = not (eqForeignPtr p q)
53
54 newForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
55 newForeignPtr p finalizer
56 = do fObj <- mkForeignPtr p
57 addForeignPtrFinalizer fObj finalizer
58 return fObj
59
60 addForeignPtrFinalizer :: ForeignPtr a -> IO () -> IO ()
61 addForeignPtrFinalizer (ForeignPtr fo) finalizer =
62 IO $ \s -> case mkWeak# fo () finalizer s of { (# s1, w #) -> (# s1, () #) }
63
64 mkForeignPtr :: Ptr a -> IO (ForeignPtr a) {- not exported -}
65 mkForeignPtr (Ptr obj) = IO ( \ s# ->
66 case mkForeignObj# obj s# of
67 (# s1#, fo# #) -> (# s1#, ForeignPtr fo# #) )
68
69 touchForeignPtr :: ForeignPtr a -> IO ()
70 touchForeignPtr (ForeignPtr fo)
71 = IO $ \s -> case touch# fo s of s -> (# s, () #)
72
73 withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
74 withForeignPtr fo io
75 = do r <- io (foreignPtrToPtr fo)
76 touchForeignPtr fo
77 return r
78
79 foreignPtrToPtr :: ForeignPtr a -> Ptr a
80 foreignPtrToPtr (ForeignPtr fo) = Ptr (foreignObjToAddr# fo)
81
82 castForeignPtr (ForeignPtr a) = ForeignPtr a
83 #endif
84