[project @ 2003-07-29 12:03:13 by ross]
[ghc-base.git] / Foreign / ForeignPtr.hs
index 01c5c09..af39a61 100644 (file)
@@ -28,12 +28,10 @@ module Foreign.ForeignPtr
        , touchForeignPtr
        , castForeignPtr
 
-#ifndef __NHC__
        , mallocForeignPtr
        , mallocForeignPtrBytes
        , mallocForeignPtrArray
        , mallocForeignPtrArray0
-#endif
         ) 
        where
 
@@ -44,11 +42,14 @@ import NHC.FFI
   ( ForeignPtr
   , FinalizerPtr
   , newForeignPtr
+  , newForeignPtr_
   , addForeignPtrFinalizer
   , withForeignPtr
   , unsafeForeignPtrToPtr
   , touchForeignPtr
   , castForeignPtr
+  , Storable(sizeOf)
+  , malloc, mallocBytes, finalizerFree
   )
 #endif
 
@@ -70,9 +71,9 @@ import GHC.ForeignPtr
 
 #if !defined(__NHC__) && !defined(__GLASGOW_HASKELL__)
 import Foreign.Marshal.Alloc   ( malloc, mallocBytes, finalizerFree )
-import Data.Dynamic
+import Data.Typeable
 
-#include "Dynamic.h"
+#include "Typeable.h"
 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
 
 instance Eq (ForeignPtr a) where 
@@ -87,6 +88,19 @@ instance Show (ForeignPtr a) where
 
 
 #ifndef __NHC__
+newForeignPtr :: Ptr a -> FinalizerPtr a -> IO (ForeignPtr a)
+-- ^Turns a plain memory reference into a foreign pointer, and
+-- associates a finaliser with the reference.  The finaliser will be executed
+-- after the last reference to the foreign object is dropped.  Note that there
+-- is no guarantee on how soon the finaliser is executed after the last
+-- reference was dropped; this depends on the details of the Haskell storage
+-- manager. The only guarantee is that the finaliser runs before the program
+-- terminates.
+newForeignPtr p finalizer
+  = do fObj <- newForeignPtr_ p
+       addForeignPtrFinalizer fObj finalizer
+       return fObj
+
 withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
 -- ^This is a way to look at the pointer living inside a
 -- foreign object.  This function takes a function which is
@@ -113,12 +127,7 @@ withForeignPtr fo io
        return r
 #endif /* ! __NHC__ */
 
-#ifdef __HUGS__
--- temporary aliasing until hugs catches up
-unsafeForeignPtrToPtr = foreignPtrToPtr
-#endif
-
-#ifdef __HUGS__
+#ifndef __GLASGOW_HASKELL__
 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
 mallocForeignPtr = do
   r <- malloc
@@ -128,9 +137,8 @@ mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
 mallocForeignPtrBytes n = do
   r <- mallocBytes n
   newForeignPtr r finalizerFree
-#endif /* __HUGS__ */
+#endif /* __HUGS__ || __NHC__ */
 
-#ifndef __NHC__
 mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)
 mallocForeignPtrArray  = doMalloc undefined
   where
@@ -139,4 +147,3 @@ mallocForeignPtrArray  = doMalloc undefined
 
 mallocForeignPtrArray0      :: Storable a => Int -> IO (ForeignPtr a)
 mallocForeignPtrArray0 size  = mallocForeignPtrArray (size + 1)
-#endif