# [Haskell-cafe] Equivalent of withForeignPtr for System.Mem.Weak?

Matthew Steele mdsteele at alum.mit.edu
Sun Oct 31 23:14:16 EDT 2010

I have an object to which I have added one or more finalizers via
addFinalizer from System.Mem.Weak.  I would like to have a function
that allows me to make use of the object within a block of IO code,
and guarantee that the finalizer(s) will not be called during the code
block -- sort of like withForeignPtr, but for arbitrary objects.  Does
such a function exist, and if not, how could I write one?

I can imagine writing something like:

\begin{code}
withObject :: a -> IO b -> IO b
withObject obj action = do
result <- action
touchObject obj  -- touchObject :: a -> IO ()
return result
\end{code}

However, I don't know how I should implement touchObject and be
confident that it won't ever be optimized out.  Any suggestions?

Cheers,
-Matt