[project @ 2003-06-23 10:35:15 by simonpj]
[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
60       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 <literal>foreign
68       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 languagem, 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 < 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
208         GHC</title>
209
210         <indexterm><primary><literal>foreign import
211         ccall "wrapper"</literal></primary><secondary>with GHC</secondary>
212         </indexterm>
213
214         <para>When <literal>foreign import ccall "wrapper"</literal> is used
215         in a Haskell module, The C stub file <filename>M_stub.c</filename>
216         generated by GHC contains small helper functions used by the code
217         generated for the imported wrapper, so it must be linked in to the
218         final program.  When linking the program, remember to include
219         <filename>M_stub.o</filename> in the final link command line, or
220         you'll get link errors for the missing function(s) (this isn't
221         necessary when building your program with <literal>ghc
222         &ndash;&ndash;make</literal>, as GHC will automatically link in the
223         correct bits).</para>
224       </sect3>
225     </sect2>
226     
227     <sect2 id="glasgow-foreign-headers">
228       <title>Using function headers</title>
229
230       <indexterm><primary>C calls, function headers</primary></indexterm>
231
232       <para>When generating C (using the <option>-fvia-C</option>
233       directive), one can assist the C compiler in detecting type
234       errors by using the <option>-&num;include</option> directive
235       (<xref linkend="options-C-compiler">) to provide
236       <filename>.h</filename> files containing function
237       headers.</para>
238
239       <para>For example,</para>
240
241 <programlisting>
242 #include "HsFFI.h"
243
244 void         initialiseEFS (HsInt size);
245 HsInt        terminateEFS (void);
246 HsForeignObj emptyEFS(void);
247 HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x);
248 HsInt        lookupEFS (HsForeignObj a, HsInt i);
249 </programlisting>
250
251       <para>The types <literal>HsInt</literal>,
252       <literal>HsForeignObj</literal> etc. are described in the H98 FFI
253       Addendum.</para>
254
255       <para>Note that this approach is only
256       <emphasis>essential</emphasis> for returning
257       <literal>float</literal>s (or if <literal>sizeof(int) !=
258       sizeof(int *)</literal> on your architecture) but is a Good
259       Thing for anyone who cares about writing solid code.  You're
260       crazy not to do it.</para>
261
262 <para>
263 What if you are importing a module from another package, and
264 a cross-module inlining exposes a foreign call that needs a supporting
265 <option>-&num;include</option>?  If the imported module is from the same package as
266 the module being compiled, you should supply all the <option>-&num;include</option>
267 that you supplied when compiling the imported module.  If the imported module comes
268 from another package, you won't necessarily know what the appropriate 
269 <option>-&num;include</option> options are; but they should be in the package 
270 configuration, which GHC knows about.  So if you are building a package, remember
271 to put all those <option>-&num;include</option> options into the package configuration.
272 See the <literal>c_includes</literal> field in <xref linkend="package-management">.
273 </para>
274
275 <para>
276 It is also possible, according the FFI specification, to put the 
277 <option>-&num;include</option> option in the foreign import 
278 declaration itself:
279 <programlisting>
280   foreign import "foo.h f" f :: Int -> IO Int
281 </programlisting>
282 When compiling this module, GHC will generate a C file that includes
283 the specified <option>-&num;include</option>.  However, GHC
284 <emphasis>disables</emphasis> cross-module inlinding for such foreign
285 calls, because it doesn't transport the <option>-&num;include</option>
286 information across module boundaries.  (There is no fundamental reason for this;
287 it was just tiresome to implement.  The wrapper, which unboxes the arguments
288 etc, is still inlined across modules.)  So if you want the foreign call itself
289 to be inlined across modules, use the command-line and package-configuration
290 <option>-&num;include</option> mechanism.
291 </para>
292
293     </sect2>
294
295     <sect2>
296       <title>Memory Allocation</title>
297
298       <para>The FFI libraries provide several ways to allocate memory
299       for use with the FFI, and it isn't always clear which way is the
300       best.  This decision may be affected by how efficient a
301       particular kind of allocation is on a given compiler/platform,
302       so this section aims to shed some light on how the different
303       kinds of allocation perform with GHC.</para>
304
305       <variablelist>
306         <varlistentry>
307           <term><literal>alloca</literal> and friends</term>
308           <listitem>
309             <para>Useful for short-term allocation when the allocation
310             is intended to scope over a given <literal>IO</literal>
311             compuatation.  This kind of allocation is commonly used
312             when marshalling data to and from FFI functions.</para>
313
314             <para>In GHC, <literal>alloca</literal> is implemented
315             using <literal>MutableByteArray#</literal>, so allocation
316             and deallocation are fast: much faster than C's
317             <literal>malloc/free</literal>, but not quite as fast as
318             stack allocation in C.  Use <literal>alloca</literal>
319             whenever you can.</para>
320           </listitem>
321         </varlistentry>
322
323         <varlistentry>
324           <term><literal>mallocForeignPtr</literal></term>
325           <listitem>
326             <para>Useful for longer-term allocation which requires
327             garbage collection.  If you intend to store the pointer to
328             the memory in a foreign data structure, then
329             <literal>mallocForeignPtr</literal> is
330             <emphasis>not</emphasis> a good choice, however.</para>
331
332             <para>In GHC, <literal>mallocForeignPtr</literal> is also
333             implemented using <literal>MutableByteArray#</literal>.
334             Although the memory is pointed to by a
335             <literal>ForeignPtr</literal>, there are no actual
336             finalizers involved (unless you add one with
337             <literal>addForeignPtrFinalizer</literal>), and the
338             deallocation is done using GC, so
339             <literal>mallocForeignPtr</literal> is normally very
340             cheap.</para>
341           </listitem>
342         </varlistentry>
343
344         <varlistentry>
345           <term><literal>malloc/free</literal></term>
346           <listitem>
347             <para>If all else fails, then you need to resort to
348             <literal>Foreign.malloc</literal> and
349             <literal>Foreign.free</literal>.  These are just wrappers
350             around the C funcitons of the same name, and their
351             efficiency will depend ultimately on the implementations
352             of these functions in your platform's C library.  We
353             usually find <literal>malloc</literal> and
354             <literal>free</literal> to be significantly slower than
355             the other forms of allocation above.</para>
356           </listitem>
357         </varlistentry>
358
359         <varlistentry>
360           <term><literal>Foreign.Marhsal.Pool</literal></term>
361           <listitem>
362             <para>Pools are currently implemented using
363             <literal>malloc/free</literal>, so while they might be a
364             more convenient way to structure your memory allocation
365             than using one of the other forms of allocation, they
366             won't be any more efficient.  We do plan to provide an
367             improved-performance implementaiton of Pools in the
368             future, however.</para>
369           </listitem>
370         </varlistentry>
371       </variablelist>
372     </sect2>
373   </sect1>
374 </Chapter>
375
376 <!-- Emacs stuff:
377      ;;; Local Variables: ***
378      ;;; mode: sgml ***
379      ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter") ***
380      ;;; End: ***
381  -->