84fb8aed9298fbcadfd51a9106de3f53280ca88f
[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       <sect3 id="using-own-main"> 
111         <title>Using your own <literal>main()</literal></title>
112
113         <para>Normally, GHC's runtime system provides a
114         <literal>main()</literal>, which arranges to invoke
115         <literal>Main.main</literal> in the Haskell program.  However,
116         you might want to link some Haskell code into a program which
117         has a main function written in another language, say C.  In
118         order to do this, you have to initialize the Haskell runtime
119         system explicitly.</para>
120
121         <para>Let's take the example from above, and invoke it from a
122         standalone C program.  Here's the C code:</para>
123
124 <programlisting>
125 #include &lt;stdio.h&gt;
126 #include "HsFFI.h"
127
128 #ifdef __GLASGOW_HASKELL__
129 #include "foo_stub.h"
130 #endif
131
132 #ifdef __GLASGOW_HASKELL__
133 extern void __stginit_Foo ( void );
134 #endif
135
136 int main(int argc, char *argv[])
137 {
138   int i;
139
140   hs_init(&amp;argc, &amp;argv);
141 #ifdef __GLASGOW_HASKELL__
142   hs_add_root(__stginit_Foo);
143 #endif
144
145   for (i = 0; i &lt; 5; i++) {
146     printf("%d\n", foo(2500));
147   }
148
149   hs_exit();
150   return 0;
151 }</programlisting>
152
153         <para>We've surrounded the GHC-specific bits with
154         <literal>#ifdef __GLASGOW_HASKELL__</literal>; the rest of the
155         code should be portable across Haskell implementations that
156         support the FFI standard.</para>
157
158         <para>The call to <literal>hs_init()</literal>
159         initializes GHC's runtime system.  Do NOT try to invoke any
160         Haskell functions before calling
161         <literal>hs_init()</literal>: strange things will
162         undoubtedly happen.</para>
163
164         <para>We pass <literal>argc</literal> and
165         <literal>argv</literal> to <literal>hs_init()</literal>
166         so that it can separate out any arguments for the RTS
167         (i.e. those arguments between
168         <literal>+RTS...-RTS</literal>).</para>
169
170         <para>Next, we call
171         <function>hs_add_root</function><indexterm><primary><function>hs_add_root</function></primary>
172         </indexterm>, a GHC-specific interface which is required to
173         initialise the Haskell modules in the program.  The argument
174         to <function>hs_add_root</function> should be the name of the
175         initialization function for the "root" module in your program
176         - in other words, the module which directly or indirectly
177         imports all the other Haskell modules in the program.  In a
178         standalone Haskell program the root module is normally
179         <literal>Main</literal>, but when you are using Haskell code
180         from a library it may not be.  If your program has multiple
181         root modules, then you can call
182         <function>hs_add_root</function> multiple times, one for each
183         root.  The name of the initialization function for module
184         <replaceable>M</replaceable> is
185         <literal>__stginit_<replaceable>M</replaceable></literal>, and
186         it may be declared as an external function symbol as in the
187         code above.</para>
188
189         <para>After we've finished invoking our Haskell functions, we
190         can call <literal>hs_exit()</literal>, which
191         terminates the RTS.  It runs any outstanding finalizers and
192         generates any profiling or stats output that might have been
193         requested.</para>
194
195         <para>There can be multiple calls to
196         <literal>hs_init()</literal>, but each one should be matched
197         by one (and only one) call to
198         <literal>hs_exit()</literal><footnote><para>The outermost
199         <literal>hs_exit()</literal> will actually de-initialise the
200         system.  NOTE that currently GHC's runtime cannot reliably
201         re-initialise after this has happened.</para>
202         </footnote>.</para>
203
204         <para>NOTE: when linking the final program, it is normally
205         easiest to do the link using GHC, although this isn't
206         essential.  If you do use GHC, then don't forget the flag
207         <option>-no-hs-main</option><indexterm><primary><option>-no-hs-main</option></primary>
208           </indexterm>, otherwise GHC will try to link
209         to the <literal>Main</literal> Haskell module.</para>
210       </sect3>
211
212       <sect3 id="foreign-export-dynamic-ghc">
213         <title>Using <literal>foreign import ccall "wrapper"</literal> with GHC</title>
214
215         <indexterm><primary><literal>foreign import
216         ccall "wrapper"</literal></primary><secondary>with GHC</secondary>
217         </indexterm>
218
219         <para>When <literal>foreign import ccall "wrapper"</literal> is used
220         in a Haskell module, The C stub file <filename>M_stub.c</filename>
221         generated by GHC contains small helper functions used by the code
222         generated for the imported wrapper, so it must be linked in to the
223         final program.  When linking the program, remember to include
224         <filename>M_stub.o</filename> in the final link command line, or
225         you'll get link errors for the missing function(s) (this isn't
226         necessary when building your program with <literal>ghc
227         &ndash;&ndash;make</literal>, as GHC will automatically link in the
228         correct bits).</para>
229       </sect3>
230     </sect2>
231     
232     <sect2 id="glasgow-foreign-headers">
233       <title>Using function headers</title>
234
235       <indexterm><primary>C calls, function headers</primary></indexterm>
236
237       <para>When generating C (using the <option>-fvia-C</option>
238       directive), one can assist the C compiler in detecting type
239       errors by using the <option>-&num;include</option> directive
240       (<xref linkend="options-C-compiler"/>) to provide
241       <filename>.h</filename> files containing function
242       headers.</para>
243
244       <para>For example,</para>
245
246 <programlisting>
247 #include "HsFFI.h"
248
249 void         initialiseEFS (HsInt size);
250 HsInt        terminateEFS (void);
251 HsForeignObj emptyEFS(void);
252 HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x);
253 HsInt        lookupEFS (HsForeignObj a, HsInt i);
254 </programlisting>
255
256       <para>The types <literal>HsInt</literal>,
257       <literal>HsForeignObj</literal> etc. are described in the H98 FFI
258       Addendum.</para>
259
260       <para>Note that this approach is only
261       <emphasis>essential</emphasis> for returning
262       <literal>float</literal>s (or if <literal>sizeof(int) !=
263       sizeof(int *)</literal> on your architecture) but is a Good
264       Thing for anyone who cares about writing solid code.  You're
265       crazy not to do it.</para>
266
267 <para>
268 What if you are importing a module from another package, and
269 a cross-module inlining exposes a foreign call that needs a supporting
270 <option>-&num;include</option>?  If the imported module is from the same package as
271 the module being compiled, you should supply all the <option>-&num;include</option>
272 that you supplied when compiling the imported module.  If the imported module comes
273 from another package, you won't necessarily know what the appropriate 
274 <option>-&num;include</option> options are; but they should be in the package 
275 configuration, which GHC knows about.  So if you are building a package, remember
276 to put all those <option>-&num;include</option> options into the package configuration.
277 See the <literal>c_includes</literal> field in <xref linkend="package-management"/>.
278 </para>
279
280 <para>
281 It is also possible, according the FFI specification, to put the 
282 <option>-&num;include</option> option in the foreign import 
283 declaration itself:
284 <programlisting>
285   foreign import "foo.h f" f :: Int -> IO Int
286 </programlisting>
287 When compiling this module, GHC will generate a C file that includes
288 the specified <option>-&num;include</option>.  However, GHC
289 <emphasis>disables</emphasis> cross-module inlining for such foreign
290 calls, because it doesn't transport the <option>-&num;include</option>
291 information across module boundaries.  (There is no fundamental reason for this;
292 it was just tiresome to implement.  The wrapper, which unboxes the arguments
293 etc, is still inlined across modules.)  So if you want the foreign call itself
294 to be inlined across modules, use the command-line and package-configuration
295 <option>-&num;include</option> mechanism.
296 </para>
297
298       <sect3 id="finding-header-files">
299         <title>Finding Header files</title>
300
301         <para>Header files named by the <option>-&num;include</option>
302         option or in a <literal>foreign import</literal> declaration
303         are searched for using the C compiler's usual search path.
304         You can add directories to this search path using the
305         <option>-I</option> option (see <xref
306         linkend="c-pre-processor"/>).</para>
307
308         <para>Note: header files are ignored unless compiling via C.
309         If you had been compiling your code using the native code
310         generator (the default) and suddenly switch to compiling via
311         C, then you can get unexpected errors about missing include
312         files.  Compiling via C is enabled automatically when certain
313         options are given (eg. <option>-O</option> and
314         <option>-prof</option> both enable
315         <option>-fvia-C</option>).</para>
316       </sect3>
317
318     </sect2>
319
320     <sect2>
321       <title>Memory Allocation</title>
322
323       <para>The FFI libraries provide several ways to allocate memory
324       for use with the FFI, and it isn't always clear which way is the
325       best.  This decision may be affected by how efficient a
326       particular kind of allocation is on a given compiler/platform,
327       so this section aims to shed some light on how the different
328       kinds of allocation perform with GHC.</para>
329
330       <variablelist>
331         <varlistentry>
332           <term><literal>alloca</literal> and friends</term>
333           <listitem>
334             <para>Useful for short-term allocation when the allocation
335             is intended to scope over a given <literal>IO</literal>
336             computation.  This kind of allocation is commonly used
337             when marshalling data to and from FFI functions.</para>
338
339             <para>In GHC, <literal>alloca</literal> is implemented
340             using <literal>MutableByteArray#</literal>, so allocation
341             and deallocation are fast: much faster than C's
342             <literal>malloc/free</literal>, but not quite as fast as
343             stack allocation in C.  Use <literal>alloca</literal>
344             whenever you can.</para>
345           </listitem>
346         </varlistentry>
347
348         <varlistentry>
349           <term><literal>mallocForeignPtr</literal></term>
350           <listitem>
351             <para>Useful for longer-term allocation which requires
352             garbage collection.  If you intend to store the pointer to
353             the memory in a foreign data structure, then
354             <literal>mallocForeignPtr</literal> is
355             <emphasis>not</emphasis> a good choice, however.</para>
356
357             <para>In GHC, <literal>mallocForeignPtr</literal> is also
358             implemented using <literal>MutableByteArray#</literal>.
359             Although the memory is pointed to by a
360             <literal>ForeignPtr</literal>, there are no actual
361             finalizers involved (unless you add one with
362             <literal>addForeignPtrFinalizer</literal>), and the
363             deallocation is done using GC, so
364             <literal>mallocForeignPtr</literal> is normally very
365             cheap.</para>
366           </listitem>
367         </varlistentry>
368
369         <varlistentry>
370           <term><literal>malloc/free</literal></term>
371           <listitem>
372             <para>If all else fails, then you need to resort to
373             <literal>Foreign.malloc</literal> and
374             <literal>Foreign.free</literal>.  These are just wrappers
375             around the C functions of the same name, and their
376             efficiency will depend ultimately on the implementations
377             of these functions in your platform's C library.  We
378             usually find <literal>malloc</literal> and
379             <literal>free</literal> to be significantly slower than
380             the other forms of allocation above.</para>
381           </listitem>
382         </varlistentry>
383
384         <varlistentry>
385           <term><literal>Foreign.Marshal.Pool</literal></term>
386           <listitem>
387             <para>Pools are currently implemented using
388             <literal>malloc/free</literal>, so while they might be a
389             more convenient way to structure your memory allocation
390             than using one of the other forms of allocation, they
391             won't be any more efficient.  We do plan to provide an
392             improved-performance implementation of Pools in the
393             future, however.</para>
394           </listitem>
395         </varlistentry>
396       </variablelist>
397     </sect2>
398   </sect1>
399 </chapter>
400
401 <!-- Emacs stuff:
402      ;;; Local Variables: ***
403      ;;; mode: xml ***
404      ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") ***
405      ;;; End: ***
406  -->