Import Upstream version 20180207
[hcoop/debian/mlton.git] / doc / guide / src / CallingFromSMLToC.adoc
CommitLineData
7f918cf1
CE
1CallingFromSMLToC
2=================
3
4MLton's <:ForeignFunctionInterface:> allows an SML program to _import_
5C functions. Suppose you would like to import from C a function with
6the following prototype:
7[source,c]
8----
9int foo (double d, char c);
10----
11MLton extends the syntax of SML to allow expressions like the following:
12----
13_import "foo": real * char -> int;
14----
15This expression denotes a function of type `real * char -> int` whose
16behavior is implemented by calling the C function whose name is `foo`.
17Thinking 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,
19the C statement `i = foo (d, c)` is executed and `i` is returned.
20
21The general form of an `_import` expression is:
22----
23_import "C function name" attr... : cFuncTy;
24----
25The type and the semicolon are not optional.
26
27The function name is followed by a (possibly empty) sequence of
28attributes, analogous to C `__attribute__` specifiers.
29
30
31== Example ==
32
33`import.sml` imports the C function `ffi` and the C variable `FFI_INT`
34as follows.
35
36[source,sml]
37----
38sys::[./bin/InclGitFile.py mlton master doc/examples/ffi/import.sml]
39----
40
41`ffi-import.c` is
42
43[source,c]
44----
45sys::[./bin/InclGitFile.py mlton master doc/examples/ffi/ffi-import.c]
46----
47
48Compile and run the program.
49----
50% mlton -default-ann 'allowFFI true' -export-header export.h import.sml ffi-import.c
51% ./import
5213
53success
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:>