1 <!-- FFI docs as a chapter -->
4 <title>Foreign function interface (FFI)</title>
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:
14 <para>Syntactic forms and library functions proposed in earlier versions
15 of the FFI are still supported for backwards compatibility.</para>
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>
27 <para>The FFI libraries are documented in the accompanying library
28 documentation; see for example the <literal>Foreign</literal>
31 <sect1 id="sec-ffi-ghcexts">
32 <title>GHC extensions to the FFI Addendum</title>
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>
39 <title>Unboxed types</title>
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>
52 <sect1 id="sec-ffi-ghc">
53 <title>Using the FFI with GHC</title>
55 <para>The following sections also give some hints and tips on the
56 use of the foreign function interface in GHC.</para>
58 <sect2 id="foreign-export-ghc">
59 <title>Using <literal>foreign export</literal> and <literal>foreign import ccall "wrapper"</literal> with GHC</title>
61 <indexterm><primary><literal>foreign export
62 </literal></primary><secondary>with GHC</secondary>
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>
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>
82 foreign export ccall foo :: Int -> IO Int
85 foo n = return (length (f n))
89 f n = n:(f (n-1))</programlisting>
91 <para>Then <filename>Foo_stub.h</filename> will contain
92 something like this:</para>
96 extern HsInt foo(HsInt a0);</programlisting>
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>
103 <sect3 id="using-own-main">
104 <title>Using your own <literal>main()</literal></title>
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>
114 <para>Let's take the example from above, and invoke it from a
115 standalone C program. Here's the C code:</para>
118 #include <stdio.h>
121 #ifdef __GLASGOW_HASKELL__
122 #include "foo_stub.h"
125 #ifdef __GLASGOW_HASKELL__
126 extern void __stginit_Foo ( void );
129 int main(int argc, char *argv[])
133 hs_init(&argc, &argv);
134 #ifdef __GLASGOW_HASKELL__
135 hs_add_root(__stginit_Foo);
138 for (i = 0; i < 5; i++) {
139 printf("%d\n", foo(2500));
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>
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>
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>
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
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
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>
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>
205 <sect3 id="foreign-export-dynamic-ghc">
206 <title>Using <literal>foreign import ccall "wrapper"</literal> with GHC</title>
208 <indexterm><primary><literal>foreign import
209 ccall "wrapper"</literal></primary><secondary>with GHC</secondary>
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 ––make</literal>, as GHC will automatically link in the
221 correct bits).</para>
225 <sect2 id="glasgow-foreign-headers">
226 <title>Using function headers</title>
228 <indexterm><primary>C calls, function headers</primary></indexterm>
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>-#include</option> directive
233 (<xref linkend="options-C-compiler"/>) to provide
234 <filename>.h</filename> files containing function
237 <para>For example,</para>
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);
249 <para>The types <literal>HsInt</literal>,
250 <literal>HsForeignObj</literal> etc. are described in the H98 FFI
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>
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>-#include</option>? If the imported module is from the same package as
264 the module being compiled, you should supply all the <option>-#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>-#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>-#include</option> options into the package configuration.
270 See the <literal>c_includes</literal> field in <xref linkend="package-management"/>.
274 It is also possible, according the FFI specification, to put the
275 <option>-#include</option> option in the foreign import
278 foreign import "foo.h f" f :: Int -> IO Int
280 When compiling this module, GHC will generate a C file that includes
281 the specified <option>-#include</option>. However, GHC
282 <emphasis>disables</emphasis> cross-module inlinding for such foreign
283 calls, because it doesn't transport the <option>-#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>-#include</option> mechanism.
291 <sect3 id="finding-header-files">
292 <title>Finding Header files</title>
294 <para>Header files named by the <option>-#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>
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>
314 <title>Memory Allocation</title>
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>
325 <term><literal>alloca</literal> and friends</term>
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>
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>
342 <term><literal>mallocForeignPtr</literal></term>
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>
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
363 <term><literal>malloc/free</literal></term>
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>
378 <term><literal>Foreign.Marhsal.Pool</literal></term>
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>
395 ;;; Local Variables: ***
397 ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter") ***