Ptr and ForeignPtr Questions

Simon Marlow simonmar@microsoft.com
Thu, 20 Sep 2001 10:14:12 +0100


> Ashley Yakeley <ashley@semantic.org> wrote,
>=20
> > The documentation for FFI in the GHC user's guide seems to=20
> be out of date=20
> > with regard to passing Ptrs across.
> >=20
> > 1. My reference is=20
> > <http://www.haskell.org/ghc/docs/latest/set/ffi.html>
> > (from=20
> <http://www.haskell.org/ghc/docs/latest/set/book-users-guide.html>)
> > Is this the latest documentation available?
> >=20
> > 2. My understanding is that you can use any instance of=20
> 'Storable a =3D>=20
> > Ptr a' as an FFI argument and return type for both imported=20
> and exported=20
> > functions? Is this correct?=20
>=20
> If I understand you question correctly and you want to pass
> a pointer to C land and back, yes, this is possible.

I'll just add that the docs have been updated for 5.02, and the FFI
section now refers to Ptr and ForeignPtr instead of Addr and ForeignObj.

> > 4. Does newForeignPtr work safely with null pointers, and will the=20
> > finalizer get called? For instance:
> >=20
> >      fp <- newForeignPtr nullPtr finalFunc;
> >      let {isNull =3D (foreignPtrToPtr fp) =3D=3D nullPtr};
> >      r <- withForeign fp (\p -> foo p);
> >=20
> > Will foo be passed nullPtr? Will finalFunc ever get called?=20
> Is my use,=20
> > above, of foreignPtrToPtr safe, and will isNull be True?
>=20
> Should work.  From the storage managers point of view, a
> `Ptr' is just an uninterpreted bit-pattern.  A glorified
> `Int'.  Of course, you should better make sure that
> `finalFunc' can handle getting a `nullPtr'.

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.

Cheers,
	Simon