module Foreign.ForeignPtr
(
ForeignPtr
, FinalizerPtr
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, FinalizerEnvPtr
#endif
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, newForeignPtrEnv
, addForeignPtrFinalizerEnv
#endif
, withForeignPtr
#ifdef __GLASGOW_HASKELL__
, finalizeForeignPtr
#endif
, unsafeForeignPtrToPtr
, touchForeignPtr
, castForeignPtr
, mallocForeignPtr
, mallocForeignPtrBytes
, mallocForeignPtrArray
, mallocForeignPtrArray0
)
where
import Foreign.Ptr
#ifdef __NHC__
import NHC.FFI
( ForeignPtr
, FinalizerPtr
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
, withForeignPtr
, unsafeForeignPtrToPtr
, touchForeignPtr
, castForeignPtr
, Storable(sizeOf)
, malloc, mallocBytes, finalizerFree
)
#endif
#ifdef __HUGS__
import Hugs.ForeignPtr
#endif
#ifndef __NHC__
import Foreign.Storable ( Storable(sizeOf) )
#endif
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.Num
import GHC.Err ( undefined )
import GHC.ForeignPtr
#endif
#if !defined(__NHC__) && !defined(__GLASGOW_HASKELL__)
import Foreign.Marshal.Alloc ( malloc, mallocBytes, finalizerFree )
instance Eq (ForeignPtr a) where
p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
instance Ord (ForeignPtr a) where
compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
instance Show (ForeignPtr a) where
showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
#endif
#ifndef __NHC__
newForeignPtr :: FinalizerPtr a -> Ptr a -> IO (ForeignPtr a)
newForeignPtr finalizer p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizer finalizer fObj
return fObj
withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
withForeignPtr fo io
= do r <- io (unsafeForeignPtrToPtr fo)
touchForeignPtr fo
return r
#endif /* ! __NHC__ */
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
newForeignPtrEnv ::
FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO (ForeignPtr a)
newForeignPtrEnv finalizer env p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizerEnv finalizer env fObj
return fObj
#endif /* __HUGS__ */
#ifndef __GLASGOW_HASKELL__
mallocForeignPtr :: Storable a => IO (ForeignPtr a)
mallocForeignPtr = do
r <- malloc
newForeignPtr finalizerFree r
mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
mallocForeignPtrBytes n = do
r <- mallocBytes n
newForeignPtr finalizerFree r
#endif /* !__GLASGOW_HASKELL__ */
mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray = doMalloc undefined
where
doMalloc :: Storable b => b -> Int -> IO (ForeignPtr b)
doMalloc dummy size = mallocForeignPtrBytes (size * sizeOf dummy)
mallocForeignPtrArray0 :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray0 size = mallocForeignPtrArray (size + 1)