[Haskell-cafe] Attach a finalizer to a FunPtr

Roman Cheplyaka roman.cheplyaka at tweag.io
Tue Sep 17 08:26:55 UTC 2019

On 17/09/2019 10.50, Shao Cheng wrote:
> Hi Roman,
> mkWeak# 's "key" and "value" arguments must both be lifted types, see https://gitlab.haskell.org/ghc/ghc/blob/master/rts/PrimOps.cmm#L699. Your code directly passes the raw Addr# which is not a managed pointer, thus the segfault.
Ah, that makes sense — thanks Cheng (and Matthew). I modeled my code after mkWeakIORef, and I assumed that MutVar# and Addr# were in the same category.
> I recommend using ForeignPtr in this case. You can add finalizers to ForeignPtr properly, and coerce from ForeignPtr to FunPtr when using it, since they're both containing the Addr# under the hood.

I considered doing that, but that'd require quite a bit of code to be constantly converting between ForeignPtr and FunPtr and also converting IO () finalizers to FunPtr (...) finalizers. System.Mem.Weak looks like a better fit because it uses IO () finalizers.

I think I'll try attaching a finalizer to ForeignPtr itself and be careful to retain a pointer to ForeignPtr (perhaps with the help of a StablePtr) while it's in use. Or, if that doesn't work, I might implement a reference counter instead.


More information about the Haskell-Cafe mailing list