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