Foreign proxy

Manuel M T Chakravarty chak at
Mon Jan 13 09:45:33 EST 2003

An interface like the following has been repeatedly proposed
(in slightly varying versions):

  data ForeignObj a            -- abstract
  instance Eq (ForeignObj a)
  type Finalizer a = FunPtr (a -> IO ())
  newForeignObj   :: a -> Finalizer a -> IO (ForeignObj a) 
  addFinalizer    :: ForeignObj a -> Finalizer a -> IO () 
  withForeignObj  :: ForeignObj a -> (a -> IO b) -> IO b 
  touchForeignObj :: ForeignObj a -> IO () 

If we adopt it, we might define `ForeignPtr' in terms of the
new interface:

  type ForeignPtr a = ForeignObj (Ptr a)
  newForeignPtr :: a -> Finalizer (Ptr a) -> IO (ForeignPtr a) 

We, btw, also need

  foreignObjToObj :: ForeignObj a -> a

to implement `foreignPtrToPtr'.  Unfortunately, there
doesn't seem to be any easy way to implement
`castForeignPtr', which is valid for pointers, but can't be
generalised to `ForeignObj'.  We could assume the position
that such casts need always to be made on the vanilla `Ptr'
after it has been obtained from the `ForeignPtr'.  However,
this might be a nuisance in some situations.

Open Questions

(1) Shall we adopt an interface like `ForeignObj'?  
    (Seems like a nice idea to me.)

(2) What shall we do about `castForeignPtr'?

(3) Shall we call the new objects `ForeignObj'?
    (It's a good name, but conflicts with some of GHC's
    legacy libraries.  `ForeignProxy' is one of the more
    appealing possible alternatives that was suggested
    ealier.  `ForeignFinalized' is also nice, but maybe a
    bit long.)

What do you think?


More information about the FFI mailing list