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.
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 * |