Import Upstream version 20180207
[hcoop/debian/mlton.git] / doc / guide / src / CallingFromSMLToCFunctionPointer.adoc
CommitLineData
7f918cf1
CE
1CallingFromSMLToCFunctionPointer
2================================
3
4Just as MLton can <:CallingFromSMLToC:directly call C functions>, it
5is possible to make indirect function calls; that is, function calls
6through a function pointer. MLton extends the syntax of SML to allow
7expressions like the following:
8----
9_import * : MLton.Pointer.t -> real * char -> int;
10----
11This expression denotes a function of type
12[source,sml]
13----
14MLton.Pointer.t -> real * char -> int
15----
16whose behavior is implemented by calling the C function at the address
17denoted by the `MLton.Pointer.t` argument, and supplying the C
18function two arguments, a `double` and an `int`. The C function
19pointer may be obtained, for example, by the dynamic linking loader
20(`dlopen`, `dlsym`, ...).
21
22The general form of an indirect `_import` expression is:
23----
24_import * attr... : cPtrTy -> cFuncTy;
25----
26The type and the semicolon are not optional.
27
28
29== Example ==
30
31This example uses `dlopen` and friends (imported using normal
32`_import`) to dynamically load the math library (`libm`) and call the
33`cos` function. Suppose `iimport.sml` contains the following.
34
35[source,sml]
36----
37sys::[./bin/InclGitFile.py mlton master doc/examples/ffi/iimport.sml]
38----
39
40Compile and run `iimport.sml`.
41----
42% mlton -default-ann 'allowFFI true' \
43 -target-link-opt linux -ldl \
44 -target-link-opt solaris -ldl \
45 iimport.sml
46% iimport
47 Math.cos(2.0) = ~0.416146836547
48libm.so::cos(2.0) = ~0.416146836547
49----
50
51This example also shows the `-target-link-opt` option, which uses the
52switch when linking only when on the specified platform. Compile with
53`-verbose 1` to see in more detail what's being passed to `gcc`.
54
55
56== Download ==
57* <!RawGitFile(mlton,master,doc/examples/ffi/iimport.sml)>