1 <?xml version="1.0" encoding="iso-8859-1"?>
2 <!-- FFI docs as a chapter -->
5 <title>Foreign function interface (FFI)</title>
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:
15 <para>Syntactic forms and library functions proposed in earlier versions
16 of the FFI are still supported for backwards compatibility.</para>
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>
28 <para>The FFI libraries are documented in the accompanying library
29 documentation; see for example the <literal>Foreign</literal>
32 <sect1 id="sec-ffi-ghcexts">
33 <title>GHC extensions to the FFI Addendum</title>
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>
40 <title>Unboxed types</title>
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>
53 <sect1 id="sec-ffi-ghc">
54 <title>Using the FFI with GHC</title>
56 <para>The following sections also give some hints and tips on the
57 use of the foreign function interface in GHC.</para>
59 <sect2 id="foreign-export-ghc">
60 <title>Using <literal>foreign export</literal> and <literal>foreign import ccall "wrapper"</literal> with GHC</title>
62 <indexterm><primary><literal>foreign export
63 </literal></primary><secondary>with GHC</secondary>
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>
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>
83 foreign export ccall foo :: Int -> IO Int
86 foo n = return (length (f n))
90 f n = n:(f (n-1))</programlisting>
92 <para>Then <filename>Foo_stub.h</filename> will contain
93 something like this:</para>
97 extern HsInt foo(HsInt a0);</programlisting>
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>
104 <sect3 id="using-own-main">
105 <title>Using your own <literal>main()</literal></title>
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>
115 <para>Let's take the example from above, and invoke it from a
116 standalone C program. Here's the C code:</para>
119 #include <stdio.h>
122 #ifdef __GLASGOW_HASKELL__
123 #include "foo_stub.h"
126 #ifdef __GLASGOW_HASKELL__
127 extern void __stginit_Foo ( void );
130 int main(int argc, char *argv[])
134 hs_init(&argc, &argv);
135 #ifdef __GLASGOW_HASKELL__
136 hs_add_root(__stginit_Foo);
139 for (i = 0; i < 5; i++) {
140 printf("%d\n", foo(2500));
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>
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>
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>
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
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
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>
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>
206 <sect3 id="foreign-export-dynamic-ghc">
207 <title>Using <literal>foreign import ccall "wrapper"</literal> with GHC</title>
209 <indexterm><primary><literal>foreign import
210 ccall "wrapper"</literal></primary><secondary>with GHC</secondary>
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 ––make</literal>, as GHC will automatically link in the
222 correct bits).</para>
226 <sect2 id="glasgow-foreign-headers">
227 <title>Using function headers</title>
229 <indexterm><primary>C calls, function headers</primary></indexterm>
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>-#include</option> directive
234 (<xref linkend="options-C-compiler"/>) to provide
235 <filename>.h</filename> files containing function
238 <para>For example,</para>
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);
250 <para>The types <literal>HsInt</literal>,
251 <literal>HsForeignObj</literal> etc. are described in the H98 FFI
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>
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>-#include</option>? If the imported module is from the same package as
265 the module being compiled, you should supply all the <option>-#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>-#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>-#include</option> options into the package configuration.
271 See the <literal>c_includes</literal> field in <xref linkend="package-management"/>.
275 It is also possible, according the FFI specification, to put the
276 <option>-#include</option> option in the foreign import
279 foreign import "foo.h f" f :: Int -> IO Int
281 When compiling this module, GHC will generate a C file that includes
282 the specified <option>-#include</option>. However, GHC
283 <emphasis>disables</emphasis> cross-module inlinding for such foreign
284 calls, because it doesn't transport the <option>-#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>-#include</option> mechanism.
292 <sect3 id="finding-header-files">
293 <title>Finding Header files</title>
295 <para>Header files named by the <option>-#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>
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>
315 <title>Memory Allocation</title>
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>
326 <term><literal>alloca</literal> and friends</term>
328 <para>Useful for short-term allocation when the allocation
329 is intended to scope over a given <literal>IO</literal>
330 compuatation. This kind of allocation is commonly used
331 when marshalling data to and from FFI functions.</para>
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>
343 <term><literal>mallocForeignPtr</literal></term>
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>
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
364 <term><literal>malloc/free</literal></term>
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 funcitons 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>
379 <term><literal>Foreign.Marhsal.Pool</literal></term>
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 implementaiton of Pools in the
387 future, however.</para>
396 ;;; Local Variables: ***
398 ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") ***