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