| 1 |
= CallingFromSMLToC |
| 2 |
|
| 3 |
MLton's <<ForeignFunctionInterface#>> allows an SML program to _import_ |
| 4 |
C functions. Suppose you would like to import from C a function with |
| 5 |
the following prototype: |
| 6 |
[source,c] |
| 7 |
---- |
| 8 |
int foo (double d, char c); |
| 9 |
---- |
| 10 |
MLton extends the syntax of SML to allow expressions like the following: |
| 11 |
---- |
| 12 |
_import "foo": real * char -> int; |
| 13 |
---- |
| 14 |
This expression denotes a function of type `real * char \-> int` whose |
| 15 |
behavior is implemented by calling the C function whose name is `foo`. |
| 16 |
Thinking in terms of C, imagine that there are C variables `d` of type |
| 17 |
`double`, `c` of type `unsigned char`, and `i` of type `int`. Then, |
| 18 |
the C statement `i = foo (d, c)` is executed and `i` is returned. |
| 19 |
|
| 20 |
The general form of an `_import` expression is: |
| 21 |
---- |
| 22 |
_import "C function name" attr... : cFuncTy; |
| 23 |
---- |
| 24 |
The type and the semicolon are not optional. |
| 25 |
|
| 26 |
The function name is followed by a (possibly empty) sequence of |
| 27 |
attributes, analogous to C `__attribute__` specifiers. |
| 28 |
|
| 29 |
|
| 30 |
== Example |
| 31 |
|
| 32 |
`import.sml` imports the C function `ffi` and the C variable `FFI_INT` |
| 33 |
as follows. |
| 34 |
|
| 35 |
[source,sml] |
| 36 |
---- |
| 37 |
include::https://raw.github.com/MLton/mlton/master/doc/examples/ffi/import.sml[indent=0] |
| 38 |
---- |
| 39 |
|
| 40 |
`ffi-import.c` is |
| 41 |
|
| 42 |
[source,c] |
| 43 |
---- |
| 44 |
include::https://raw.github.com/MLton/mlton/master/doc/examples/ffi/ffi-import.c[indent=0] |
| 45 |
---- |
| 46 |
|
| 47 |
Compile and run the program. |
| 48 |
---- |
| 49 |
% mlton -default-ann 'allowFFI true' -export-header export.h import.sml ffi-import.c |
| 50 |
% ./import |
| 51 |
13 |
| 52 |
success |
| 53 |
---- |
| 54 |
|
| 55 |
|
| 56 |
== Download |
| 57 |
* https://raw.github.com/MLton/mlton/master/doc/examples/ffi/import.sml[`import.sml`] |
| 58 |
* https://raw.github.com/MLton/mlton/master/doc/examples/ffi/ffi-import.c[`ffi-import.c`] |
| 59 |
|
| 60 |
|
| 61 |
== Next Steps |
| 62 |
|
| 63 |
* <<CallingFromSMLToCFunctionPointer#>> |