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