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