[project @ 2001-09-17 09:51:23 by simonmar]
[ghc-hetmet.git] / ghc / docs / users_guide / ffi-chap.sgml
1 <!-- FFI docs as a chapter -->
2
3 <Chapter id="ffi">
4 <Title>Foreign function interface</Title>
5
6   <para>The foreign function interface consists of the following
7   components:</para>
8
9   <itemizedlist>
10     <listitem>
11       <para>The Foreign Function Interface language specification
12       (which constitutes most of this Chapter, beginning with <xref
13       linkend="sec-ffi-intro">).  You must use the
14       <option>-fglasgow-exts</option> command-line option to make GHC
15       understand the <literal>foreign</literal> declarations defined
16       by the FFI.</para>
17     </listitem>
18
19     <listitem>
20       <para>Several library modules which provide access to types used
21       by foreign languages and utilties for marshalling values to and
22       from foreign functions, and for converting errors in the foreign
23       language into Haskell IO errors.  See <xref linkend="sec-Foreign"> for
24       more details.  </para>
25     </listitem>
26   </itemizedlist>
27
28 &ffi-body;
29
30   <sect1 id="ffi-ghc">
31     <title>Using the FFI with GHC</title>
32
33     <para>The following sections also give some hints and tips on the
34     use of the foreign function interface in GHC.</para>
35
36     <sect2 id="foreign-export-ghc">
37       <title>Using <literal>foreign export</literal> with GHC</title>
38
39       <indexterm><primary><literal>foreign export
40       </literal></primary><secondary>with GHC</secondary>
41       </indexterm>
42
43       <para>When GHC compiles a module (say <filename>M.hs</filename>)
44       which uses <literal>foreign export</literal> or <literal>foreign
45       export dynamic</literal>, it generates two
46       additional files, <filename>M_stub.c</filename> and
47       <filename>M_stub.h</filename>.  GHC will automatically compile
48       <filename>M_stub.c</filename> to generate
49       <filename>M_stub.o</filename> at the same time.</para>
50
51       <para>For a plain <literal>foreign export</literal>, the file
52       <filename>M_stub.h</filename> contains a C prototype for the
53       foreign exported function, and <filename>M_stub.c</filename>
54       contains its definition.  For example, if we compile the
55       following module:</para>
56
57 <programlisting>
58 module Foo where
59
60 foreign export foo :: Int -> IO Int
61
62 foo :: Int -> IO Int
63 foo n = return (length (f n))
64
65 f :: Int -> [Int]
66 f 0 = []
67 f n = n:(f (n-1))</programlisting>
68
69       <para>Then <filename>Foo_stub.h</filename> will contain
70       something like this:</para>
71
72 <programlisting>
73 #include "HsFFI.h"
74 extern HsInt foo(HsInt a0);</programlisting>
75
76       <para>and <filename>Foo_stub.c</filename> contains the
77       compiler-generated definition of <literal>foo()</literal>.  To
78       invoke <literal>foo()</literal> from C, just <literal>#include
79       "Foo_stub.h"</literal> and call <literal>foo()</literal>.</para>
80
81       <sect3> 
82         <title>Using your own <literal>main()</literal></title>
83
84         <para>Normally, GHC's runtime system provides a
85         <literal>main()</literal>, which arranges to invoke
86         <literal>Main.main</literal> in the Haskell program.  However,
87         you might want to link some Haskell code into a program which
88         has a main function written in another languagem, say C.  In
89         order to do this, you have to initialize the Haskell runtime
90         system explicitly.</para>
91
92         <para>Let's take the example from above, and invoke it from a
93         standalone C program.  Here's the C code:</para>
94
95 <programlisting>
96 #include &lt;stdio.h&gt;
97 #include "foo_stub.h"
98
99 #include "RtsAPI.h"
100
101 extern void __stginit_Foo ( void );
102
103 int main(int argc, char *argv[])
104 {
105   int i;
106
107   startupHaskell(argc, argv, __stginit_Foo);
108
109   for (i = 0; i < 5; i++) {
110     printf("%d\n", foo(2500));
111   }
112
113   shutdownHaskell();
114
115   return 0;
116 }</programlisting>
117
118         <para>The call to <literal>startupHaskell()</literal>
119         initializes GHC's runtime system.  Do NOT try to invoke any
120         Haskell functions before calling
121         <literal>startupHaskell()</literal>: strange things will
122         undoubtedly happen.</para>
123
124         <para>We pass <literal>argc</literal> and
125         <literal>argv</literal> to <literal>startupHaskell()</literal>
126         so that it can separate out any arguments for the RTS
127         (i.e. those arguments between
128         <literal>+RTS...-RTS</literal>).</para>
129
130         <para>The third argument to <literal>startupHaskell()</literal>
131         is used for initializing the Haskell modules in the program.
132         It must be the name of the initialization function for the
133         "top" module in the program/library - in other words, the
134         module which directly or indirectly imports all the other
135         Haskell modules in the program.  In a standalone Haskell
136         program this would be module <literal>Main</literal>, but when
137         you are only using the Haskell code as a library it may not
138         be.  If your library doesn't have such a module, then it is
139         straightforward to create one, purely for this initialization
140         process.  The name of the initialization function for module
141         <replaceable>M</replaceable> is
142         <literal>__stginit_<replaceable>M</replaceable></literal>, and
143         it may be declared as an external function symbol as in the
144         code above.</para>
145
146         <para>After we've finished invoking our Haskell functions, we
147         can call <literal>shutdownHaskell()</literal>, which
148         terminates the RTS.  It runs any outstanding finalizers and
149         generates any profiling or stats output that might have been
150         requested.</para>
151
152         <para>The functions <literal>startupHaskell()</literal> and
153         <literal>shutdownHaskell()</literal> may be called only once
154         each, and only in that order.</para>
155       </sect3>
156
157       <sect3 id="foreign-export-dynamic-ghc">
158         <title>Using <literal>foreign export dynamic</literal> with
159         GHC</title>
160
161         <indexterm><primary><literal>foreign export
162         dynamic</literal></primary><secondary>with GHC</secondary>
163         </indexterm>
164
165         <para>When <literal>foreign export dynamic</literal> is used
166         in a Haskell module, The C stub file
167         <filename>M_stub.c</filename> generated by GHC contains small
168         helper functions used by the code generated for the
169         <literal>foreign export dynamic</literal>, so it must be
170         linked in to the final program.  When linking the program,
171         remember to include <filename>M_stub.o</filename> in the final
172         link command line, or you'll get link errors for the missing
173         function(s) (this isn't necessary when building your program
174         with <literal>ghc --make</literal>, as GHC will automatically
175         link in the correct bits).</para>
176       </sect3>
177     </sect2>
178     
179     <sect2 id="glasgow-foreign-headers">
180       <title>Using function headers</title>
181
182       <indexterm><primary>C calls, function headers</primary></indexterm>
183
184       <para>When generating C (using the <option>-fvia-C</option>
185
186       directive), one can assist the C compiler in detecting type
187       errors by using the <option>-&num;include</option> directive
188       (<xref linkend="options-C-compiler">) to provide
189       <filename>.h</filename> files containing function
190       headers.</para>
191
192       <para>For example,</para>
193
194 <programlisting>
195 #include "HsFFI.h"
196
197 void         initialiseEFS (HsInt size);
198 HsInt        terminateEFS (void);
199 HsForeignObj emptyEFS(void);
200 HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x);
201 HsInt        lookupEFS (HsForeignObj a, HsInt i);
202 </programlisting>
203
204       <para>The types <literal>HsInt</literal>,
205       <literal>HsForeignObj</literal> etc. are described in <xref
206       linkend="sec-ffi-mapping-table">.</para>
207
208       <para>Note that this approach is only
209       <emphasis>essential</emphasis> for returning
210       <literal>float</literal>s (or if <literal>sizeof(int) !=
211       sizeof(int *)</literal> on your architecture) but is a Good
212       Thing for anyone who cares about writing solid code.  You're
213       crazy not to do it.</para>
214
215     </sect2>
216   </sect1>
217 </Chapter>
218
219 <!-- Emacs stuff:
220      ;;; Local Variables: ***
221      ;;; mode: sgml ***
222      ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter") ***
223      ;;; End: ***
224  -->