<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 2.0.20">
<title>CallingFromCToSML</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700">
<link rel="stylesheet" href="./asciidoctor.css">
<link rel="stylesheet" href="./mlton.css">

</head>
<body class="article">
<div id="mlton-header">
<div id="mlton-header-text">
<h2>
<a href="./Home">
MLton
20241230+git20251029+dfsg-ok1
</a>
</h2>
</div>
</div>
<div id="header">
<h1>CallingFromCToSML</h1>
</div>
<div id="content">
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>MLton&#8217;s <a href="ForeignFunctionInterface">ForeignFunctionInterface</a> allows programs to <em>export</em> SML
functions to be called from C.  Suppose you would like export from SML
a function of type <code>real * char -&gt; int</code> as the C function <code>foo</code>.
MLton extends the syntax of SML to allow expressions like the
following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>_export "foo": (real * char -&gt; int) -&gt; unit;</pre>
</div>
</div>
<div class="paragraph">
<p>The above expression exports a C function named <code>foo</code>, with
prototype</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="c">Int32 foo (Real64 x0, Char x1);</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>_export</code> expression denotes a function of type
<code>(real * char -&gt; int) -&gt; unit</code> that when called with a function
<code>f</code>, arranges for the exported <code>foo</code> function to call <code>f</code>
when <code>foo</code> is called.  So, for example, the following exports and
defines <code>foo</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="sml">val e = _export "foo": (real * char -&gt; int) -&gt; unit;
val _ = e (fn (x, c) =&gt; 13 + Real.floor x + Char.ord c)</code></pre>
</div>
</div>
<div class="paragraph">
<p>The general form of an <code>_export</code> expression is</p>
</div>
<div class="listingblock">
<div class="content">
<pre>_export "C function name" attr... : cFuncTy -&gt; unit;</pre>
</div>
</div>
<div class="paragraph">
<p>The type and the semicolon are not optional.  As with <code>_import</code>, a
sequence of attributes may follow the function name.</p>
</div>
<div class="paragraph">
<p>MLton&#8217;s <code>-export-header</code> option generates a C header file with
prototypes for all of the functions exported from SML.  Include this
header file in your C files to type check calls to functions exported
from SML.  This header file includes <code>typedef</code>s for the
<a href="ForeignFunctionInterfaceTypes">types that can be passed between SML and C</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_example">Example</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Suppose that <code>export.sml</code> is</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="sml">val e = _export "f": (int * real * char -&gt; char) -&gt; unit;
val _ = e (fn (i, r, _) =&gt;
           (print (concat ["i = ", Int.toString i,
                           "  r = ", Real.toString r, "\n"])
            ; #"g"))
val g = _import "g" public reentrant: unit -&gt; unit;
val _ = g ()
val _ = g ()

val e = _export "f2": (Word8.word -&gt; word array) -&gt; unit;
val _ = e (fn w =&gt;
           Array.tabulate (10, fn _ =&gt; Word.fromLargeWord (Word8.toLargeWord w)))
val g2 = _import "g2" public reentrant: unit -&gt; word array;
val a = g2 ()
val _ = print (concat ["0wx", Word.toString (Array.sub (a, 0)), "\n"])

val e = _export "f3": (unit -&gt; unit) -&gt; unit;
val _ = e (fn () =&gt; print "hello\n");
val g3 = _import "g3" public reentrant: unit -&gt; unit;
val _ = g3 ()

(* This example demonstrates mutual recursion between C and SML. *)
val e = _export "f4": (int -&gt; unit) -&gt; unit;
val g4 = _import "g4" public reentrant: int -&gt; unit;
val _ = e (fn i =&gt; if i = 0 then () else g4 (i - 1))
val _ = g4 13

val (_, zzzSet) = _symbol "zzz" alloc: (unit -&gt; int) * (int -&gt; unit);
val () = zzzSet 42
val g5 = _import "g5" public: unit -&gt; unit;
val _ = g5 ()

val _ = print "success\n"</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that the the <code>reentrant</code> attribute is used for <code>_import</code>-ing the
C functions that will call the <code>_export</code>-ed SML functions.</p>
</div>
<div class="paragraph">
<p>Create the header file with <code>-export-header</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre>% mlton -default-ann 'allowFFI true'    \
        -export-header export.h         \
        -stop tc                        \
        export.sml</pre>
</div>
</div>
<div class="paragraph">
<p><code>export.h</code> now contains the following C prototypes.</p>
</div>
<div class="listingblock">
<div class="content">
<pre>Int8 f (Int32 x0, Real64 x1, Int8 x2);
Pointer f2 (Word8 x0);
void f3 ();
void f4 (Int32 x0);
extern Int32 zzz;</pre>
</div>
</div>
<div class="paragraph">
<p>Use <code>export.h</code> in a C program, <code>ffi-export.c</code>, as follows.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="c">#include &lt;stdio.h&gt;
#include "export.h"

/* Functions in C are by default PUBLIC symbols */
void g () {
        Char8 c;

        fprintf (stderr, "g starting\n");
        c = f (13, 17.15, 'a');
        fprintf (stderr, "g done  char = %c\n", c);
}

Pointer g2 () {
        Pointer res;
        fprintf (stderr, "g2 starting\n");
        res = f2 (0xFF);
        fprintf (stderr, "g2 done\n");
        return res;
}

void g3 () {
        fprintf (stderr, "g3 starting\n");
        f3 ();
        fprintf (stderr, "g3 done\n");
}

void g4 (Int32 i) {
        fprintf (stderr, "g4 (%d)\n", i);
        f4 (i);
}

void g5 () {
        fprintf (stderr, "g5 ()\n");
        fprintf (stderr, "zzz = %i\n", zzz);
        fprintf (stderr, "g5 done\n");
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Compile <code>ffi-export.c</code> and <code>export.sml</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre>% gcc -c ffi-export.c
% mlton -default-ann 'allowFFI true' \
         export.sml ffi-export.o</pre>
</div>
</div>
<div class="paragraph">
<p>Finally, run <code>export</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre>% ./export
g starting
...
g4 (0)
success</pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_download">Download</h2>
<div class="sectionbody">
<div class="ulist">
<ul>
<li>
<p><a href="https://raw.github.com/MLton/mlton/master/doc/examples/ffi/export.sml"><code>export.sml</code></a></p>
</li>
<li>
<p><a href="https://raw.github.com/MLton/mlton/master/doc/examples/ffi/ffi-export.c"><code>ffi-export.c</code></a></p>
</li>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>