ce24313a847caf7059009e83dfbf8d4f0efc0fb5
[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
156         <para>NOTE: when linking the final program, it is normally
157         easiest to do the link using GHC, although this isn't
158         essential.  If you do use GHC, then don't forget the flag
159         <option>-no-hs-main</option><indexterm><primary><option>-no-hs-main</option></primary>
160           </indexterm>, otherwise GHC will try to link
161         to the <literal>Main</literal> Haskell module.</para>
162       </sect3>
163
164       <sect3 id="foreign-export-dynamic-ghc">
165         <title>Using <literal>foreign export dynamic</literal> with
166         GHC</title>
167
168         <indexterm><primary><literal>foreign export
169         dynamic</literal></primary><secondary>with GHC</secondary>
170         </indexterm>
171
172         <para>When <literal>foreign export dynamic</literal> is used
173         in a Haskell module, The C stub file
174         <filename>M_stub.c</filename> generated by GHC contains small
175         helper functions used by the code generated for the
176         <literal>foreign export dynamic</literal>, so it must be
177         linked in to the final program.  When linking the program,
178         remember to include <filename>M_stub.o</filename> in the final
179         link command line, or you'll get link errors for the missing
180         function(s) (this isn't necessary when building your program
181         with <literal>ghc &ndash;&ndash;make</literal>, as GHC will automatically
182         link in the correct bits).</para>
183       </sect3>
184     </sect2>
185     
186     <sect2 id="glasgow-foreign-headers">
187       <title>Using function headers</title>
188
189       <indexterm><primary>C calls, function headers</primary></indexterm>
190
191       <para>When generating C (using the <option>-fvia-C</option>
192
193       directive), one can assist the C compiler in detecting type
194       errors by using the <option>-&num;include</option> directive
195       (<xref linkend="options-C-compiler">) to provide
196       <filename>.h</filename> files containing function
197       headers.</para>
198
199       <para>For example,</para>
200
201 <programlisting>
202 #include "HsFFI.h"
203
204 void         initialiseEFS (HsInt size);
205 HsInt        terminateEFS (void);
206 HsForeignObj emptyEFS(void);
207 HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x);
208 HsInt        lookupEFS (HsForeignObj a, HsInt i);
209 </programlisting>
210
211       <para>The types <literal>HsInt</literal>,
212       <literal>HsForeignObj</literal> etc. are described in <xref
213       linkend="sec-ffi-mapping-table">.</para>
214
215       <para>Note that this approach is only
216       <emphasis>essential</emphasis> for returning
217       <literal>float</literal>s (or if <literal>sizeof(int) !=
218       sizeof(int *)</literal> on your architecture) but is a Good
219       Thing for anyone who cares about writing solid code.  You're
220       crazy not to do it.</para>
221
222     </sect2>
223   </sect1>
224 </Chapter>
225
226 <!-- Emacs stuff:
227      ;;; Local Variables: ***
228      ;;; mode: sgml ***
229      ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter") ***
230      ;;; End: ***
231  -->