Backport from sid to buster
[hcoop/debian/mlton.git] / doc / guide / src / CallingFromCToSML.adoc
CommitLineData
7f918cf1
CE
1CallingFromCToSML
2=================
3
4MLton's <:ForeignFunctionInterface:> allows programs to _export_ SML
5functions to be called from C. Suppose you would like export from SML
6a function of type `real * char -> int` as the C function `foo`.
7MLton extends the syntax of SML to allow expressions like the
8following:
9----
10_export "foo": (real * char -> int) -> unit;
11----
12The above expression exports a C function named `foo`, with
13prototype
14[source,c]
15----
16Int32 foo (Real64 x0, Char x1);
17----
18The `_export` expression denotes a function of type
19`(real * char -> int) -> unit` that when called with a function
20`f`, arranges for the exported `foo` function to call `f`
21when `foo` is called. So, for example, the following exports and
22defines `foo`.
23[source,sml]
24----
25val e = _export "foo": (real * char -> int) -> unit;
26val _ = e (fn (x, c) => 13 + Real.floor x + Char.ord c)
27----
28
29The general form of an `_export` expression is
30----
31_export "C function name" attr... : cFuncTy -> unit;
32----
33The type and the semicolon are not optional. As with `_import`, a
34sequence of attributes may follow the function name.
35
36MLton's `-export-header` option generates a C header file with
37prototypes for all of the functions exported from SML. Include this
38header file in your C files to type check calls to functions exported
39from SML. This header file includes ++typedef++s for the
40<:ForeignFunctionInterfaceTypes: types that can be passed between SML and C>.
41
42
43== Example ==
44
45Suppose that `export.sml` is
46
47[source,sml]
48----
49sys::[./bin/InclGitFile.py mlton master doc/examples/ffi/export.sml]
50----
51
52Note that the the `reentrant` attribute is used for `_import`-ing the
53C functions that will call the `_export`-ed SML functions.
54
55Create the header file with `-export-header`.
56----
57% mlton -default-ann 'allowFFI true' \
58 -export-header export.h \
59 -stop tc \
60 export.sml
61----
62
63`export.h` now contains the following C prototypes.
64----
65Int8 f (Int32 x0, Real64 x1, Int8 x2);
66Pointer f2 (Word8 x0);
67void f3 ();
68void f4 (Int32 x0);
69extern Int32 zzz;
70----
71
72Use `export.h` in a C program, `ffi-export.c`, as follows.
73
74[source,c]
75----
76sys::[./bin/InclGitFile.py mlton master doc/examples/ffi/ffi-export.c]
77----
78
79Compile `ffi-export.c` and `export.sml`.
80----
81% gcc -c ffi-export.c
82% mlton -default-ann 'allowFFI true' \
83 export.sml ffi-export.o
84----
85
86Finally, run `export`.
87----
88% ./export
89g starting
90...
91g4 (0)
92success
93----
94
95
96== Download ==
97* <!RawGitFile(mlton,master,doc/examples/ffi/export.sml)>
98* <!RawGitFile(mlton,master,doc/examples/ffi/ffi-export.c)>