[project @ 2003-01-28 16:57:40 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 (FFI)</Title>
5
6   <para>GHC (mostly) conforms to the Haskell 98 Foreign Function Interface
7   Addendum 1.0, whose definition is available from <ULink
8   URL="http://haskell.org/"><literal>http://haskell.org/</literal></ULink >.
9   The FFI support in GHC diverges from the Addendum in the following ways:
10   </para>
11
12   <itemizedlist>
13     <listitem>
14       <para>The routines <literal>hs_init()</literal>,
15       <literal>hs_exit()</literal>, and <literal>hs_set_argv()</literal> from
16       Chapter 6.1 of the Addendum are not supported yet.</para>
17     </listitem>
18
19     <listitem>
20       <para>Syntactic forms and library functions proposed in earlier versions
21       of the FFI are still supported for backwards compatibility.</para>
22     </listitem>
23
24     <listitem>
25       <para>GHC implements a number of GHC-specific extensions to the FFI
26       Addendum.  These extensions are described in <xref
27       linkend="sec-ffi-ghcexts">, but please note that programs using
28       these features are not portable.  Hence, these features should be
29       avoided where possible.</para>
30     </listitem>
31   </itemizedlist>
32
33   <para>The FFI libraries are documented in the accompanying library
34   documentation; see for example the <literal>Foreign</literal>
35   module.</para>
36
37   <sect1 id="sec-ffi-ghcexts">
38     <title>GHC extensions to the FFI Addendum</title>
39
40     <para>The FFI features that are described in this section are specific to
41     GHC.  Avoid them where possible to not compromise the portability of the
42     resulting code.</para>
43
44     <sect2>
45       <title>Arrays</title>
46
47       <para>The types <literal>ByteArray</literal> and
48       <literal>MutableByteArray</literal> may be used as basic foreign types
49       (see FFI Addendum, Section 3.2).  In C land, they map to
50       <literal>(char *)</literal>.</para>
51     </sect2>
52
53     <sect2>
54       <title>Unboxed types</title>
55
56       <para>The following unboxed types may be used as basic foreign types
57       (see FFI Addendum, Section 3.2): <literal>Int#</literal>,
58       <literal>Word#</literal>, <literal>Char#</literal>,
59       <literal>Float#</literal>, <literal>Double#</literal>,
60       <literal>Addr#</literal>, <literal>StablePtr# a</literal>,
61       <literal>MutableByteArray#</literal>, <literal>ForeignObj#</literal>,
62       and <literal>ByteArray#</literal>.</para>
63     </sect2>
64
65   </sect1>
66
67   <sect1 id="sec-ffi-ghc">
68     <title>Using the FFI with GHC</title>
69
70     <para>The following sections also give some hints and tips on the
71     use of the foreign function interface in GHC.</para>
72
73     <sect2 id="foreign-export-ghc">
74       <title>Using <literal>foreign export</literal> and <literal>foreign
75       import ccall "wrapper"</literal> with GHC</title>
76
77       <indexterm><primary><literal>foreign export
78       </literal></primary><secondary>with GHC</secondary>
79       </indexterm>
80
81       <para>When GHC compiles a module (say <filename>M.hs</filename>)
82       which uses <literal>foreign export</literal> or <literal>foreign
83       import "wrapper"</literal>, it generates two
84       additional files, <filename>M_stub.c</filename> and
85       <filename>M_stub.h</filename>.  GHC will automatically compile
86       <filename>M_stub.c</filename> to generate
87       <filename>M_stub.o</filename> at the same time.</para>
88
89       <para>For a plain <literal>foreign export</literal>, the file
90       <filename>M_stub.h</filename> contains a C prototype for the
91       foreign exported function, and <filename>M_stub.c</filename>
92       contains its definition.  For example, if we compile the
93       following module:</para>
94
95 <programlisting>
96 module Foo where
97
98 foreign export ccall foo :: Int -> IO Int
99
100 foo :: Int -> IO Int
101 foo n = return (length (f n))
102
103 f :: Int -> [Int]
104 f 0 = []
105 f n = n:(f (n-1))</programlisting>
106
107       <para>Then <filename>Foo_stub.h</filename> will contain
108       something like this:</para>
109
110 <programlisting>
111 #include "HsFFI.h"
112 extern HsInt foo(HsInt a0);</programlisting>
113
114       <para>and <filename>Foo_stub.c</filename> contains the
115       compiler-generated definition of <literal>foo()</literal>.  To
116       invoke <literal>foo()</literal> from C, just <literal>#include
117       "Foo_stub.h"</literal> and call <literal>foo()</literal>.</para>
118
119       <sect3> 
120         <title>Using your own <literal>main()</literal></title>
121
122         <para>Normally, GHC's runtime system provides a
123         <literal>main()</literal>, which arranges to invoke
124         <literal>Main.main</literal> in the Haskell program.  However,
125         you might want to link some Haskell code into a program which
126         has a main function written in another languagem, say C.  In
127         order to do this, you have to initialize the Haskell runtime
128         system explicitly.</para>
129
130         <para>Let's take the example from above, and invoke it from a
131         standalone C program.  Here's the C code:</para>
132
133 <programlisting>
134 #include &lt;stdio.h&gt;
135 #include "HsFFI.h"
136
137 #ifdef __GLASGOW_HASKELL__
138 #include "foo_stub.h"
139 #endif
140
141 #ifdef __GLASGOW_HASKELL__
142 extern void __stginit_Foo ( void );
143 #endif
144
145 int main(int argc, char *argv[])
146 {
147   int i;
148
149   hs_init(&amp;argc, &amp;argv);
150 #ifdef __GLASGOW_HASKELL__
151   hs_add_root(__stginit_Foo);
152 #endif
153
154   for (i = 0; i < 5; i++) {
155     printf("%d\n", foo(2500));
156   }
157
158   hs_exit();
159   return 0;
160 }</programlisting>
161
162         <para>We've surrounded the GHC-specific bits with
163         <literal>#ifdef __GLASGOW_HASKELL__</literal>; the rest of the
164         code should be portable across Haskell implementations that
165         support the FFI standard.</para>
166
167         <para>The call to <literal>hs_init()</literal>
168         initializes GHC's runtime system.  Do NOT try to invoke any
169         Haskell functions before calling
170         <literal>hs_init()</literal>: strange things will
171         undoubtedly happen.</para>
172
173         <para>We pass <literal>argc</literal> and
174         <literal>argv</literal> to <literal>hs_init()</literal>
175         so that it can separate out any arguments for the RTS
176         (i.e. those arguments between
177         <literal>+RTS...-RTS</literal>).</para>
178
179         <para>Next, we call
180         <function>hs_add_root</function><indexterm><primary><function>hs_add_root</function></primary>
181         </indexterm>, a GHC-specific interface which is required to
182         initialise the Haskell modules in the program.  The argument
183         to <function>hs_add_root</function> should be the name of the
184         initialization function for the "root" module in your program
185         - in other words, the module which directly or indirectly
186         imports all the other Haskell modules in the program.  In a
187         standalone Haskell program the root module is normally
188         <literal>Main</literal>, but when you are using Haskell code
189         from a library it may not be.  If your program has multiple
190         root modules, then you can call
191         <function>hs_add_root</function> multiple times, one for each
192         root.  The name of the initialization function for module
193         <replaceable>M</replaceable> is
194         <literal>__stginit_<replaceable>M</replaceable></literal>, and
195         it may be declared as an external function symbol as in the
196         code above.</para>
197
198         <para>After we've finished invoking our Haskell functions, we
199         can call <literal>hs_exit()</literal>, which
200         terminates the RTS.  It runs any outstanding finalizers and
201         generates any profiling or stats output that might have been
202         requested.</para>
203
204         <para>There can be multiple calls to
205         <literal>hs_init()</literal>, but each one should be matched
206         by one (and only one) call to
207         <literal>hs_exit()</literal><footnote><para>The outermost
208         <literal>hs_exit()</literal> will actually de-initialise the
209         system.  NOTE that currently GHC's runtime cannot reliably
210         re-initialise after this has happened.</para>
211         </footnote>.</para>
212
213         <para>NOTE: when linking the final program, it is normally
214         easiest to do the link using GHC, although this isn't
215         essential.  If you do use GHC, then don't forget the flag
216         <option>-no-hs-main</option><indexterm><primary><option>-no-hs-main</option></primary>
217           </indexterm>, otherwise GHC will try to link
218         to the <literal>Main</literal> Haskell module.</para>
219       </sect3>
220
221       <sect3 id="foreign-export-dynamic-ghc">
222         <title>Using <literal>foreign import ccall "wrapper"</literal> with
223         GHC</title>
224
225         <indexterm><primary><literal>foreign import
226         ccall "wrapper"</literal></primary><secondary>with GHC</secondary>
227         </indexterm>
228
229         <para>When <literal>foreign import ccall "wrapper"</literal> is used
230         in a Haskell module, The C stub file <filename>M_stub.c</filename>
231         generated by GHC contains small helper functions used by the code
232         generated for the imported wrapper, so it must be linked in to the
233         final program.  When linking the program, remember to include
234         <filename>M_stub.o</filename> in the final link command line, or
235         you'll get link errors for the missing function(s) (this isn't
236         necessary when building your program with <literal>ghc
237         &ndash;&ndash;make</literal>, as GHC will automatically link in the
238         correct bits).</para>
239       </sect3>
240     </sect2>
241     
242     <sect2 id="glasgow-foreign-headers">
243       <title>Using function headers</title>
244
245       <indexterm><primary>C calls, function headers</primary></indexterm>
246
247       <para>When generating C (using the <option>-fvia-C</option>
248       directive), one can assist the C compiler in detecting type
249       errors by using the <option>-&num;include</option> directive
250       (<xref linkend="options-C-compiler">) to provide
251       <filename>.h</filename> files containing function
252       headers.</para>
253
254       <para>For example,</para>
255
256 <programlisting>
257 #include "HsFFI.h"
258
259 void         initialiseEFS (HsInt size);
260 HsInt        terminateEFS (void);
261 HsForeignObj emptyEFS(void);
262 HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x);
263 HsInt        lookupEFS (HsForeignObj a, HsInt i);
264 </programlisting>
265
266       <para>The types <literal>HsInt</literal>,
267       <literal>HsForeignObj</literal> etc. are described in the H98 FFI
268       Addendum.</para>
269
270       <para>Note that this approach is only
271       <emphasis>essential</emphasis> for returning
272       <literal>float</literal>s (or if <literal>sizeof(int) !=
273       sizeof(int *)</literal> on your architecture) but is a Good
274       Thing for anyone who cares about writing solid code.  You're
275       crazy not to do it.</para>
276
277 <para>
278 What if you are importing a module from another package, and
279 a cross-module inlining exposes a foreign call that needs a supporting
280 <option>-&num;include</option>?  If the imported module is from the same package as
281 the module being compiled, you should supply all the <option>-&num;include</option>
282 that you supplied when compiling the imported module.  If the imported module comes
283 from another package, you won't necessarily know what the appropriate 
284 <option>-&num;include</option> options are; but they should be in the package 
285 configuration, which GHC knows about.  So if you are building a package, remember
286 to put all those <option>-&num;include</option> options into the package configuration.
287 See the <literal>c_includes</literal> field in <xref linkend="package-management">.
288 </para>
289
290 <para>
291 It is also possible, according the FFI specification, to put the 
292 <option>-&num;include</option> option in the foreign import 
293 declaration itself:
294 <programlisting>
295   foreign import "foo.h f" f :: Int -> IO Int
296 </programlisting>
297 When compiling this module, GHC will generate a C file that includes
298 the specified <option>-&num;include</option>.  However, GHC
299 <emphasis>disables</emphasis> cross-module inlinding for such foreign
300 calls, because it doesn't transport the <option>-&num;include</option>
301 information across module boundaries.  (There is no fundamental reason for this;
302 it was just tiresome to implement.  The wrapper, which unboxes the arguments
303 etc, is still inlined across modules.)  So if you want the foreign call itself
304 to be inlined across modules, use the command-line and package-configuration
305 <option>-&num;include</option> mechanism.
306 </para>
307
308     </sect2>
309   </sect1>
310 </Chapter>
311
312 <!-- Emacs stuff:
313      ;;; Local Variables: ***
314      ;;; mode: sgml ***
315      ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter") ***
316      ;;; End: ***
317  -->