remove empty dir
[ghc-hetmet.git] / ghc / docs / users_guide / ffi-chap.xml
1 <?xml version="1.0" encoding="iso-8859-1"?>
2 <!-- FFI docs as a chapter -->
3
4 <chapter id="ffi">
5  <title>
6 Foreign function interface (FFI)
7  </title>
8
9   <para>GHC (mostly) conforms to the Haskell 98 Foreign Function Interface
10   Addendum 1.0, whose definition is available from <ulink url="http://haskell.org/"><literal>http://haskell.org/</literal></ulink>.</para>
11
12   <para>To enable FFI support in GHC, give the <option>-fffi</option><indexterm><primary><option>-fffi</option></primary>
13     </indexterm>flag, or
14 the <option>-fglasgow-exts</option><indexterm><primary><option>-fglasgow-exts</option></primary>
15     </indexterm> flag which implies <option>-fffi</option>
16 .</para>
17
18   <para>The FFI support in GHC diverges from the Addendum in the following ways:</para>
19
20   <itemizedlist>
21     <listitem>
22       <para>Syntactic forms and library functions proposed in earlier versions
23       of the FFI are still supported for backwards compatibility.</para>
24     </listitem>
25
26     <listitem>
27       <para>GHC implements a number of GHC-specific extensions to the FFI
28       Addendum.  These extensions are described in <xref linkend="sec-ffi-ghcexts" />, but please note that programs using
29       these features are not portable.  Hence, these features should be
30       avoided where possible.</para>
31     </listitem>
32   </itemizedlist>
33
34   <para>The FFI libraries are documented in the accompanying library
35   documentation; see for example the <literal>Foreign</literal>
36   module.</para>
37
38   <sect1 id="sec-ffi-ghcexts">
39     <title>GHC extensions to the FFI Addendum</title>
40
41     <para>The FFI features that are described in this section are specific to
42     GHC.  Avoid them where possible to not compromise the portability of the
43     resulting code.</para>
44
45     <sect2>
46       <title>Unboxed types</title>
47
48       <para>The following unboxed types may be used as basic foreign types
49       (see FFI Addendum, Section 3.2): <literal>Int#</literal>,
50       <literal>Word#</literal>, <literal>Char#</literal>,
51       <literal>Float#</literal>, <literal>Double#</literal>,
52       <literal>Addr#</literal>, <literal>StablePtr# a</literal>,
53       <literal>MutableByteArray#</literal>, <literal>ForeignObj#</literal>,
54       and <literal>ByteArray#</literal>.</para>
55     </sect2>
56
57   </sect1>
58
59   <sect1 id="sec-ffi-ghc">
60     <title>Using the FFI with GHC</title>
61
62     <para>The following sections also give some hints and tips on the
63     use of the foreign function interface in GHC.</para>
64
65     <sect2 id="foreign-export-ghc">
66       <title>Using <literal>foreign export</literal> and <literal>foreign import ccall "wrapper"</literal> with GHC</title>
67
68       <indexterm><primary><literal>foreign export
69       </literal></primary><secondary>with GHC</secondary>
70       </indexterm>
71
72       <para>When GHC compiles a module (say <filename>M.hs</filename>)
73       which uses <literal>foreign export</literal> or 
74       <literal>foreign import "wrapper"</literal>, it generates two
75       additional files, <filename>M_stub.c</filename> and
76       <filename>M_stub.h</filename>.  GHC will automatically compile
77       <filename>M_stub.c</filename> to generate
78       <filename>M_stub.o</filename> at the same time.</para>
79
80       <para>For a plain <literal>foreign export</literal>, the file
81       <filename>M_stub.h</filename> contains a C prototype for the
82       foreign exported function, and <filename>M_stub.c</filename>
83       contains its definition.  For example, if we compile the
84       following module:</para>
85
86 <programlisting>
87 module Foo where
88
89 foreign export ccall foo :: Int -> IO Int
90
91 foo :: Int -> IO Int
92 foo n = return (length (f n))
93
94 f :: Int -> [Int]
95 f 0 = []
96 f n = n:(f (n-1))</programlisting>
97
98       <para>Then <filename>Foo_stub.h</filename> will contain
99       something like this:</para>
100
101 <programlisting>
102 #include "HsFFI.h"
103 extern HsInt foo(HsInt a0);</programlisting>
104
105       <para>and <filename>Foo_stub.c</filename> contains the
106       compiler-generated definition of <literal>foo()</literal>.  To
107       invoke <literal>foo()</literal> from C, just <literal>#include
108       "Foo_stub.h"</literal> and call <literal>foo()</literal>.</para>
109
110       <para>The <filename>foo_stub.c</filename> and
111         <filename>foo_stub.h</filename> files can be redirected using the
112         <option>-stubdir</option> option; see <xref linkend="options-output"
113           />.</para>
114
115       <sect3 id="using-own-main"> 
116         <title>Using your own <literal>main()</literal></title>
117
118         <para>Normally, GHC's runtime system provides a
119         <literal>main()</literal>, which arranges to invoke
120         <literal>Main.main</literal> in the Haskell program.  However,
121         you might want to link some Haskell code into a program which
122         has a main function written in another language, say C.  In
123         order to do this, you have to initialize the Haskell runtime
124         system explicitly.</para>
125
126         <para>Let's take the example from above, and invoke it from a
127         standalone C program.  Here's the C code:</para>
128
129 <programlisting>
130 #include &lt;stdio.h&gt;
131 #include "HsFFI.h"
132
133 #ifdef __GLASGOW_HASKELL__
134 #include "foo_stub.h"
135 #endif
136
137 #ifdef __GLASGOW_HASKELL__
138 extern void __stginit_Foo ( void );
139 #endif
140
141 int main(int argc, char *argv[])
142 {
143   int i;
144
145   hs_init(&amp;argc, &amp;argv);
146 #ifdef __GLASGOW_HASKELL__
147   hs_add_root(__stginit_Foo);
148 #endif
149
150   for (i = 0; i &lt; 5; i++) {
151     printf("%d\n", foo(2500));
152   }
153
154   hs_exit();
155   return 0;
156 }</programlisting>
157
158         <para>We've surrounded the GHC-specific bits with
159         <literal>#ifdef __GLASGOW_HASKELL__</literal>; the rest of the
160         code should be portable across Haskell implementations that
161         support the FFI standard.</para>
162
163         <para>The call to <literal>hs_init()</literal>
164         initializes GHC's runtime system.  Do NOT try to invoke any
165         Haskell functions before calling
166         <literal>hs_init()</literal>: strange things will
167         undoubtedly happen.</para>
168
169         <para>We pass <literal>argc</literal> and
170         <literal>argv</literal> to <literal>hs_init()</literal>
171         so that it can separate out any arguments for the RTS
172         (i.e. those arguments between
173         <literal>+RTS...-RTS</literal>).</para>
174
175         <para>Next, we call
176         <function>hs_add_root</function><indexterm><primary><function>hs_add_root</function></primary>
177         </indexterm>, a GHC-specific interface which is required to
178         initialise the Haskell modules in the program.  The argument
179         to <function>hs_add_root</function> should be the name of the
180         initialization function for the "root" module in your program
181         - in other words, the module which directly or indirectly
182         imports all the other Haskell modules in the program.  In a
183         standalone Haskell program the root module is normally
184         <literal>Main</literal>, but when you are using Haskell code
185         from a library it may not be.  If your program has multiple
186         root modules, then you can call
187         <function>hs_add_root</function> multiple times, one for each
188         root.  The name of the initialization function for module
189         <replaceable>M</replaceable> is
190         <literal>__stginit_<replaceable>M</replaceable></literal>, and
191         it may be declared as an external function symbol as in the
192         code above.</para>
193
194         <para>After we've finished invoking our Haskell functions, we
195         can call <literal>hs_exit()</literal>, which
196         terminates the RTS.  It runs any outstanding finalizers and
197         generates any profiling or stats output that might have been
198         requested.</para>
199
200         <para>There can be multiple calls to
201         <literal>hs_init()</literal>, but each one should be matched
202         by one (and only one) call to
203         <literal>hs_exit()</literal><footnote><para>The outermost
204         <literal>hs_exit()</literal> will actually de-initialise the
205         system.  NOTE that currently GHC's runtime cannot reliably
206         re-initialise after this has happened.</para>
207         </footnote>.</para>
208
209         <para>NOTE: when linking the final program, it is normally
210         easiest to do the link using GHC, although this isn't
211         essential.  If you do use GHC, then don't forget the flag
212         <option>-no-hs-main</option><indexterm><primary><option>-no-hs-main</option></primary>
213           </indexterm>, otherwise GHC will try to link
214         to the <literal>Main</literal> Haskell module.</para>
215       </sect3>
216
217       <sect3 id="foreign-export-dynamic-ghc">
218         <title>Using <literal>foreign import ccall "wrapper"</literal> with GHC</title>
219
220         <indexterm><primary><literal>foreign import
221         ccall "wrapper"</literal></primary><secondary>with GHC</secondary>
222         </indexterm>
223
224         <para>When <literal>foreign import ccall "wrapper"</literal> is used
225         in a Haskell module, The C stub file <filename>M_stub.c</filename>
226         generated by GHC contains small helper functions used by the code
227         generated for the imported wrapper, so it must be linked in to the
228         final program.  When linking the program, remember to include
229         <filename>M_stub.o</filename> in the final link command line, or
230         you'll get link errors for the missing function(s) (this isn't
231         necessary when building your program with <literal>ghc
232         &ndash;&ndash;make</literal>, as GHC will automatically link in the
233         correct bits).</para>
234       </sect3>
235     </sect2>
236     
237     <sect2 id="glasgow-foreign-headers">
238       <title>Using function headers</title>
239
240       <indexterm><primary>C calls, function headers</primary></indexterm>
241
242       <para>When generating C (using the <option>-fvia-C</option>
243       directive), one can assist the C compiler in detecting type
244       errors by using the <option>-&num;include</option> directive
245       (<xref linkend="options-C-compiler"/>) to provide
246       <filename>.h</filename> files containing function
247       headers.</para>
248
249       <para>For example,</para>
250
251 <programlisting>
252 #include "HsFFI.h"
253
254 void         initialiseEFS (HsInt size);
255 HsInt        terminateEFS (void);
256 HsForeignObj emptyEFS(void);
257 HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x);
258 HsInt        lookupEFS (HsForeignObj a, HsInt i);
259 </programlisting>
260
261       <para>The types <literal>HsInt</literal>,
262       <literal>HsForeignObj</literal> etc. are described in the H98 FFI
263       Addendum.</para>
264
265       <para>Note that this approach is only
266       <emphasis>essential</emphasis> for returning
267       <literal>float</literal>s (or if <literal>sizeof(int) !=
268       sizeof(int *)</literal> on your architecture) but is a Good
269       Thing for anyone who cares about writing solid code.  You're
270       crazy not to do it.</para>
271
272 <para>
273 What if you are importing a module from another package, and
274 a cross-module inlining exposes a foreign call that needs a supporting
275 <option>-&num;include</option>?  If the imported module is from the same package as
276 the module being compiled, you should supply all the <option>-&num;include</option>
277 that you supplied when compiling the imported module.  If the imported module comes
278 from another package, you won't necessarily know what the appropriate 
279 <option>-&num;include</option> options are; but they should be in the package 
280 configuration, which GHC knows about.  So if you are building a package, remember
281 to put all those <option>-&num;include</option> options into the package configuration.
282 See the <literal>c_includes</literal> field in <xref linkend="package-management"/>.
283 </para>
284
285 <para>
286 It is also possible, according the FFI specification, to put the 
287 <option>-&num;include</option> option in the foreign import 
288 declaration itself:
289 <programlisting>
290   foreign import "foo.h f" f :: Int -> IO Int
291 </programlisting>
292 When compiling this module, GHC will generate a C file that includes
293 the specified <option>-&num;include</option>.  However, GHC
294 <emphasis>disables</emphasis> cross-module inlining for such foreign
295 calls, because it doesn't transport the <option>-&num;include</option>
296 information across module boundaries.  (There is no fundamental reason for this;
297 it was just tiresome to implement.  The wrapper, which unboxes the arguments
298 etc, is still inlined across modules.)  So if you want the foreign call itself
299 to be inlined across modules, use the command-line and package-configuration
300 <option>-&num;include</option> mechanism.
301 </para>
302
303       <sect3 id="finding-header-files">
304         <title>Finding Header files</title>
305
306         <para>Header files named by the <option>-&num;include</option>
307         option or in a <literal>foreign import</literal> declaration
308         are searched for using the C compiler's usual search path.
309         You can add directories to this search path using the
310         <option>-I</option> option (see <xref
311         linkend="c-pre-processor"/>).</para>
312
313         <para>Note: header files are ignored unless compiling via C.
314         If you had been compiling your code using the native code
315         generator (the default) and suddenly switch to compiling via
316         C, then you can get unexpected errors about missing include
317         files.  Compiling via C is enabled automatically when certain
318         options are given (eg. <option>-O</option> and
319         <option>-prof</option> both enable
320         <option>-fvia-C</option>).</para>
321       </sect3>
322
323     </sect2>
324
325     <sect2>
326       <title>Memory Allocation</title>
327
328       <para>The FFI libraries provide several ways to allocate memory
329       for use with the FFI, and it isn't always clear which way is the
330       best.  This decision may be affected by how efficient a
331       particular kind of allocation is on a given compiler/platform,
332       so this section aims to shed some light on how the different
333       kinds of allocation perform with GHC.</para>
334
335       <variablelist>
336         <varlistentry>
337           <term><literal>alloca</literal> and friends</term>
338           <listitem>
339             <para>Useful for short-term allocation when the allocation
340             is intended to scope over a given <literal>IO</literal>
341             computation.  This kind of allocation is commonly used
342             when marshalling data to and from FFI functions.</para>
343
344             <para>In GHC, <literal>alloca</literal> is implemented
345             using <literal>MutableByteArray#</literal>, so allocation
346             and deallocation are fast: much faster than C's
347             <literal>malloc/free</literal>, but not quite as fast as
348             stack allocation in C.  Use <literal>alloca</literal>
349             whenever you can.</para>
350           </listitem>
351         </varlistentry>
352
353         <varlistentry>
354           <term><literal>mallocForeignPtr</literal></term>
355           <listitem>
356             <para>Useful for longer-term allocation which requires
357             garbage collection.  If you intend to store the pointer to
358             the memory in a foreign data structure, then
359             <literal>mallocForeignPtr</literal> is
360             <emphasis>not</emphasis> a good choice, however.</para>
361
362             <para>In GHC, <literal>mallocForeignPtr</literal> is also
363             implemented using <literal>MutableByteArray#</literal>.
364             Although the memory is pointed to by a
365             <literal>ForeignPtr</literal>, there are no actual
366             finalizers involved (unless you add one with
367             <literal>addForeignPtrFinalizer</literal>), and the
368             deallocation is done using GC, so
369             <literal>mallocForeignPtr</literal> is normally very
370             cheap.</para>
371           </listitem>
372         </varlistentry>
373
374         <varlistentry>
375           <term><literal>malloc/free</literal></term>
376           <listitem>
377             <para>If all else fails, then you need to resort to
378             <literal>Foreign.malloc</literal> and
379             <literal>Foreign.free</literal>.  These are just wrappers
380             around the C functions of the same name, and their
381             efficiency will depend ultimately on the implementations
382             of these functions in your platform's C library.  We
383             usually find <literal>malloc</literal> and
384             <literal>free</literal> to be significantly slower than
385             the other forms of allocation above.</para>
386           </listitem>
387         </varlistentry>
388
389         <varlistentry>
390           <term><literal>Foreign.Marshal.Pool</literal></term>
391           <listitem>
392             <para>Pools are currently implemented using
393             <literal>malloc/free</literal>, so while they might be a
394             more convenient way to structure your memory allocation
395             than using one of the other forms of allocation, they
396             won't be any more efficient.  We do plan to provide an
397             improved-performance implementation of Pools in the
398             future, however.</para>
399           </listitem>
400         </varlistentry>
401       </variablelist>
402     </sect2>
403   </sect1>
404 </chapter>
405
406 <!-- Emacs stuff:
407      ;;; Local Variables: ***
408      ;;; mode: xml ***
409      ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") ***
410      ;;; End: ***
411  -->