Ptr and ForeignPtr Questions
Thu, 20 Sep 2001 10:46:01 +0100
> At 2001-09-20 02:14, Simon Marlow wrote:
> >I'll just add that the docs have been updated for 5.02,
> Do you have a URL for that?
Not yet, but the release is imminent (really!) so it'll be up on the web
> >And don't forget that using foreignPtrToPtr is quite dangerous; much
> >better to use withForeignPtr instead, otherwise you might find the
> >ForeignPtr being finalised earlier than you expect.
> This is because foreignPtrToPtr is not in the IO monad, correct?
> foreignPtrToPtr :: ForeignPtr a -> Ptr a;
> A function like this:
> ioForeignPtrToPtr :: ForeignPtr a -> IO (Ptr a);
> ioForeignPtrToPtr fp =3D withForeignPtr fp return;
> ...would surely be safe? The 5.00 documentation claims that it isn't,=20
> however, but I don't see why.
No, it's not safe. The reason is that the compiler can track a
ForeignPtr to discover when it dies, in order to run the finalizer, but
it can't track a Ptr. As soon as you drop all references to the
ForeignPtr then the finalizer will run, even if you converted it to a
Ptr and you're still using it.
withForeignPtr is safe to use because it ensures that the ForeignPtr is
kept live until it returns. The documentation is a little terse on this
issue; I'll see if I can improve it.