How do you represent a C pointer type?

Alastair Reid reid at cs.utah.edu
Fri Jun 7 10:51:15 EDT 2002


> I have a small C interface with a C type DB.  DB handles are only
> administed on the C side; at the Haskell end they are a black box.
> The Haskell side never sees DB values, just values of type DB *
> (pointers to DB).  I'm wondering how to represent this.

The usual is something like:

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

> One solution would be just to represent the equivalent of DB * as
> type DBP = Addr (or Ptr () or something) but then of course it might
> be confused with any other Addr.

I think Addr is deprecated (in favour of Ptr and FunPtr).  It doesn't
even appear in section 3.2.  

[The other type that you might expect but which was dropped was 'Word'
- the reasoning being that it is an obstacle to writing portable code.
'Int' should be excluded for the same reason but that was even more
controversial than omitting Word :-)]

I'd say that 'Ptr ()' is discouraged partly because it's an accident
waiting to happen and also because it prevents you from creating
meaningful instances of Storable.

> A rather more ingenious solution would be something like 

> newtype DBPInternal = DBPInternal Int
> type DBP = Ptr (Ptr DBPInternal) 

> I think this might actually work in that a DBP would be marshallable
> and couldn't be confused with any other type not involving
> DBPInternal.  Elegant it isn't, since it involves a pretend pointer
> inside the Ptr just to get the types working.

I think this is too ingenious for me.  Not knowing about the common
trick of writing a datatype with no data constructors (note: not
sanctioned by H98), I can see why you might have gone for:

  newtype DB = DB_Dont_Use_Me Int
  type DBP = Ptr DB

or 

  newtype DB = DB_Dont_Use_Me Int

  foreign import ... :: blah -> IO (Ptr DB)

the idea being that no-one would ever use the data constructor or the Int.

I'm a bit puzzled by the double-layer of pointers though.


-- 
Alastair Reid        reid at cs.utah.edu        http://www.cs.utah.edu/~reid/



More information about the FFI mailing list