How to force finalization of ForeignPtr

Krasimir Angelov ka2_mail at
Mon Dec 22 02:18:38 EST 2003

Dear GHC team,

   In the current implementation there is no way to
force finalization of the foreign ptr if there are 
still references to it. In this scenario
the finalization will be executed during the next 
garbage collection. In some cases it is known that the
foreign pointer value is not used anymore but the
references still exist in the stack and they cannot be
freed from the collector. In such cases I want to be
able to explicitly finalize the foreign pointers. For
that reason I wrote the following simple function:

module FinalizeForeignPtr(finalizeForeignPtr) where

import GHC.ForeignPtr
import Data.IORef

finalizeForeignPtr :: ForeignPtr a -> IO ()
finalizeForeignPtr foreignPtr = do
	finalizers <- readIORef refFinalizers
	sequence_ finalizers
	writeIORef refFinalizers []
		refFinalizers = case foreignPtr of
			(ForeignPtr _ ref) -> ref
			(MallocPtr  _ ref) -> ref

The function uses the internal representation of the
foreign pointer. Is there any other way to do this or
I am missing something? If there is not any other way,
then I think that the right place for this function is
in the standard libraries.

Any suggestions will be welcomed!


Do you Yahoo!?
New Yahoo! Photos - easier uploading and sharing.

More information about the Glasgow-haskell-users mailing list