[MLton] FFI types

Stephen Weeks MLton@mlton.org
Fri, 13 May 2005 06:13:27 -0700


> I  can  see  the  problem  with the cast being from string to MLton.Pointer.t
> because of a GC.  I would think that still, some kind of primitive  would  do
> the  job.   What  currently is the mechanism which goes from a string to what
> actually gets passed to the C code (to make the types right)?

The string is passed directly.  There is no conversion.  The MLton ILs
understand the notion of passing a string (internally a word8 vector)
to C all the way down to the lowest levels.

> The point is that a pointer in C really IS an xxx option in ML.  It is such a
> common idiom in C code that you really want the FFI to understand it.

One way to handle it is convert from string option to string on the
SML side and from SML string to C pointer on the C side, as opposed to
your original proposal which converted from SML string option to C
pointer on the SML side.  This could be done be auto-generating C
wrappers around both imports and exports that do the coercion.  To
convert from SML string option to C pointer, we could use the same
trick I described earlier, converting NONE to "" and converting SOME s
to s (hence assuming s is #"\000" terminated) on the SML side.  Then,
the auto-generated C wrapper could look at the string length and pass
the appropriate C pointer (either NULL or the string).  Going from C
pointer to SML string option is harder because the C code would seem
to need to get its hands on the SML "" value.  Because this (pointer)
value can change, the best way I can think to do that would be to
register it in some known global.

To handle the fact that MLton doesn't know about string options, we
could add some mechanism to specify coercions between types that are
not handled by the FFI and types that are, and have _import and
_export automatically call the coercions.