next up previous contents
Next: Compile-time constants Up: MLton User Guide Previous: Runtime system options   Contents


Foreign function interface (FFI)

MLton's FFI is not part of Standard ML and it is quite possible that this interface will change. That having been said, it is easy to make calls to C functions from within SML using MLton, at least when passing and returning simple types like char, double, int, and word. It is not possible to call C macros or to call SML from C. Suppose you would like to call a C function with the following prototype from SML:

int foo(double d, unsigned char c);
MLton extends the syntax of SML to allow expressions like the following:
_ffi "foo": real * char -> int;
This expression returns a function of type real * char -> int whose behavior is implemented by calling the C function whose name is foo. Thinking in terms of C, imagine that there is a C variable d of type double, c of type unsigned char, and i of type int. Then, the C statement i = foo(d, c) is executed. The general form of an _ffi declaration is:
_ffi "c function name": ty;
The semicolon is not optional. Here is a grammar for the types that are currently allowed.

\begin{displaymath}
\begin{array}{lcl}
\mbox{ty} & ::= & u \ \vert\ t\ \mbox{\tt...
...\vert\ \mbox{\tt word} \ \vert\ \mbox{\tt word8}\\
\end{array}\end{displaymath}

Here is the mapping between SML types and C types.
SML type C type
bool int (0 is false, nonzero is true)
char unsigned char
int int
real double
string char *
unit void
word unsigned int
word8 unsigned char
u array char *
u ref char *
u vector char *
Passing or returning tuples or datatypes is not allowed because the representation of these is decided late in the compilation process and because many optimizations can cause the representation to change. Arrays, refs, and vectors may only be passed as arguments and not returned as results because C functions are not allowed to allocate in the SML heap. Although the C type of an array, ref, or vector is always char*, in reality, the object is layed out in the natural C representation. Strings are just like char arrays, and are not null terminated, unless you manually do so from the SML side.



Subsections
next up previous contents
Next: Compile-time constants Up: MLton User Guide Previous: Runtime system options   Contents