More on Ptr types

George Russell ger at
Mon Jun 10 06:51:50 EDT 2002

Alastair Reid wrote:
> Any casting between Ptr types (and FunPtr, StablePtr, etc.) has to
> apply the appropriate bit-shift (or whatever transformation is
> required).  The simplest way to handle this may be to remove all the
> cast* functions from the ffi spec so that they have to be done in the
> C world (which understands these things).  If this were simply
> intolerable (I must confess I don't know why we have them), I guess
> I'd define a ForeignCastable typeclass providing appropriate
> operations to cast to and from the equivalent of void*.
Also I think something would need to be done to allow the user to interface
to C libraries which need pointers to their own types (as in my first example).
You don't know whether DB * is a pointer to char, or int, or whatever.  Also
the suggested solution

  data DB    -- note that we have no constructors
  foreign import ... :: blah -> IO (Ptr DB)

does not necessarily guarantee that a Ptr DB is actually able to represent
a DB *, whatever it is.  So my suggestion would be that
(1) a data DB (or any other type with constructors) would be regarded as like C's type 
void, so that casting to a Ptr DB and back from any other pointer type will preserve
the pointer.
(2) the implementation be required to perform any necessary casting between pointer
types in argument and result types.  Then if a DB * is actually a pointer to a 4-byte
quantity (say), it will silently cast from Ptr DB.  I hope this would not in fact
be too hard; where a C compiler is used to read the header file, calling an 
import'd function with non-matching pointer types one hopes the compiler will insert
the relevant casts.  Still these are deep waters; if this issue is to be addressed
perhaps someone should check the latest copy of the C standard and see if it still
exists.  (I think Harbisson & Steele's reference to standard C mentions a machine
where differing pointer sizes actually occur, but I don't know if any are still

More information about the FFI mailing list