1 {-# LANGUAGE ForeignFunctionInterface #-}
13 import Foreign.Marshal.Alloc
16 import System.IO.Unsafe
17 import Foreign.C.Types
20 foreign import ccall "gc/gc.h GC_malloc"
21 mallocGC_c :: CSize -> IO (Ptr a)
23 foreign import ccall "gc/gc.h GC_get_heap_size"
24 heapSizeGC_c :: IO CSize
26 foreign import ccall "gc/gc.h GC_init"
29 foreign import ccall "gc/gc.h GC_add_roots"
30 addRootGCInternal_c :: Ptr a -> Ptr a -> IO ()
32 -- counts allocated memory in heap
33 {-# NOINLINE globalBytesAllocated #-}
34 globalBytesAllocated :: IORef Int
35 globalBytesAllocated = unsafePerformIO (newIORef 0)
37 -- |Initializs the GC. Should be called before mallocBytesGC
42 -- |Allocates size bytes in managed memory
43 mallocBytesGC :: Int -> IO (Ptr a)
44 mallocBytesGC size = do
45 --print "trying alloc"
46 ptr <- modifyIORef globalBytesAllocated (+ size) >> mallocGC_c (fromIntegral size)
48 then error "mallocBytes asked memory management for memory but returned nullPtr. (see BoehmGC)"
52 -- |Allocates size bytes in managed memory
53 mallocBytesGC :: Int -> IO (Ptr a)
54 mallocBytesGC = mallocGC_c . fromIntegral
57 -- |Explicitely deallocate an object. Not required and dangerous.
58 unsafeFreeGC :: Ptr a -> IO ()
59 unsafeFreeGC _ = print "not implemented"
61 -- |Returns currently allocated memory in bytes
62 getHeapSizeGC :: IO Int
63 getHeapSizeGC = liftM fromIntegral heapSizeGC_c
65 -- |Adds a memory segment to be GC root
66 addRootGC :: Ptr a -> Ptr a -> IO ()
67 addRootGC = addRootGCInternal_c