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