ANN: H98 FFI Addendum 1.0, Release Candidate 10

Fergus Henderson fjh at cs.mu.OZ.AU
Mon Jun 2 10:03:50 EDT 2003


On 02-Jun-2003, Alastair Reid <alastair at reid-consulting-uk.ltd.uk> wrote:
> If all the compiler is given is:
> 
>   data T
> 
> where T is not a builtin type, the compiler can't possible know how to 
> represent or marshall it.  (And since we can already do that using 'newtype T 
> = MkT Int8' I don't think we need to add another mechanism.)

Using `newtype T = MkT Int8' or equivalent only works for foreign data
types whose representation is known.  How do you deal with C's "time_t",
for example?  Or with C "struct" types?  The user doesn't want to make
non-portable assumptions about what padding the C compiler is going
to insert.

Like Haskell, Mercury allows data definitions with no body:

	:- type t.

But to deal with cases like the ones mentioned above,
Mercury also allows the user to declare how such types are
represented in foreign languages, using `pragma foreign_type'
declarations:

	:- pragma foreign_type("C", t, "some_c_typename").

The Mercury compiler will generate appropriate glue code to marshal and
unmarshal values of that type.

You might want to consider something like this for Haskell.
(Either that, or resign yourselves to this aspect of Haskell's FFI
being less expressive than Mercury! ;-)

In Mercury, you can even give a simple type different foreign_type
declarations for different languages:

	:- type time.
	:- pragma foreign_type("C", time, "time_t").
	:- pragma foreign_type("il", time, "[mscorlib]System.DateTime").
	:- pragma foreign_type("java", time, "Java.util.Date").

The Mercury compiler will choose whichever language is most appropriate
given the compilation options (e.g. when compiling to C or assembler,
it will use the "C" version, when compiling to .NET it will use the "il"
version, and when compiling to Java it will use the Java version).

> Although it is similar, I think
> 
>   data Int
> 
> with a builtin type is a different thing from what we're doing when we write:
> 
>   data T
> 
> for some foreign type.

Sure.  In fact, the "data Int" declaration need not even be physically
present; the implementation could just insert it in the Prelude automatically.
(That's what the Mercury implementation does for its builtin types.)

-- 
Fergus Henderson <fjh at cs.mu.oz.au>  |  "I have always known that the pursuit
The University of Melbourne         |  of excellence is a lethal habit"
WWW: <http://www.cs.mu.oz.au/~fjh>  |     -- the last words of T. S. Garp.



More information about the FFI mailing list