Ptr and ForeignPtr Questions

Manuel M. T. Chakravarty chak@cse.unsw.edu.au
Thu, 20 Sep 2001 16:45:42 +1000


Ashley Yakeley <ashley@semantic.org> wrote,

> The documentation for FFI in the GHC user's guide seems to be out of date 
> with regard to passing Ptrs across.
> 
> 1. My reference is 
> <http://www.haskell.org/ghc/docs/latest/set/ffi.html>
> (from <http://www.haskell.org/ghc/docs/latest/set/book-users-guide.html>)
> Is this the latest documentation available?
> 
> 2. My understanding is that you can use any instance of 'Storable a => 
> Ptr a' as an FFI argument and return type for both imported and exported 
> functions? Is this correct? 

If I understand you question correctly and you want to pass
a pointer to C land and back, yes, this is possible.

> What if the type is polymorphic (e.g. 
> declared as 'Storable a => Ptr a' rather than something like 'Ptr Word8')?

Also possible, as the argument to `Ptr' is just dummy.

> 3. What about ForeignPtr? Can instances of 'Storable a => ForeignPtr a' 
> be used in FFI?

They can be passed to C, but you can't get them back.  (The
storange manager wouldn't know what finaliser to attach.)

> 4. Does newForeignPtr work safely with null pointers, and will the 
> finalizer get called? For instance:
> 
>      fp <- newForeignPtr nullPtr finalFunc;
>      let {isNull = (foreignPtrToPtr fp) == nullPtr};
>      r <- withForeign fp (\p -> foo p);
> 
> Will foo be passed nullPtr? Will finalFunc ever get called? Is my use, 
> above, of foreignPtrToPtr safe, and will isNull be True?

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'.

Cheers,
Manuel