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
60 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 <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>
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
210 <indexterm><primary><literal>foreign import
211 ccall "wrapper"</literal></primary><secondary>with GHC</secondary>
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 ––make</literal>, as GHC will automatically link in the
223 correct bits).</para>
227 <sect2 id="glasgow-foreign-headers">
228 <title>Using function headers</title>
230 <indexterm><primary>C calls, function headers</primary></indexterm>
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>-#include</option> directive
235 (<xref linkend="options-C-compiler">) to provide
236 <filename>.h</filename> files containing function
239 <para>For example,</para>
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);
251 <para>The types <literal>HsInt</literal>,
252 <literal>HsForeignObj</literal> etc. are described in the H98 FFI
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>
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>-#include</option>? If the imported module is from the same package as
266 the module being compiled, you should supply all the <option>-#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>-#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>-#include</option> options into the package configuration.
272 See the <literal>c_includes</literal> field in <xref linkend="package-management">.
276 It is also possible, according the FFI specification, to put the
277 <option>-#include</option> option in the foreign import
280 foreign import "foo.h f" f :: Int -> IO Int
282 When compiling this module, GHC will generate a C file that includes
283 the specified <option>-#include</option>. However, GHC
284 <emphasis>disables</emphasis> cross-module inlinding for such foreign
285 calls, because it doesn't transport the <option>-#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>-#include</option> mechanism.
296 <title>Memory Allocation</title>
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>
307 <term><literal>alloca</literal> and friends</term>
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>
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>
324 <term><literal>mallocForeignPtr</literal></term>
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>
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
345 <term><literal>malloc/free</literal></term>
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>
360 <term><literal>Foreign.Marhsal.Pool</literal></term>
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>
377 ;;; Local Variables: ***
379 ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter") ***