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>The routines <literal>hs_init()</literal>,
15 <literal>hs_exit()</literal>, and <literal>hs_set_argv()</literal> from
16 Chapter 6.1 of the Addendum are not supported yet.</para>
20 <para>Syntactic forms and library functions proposed in earlier versions
21 of the FFI are still supported for backwards compatibility.</para>
25 <para>GHC implements a number of GHC-specific extensions to the FFI
26 Addendum. These extensions are described in <xref
27 linkend="sec-ffi-ghcexts">, but please note that programs using
28 these features are not portable. Hence, these features should be
29 avoided where possible.</para>
33 <para>The FFI libraries are documented in the accompanying library
34 documentation; see for example the <literal>Foreign</literal>
37 <sect1 id="sec-ffi-ghcexts">
38 <title>GHC extensions to the FFI Addendum</title>
40 <para>The FFI features that are described in this section are specific to
41 GHC. Avoid them where possible to not compromise the portability of the
42 resulting code.</para>
47 <para>The types <literal>ByteArray</literal> and
48 <literal>MutableByteArray</literal> may be used as basic foreign types
49 (see FFI Addendum, Section 3.2). In C land, they map to
50 <literal>(char *)</literal>.</para>
54 <title>Unboxed types</title>
56 <para>The following unboxed types may be used as basic foreign types
57 (see FFI Addendum, Section 3.2): <literal>Int#</literal>,
58 <literal>Word#</literal>, <literal>Char#</literal>,
59 <literal>Float#</literal>, <literal>Double#</literal>,
60 <literal>Addr#</literal>, <literal>StablePtr# a</literal>,
61 <literal>MutableByteArray#</literal>, <literal>ForeignObj#</literal>,
62 and <literal>ByteArray#</literal>.</para>
67 <sect1 id="sec-ffi-ghc">
68 <title>Using the FFI with GHC</title>
70 <para>The following sections also give some hints and tips on the
71 use of the foreign function interface in GHC.</para>
73 <sect2 id="foreign-export-ghc">
74 <title>Using <literal>foreign export</literal> and <literal>foreign
75 import ccall "wrapper"</literal> with GHC</title>
77 <indexterm><primary><literal>foreign export
78 </literal></primary><secondary>with GHC</secondary>
81 <para>When GHC compiles a module (say <filename>M.hs</filename>)
82 which uses <literal>foreign export</literal> or <literal>foreign
83 import "wrapper"</literal>, it generates two
84 additional files, <filename>M_stub.c</filename> and
85 <filename>M_stub.h</filename>. GHC will automatically compile
86 <filename>M_stub.c</filename> to generate
87 <filename>M_stub.o</filename> at the same time.</para>
89 <para>For a plain <literal>foreign export</literal>, the file
90 <filename>M_stub.h</filename> contains a C prototype for the
91 foreign exported function, and <filename>M_stub.c</filename>
92 contains its definition. For example, if we compile the
93 following module:</para>
98 foreign export ccall foo :: Int -> IO Int
101 foo n = return (length (f n))
105 f n = n:(f (n-1))</programlisting>
107 <para>Then <filename>Foo_stub.h</filename> will contain
108 something like this:</para>
112 extern HsInt foo(HsInt a0);</programlisting>
114 <para>and <filename>Foo_stub.c</filename> contains the
115 compiler-generated definition of <literal>foo()</literal>. To
116 invoke <literal>foo()</literal> from C, just <literal>#include
117 "Foo_stub.h"</literal> and call <literal>foo()</literal>.</para>
120 <title>Using your own <literal>main()</literal></title>
122 <para>Normally, GHC's runtime system provides a
123 <literal>main()</literal>, which arranges to invoke
124 <literal>Main.main</literal> in the Haskell program. However,
125 you might want to link some Haskell code into a program which
126 has a main function written in another languagem, say C. In
127 order to do this, you have to initialize the Haskell runtime
128 system explicitly.</para>
130 <para>Let's take the example from above, and invoke it from a
131 standalone C program. Here's the C code:</para>
134 #include <stdio.h>
137 #ifdef __GLASGOW_HASKELL__
138 #include "foo_stub.h"
141 #ifdef __GLASGOW_HASKELL__
142 extern void __stginit_Foo ( void );
145 int main(int argc, char *argv[])
149 hs_init(&argc, &argv);
150 #ifdef __GLASGOW_HASKELL__
151 hs_add_root(__stginit_Foo);
154 for (i = 0; i < 5; i++) {
155 printf("%d\n", foo(2500));
162 <para>We've surrounded the GHC-specific bits with
163 <literal>#ifdef __GLASGOW_HASKELL__</literal>; the rest of the
164 code should be portable across Haskell implementations that
165 support the FFI standard.</para>
167 <para>The call to <literal>hs_init()</literal>
168 initializes GHC's runtime system. Do NOT try to invoke any
169 Haskell functions before calling
170 <literal>hs_init()</literal>: strange things will
171 undoubtedly happen.</para>
173 <para>We pass <literal>argc</literal> and
174 <literal>argv</literal> to <literal>hs_init()</literal>
175 so that it can separate out any arguments for the RTS
176 (i.e. those arguments between
177 <literal>+RTS...-RTS</literal>).</para>
180 <function>hs_add_root</function><indexterm><primary><function>hs_add_root</function></primary>
181 </indexterm>, a GHC-specific interface which is required to
182 initialise the Haskell modules in the program. The argument
183 to <function>hs_add_root</function> should be the name of the
184 initialization function for the "root" module in your program
185 - in other words, the module which directly or indirectly
186 imports all the other Haskell modules in the program. In a
187 standalone Haskell program the root module is normally
188 <literal>Main</literal>, but when you are using Haskell code
189 from a library it may not be. If your program has multiple
190 root modules, then you can call
191 <function>hs_add_root</function> multiple times, one for each
192 root. The name of the initialization function for module
193 <replaceable>M</replaceable> is
194 <literal>__stginit_<replaceable>M</replaceable></literal>, and
195 it may be declared as an external function symbol as in the
198 <para>After we've finished invoking our Haskell functions, we
199 can call <literal>hs_exit()</literal>, which
200 terminates the RTS. It runs any outstanding finalizers and
201 generates any profiling or stats output that might have been
204 <para>There can be multiple calls to
205 <literal>hs_init()</literal>, but each one should be matched
206 by one (and only one) call to
207 <literal>hs_exit()</literal><footnote><para>The outermost
208 <literal>hs_exit()</literal> will actually de-initialise the
209 system. NOTE that currently GHC's runtime cannot reliably
210 re-initialise after this has happened.</para>
213 <para>NOTE: when linking the final program, it is normally
214 easiest to do the link using GHC, although this isn't
215 essential. If you do use GHC, then don't forget the flag
216 <option>-no-hs-main</option><indexterm><primary><option>-no-hs-main</option></primary>
217 </indexterm>, otherwise GHC will try to link
218 to the <literal>Main</literal> Haskell module.</para>
221 <sect3 id="foreign-export-dynamic-ghc">
222 <title>Using <literal>foreign import ccall "wrapper"</literal> with
225 <indexterm><primary><literal>foreign import
226 ccall "wrapper"</literal></primary><secondary>with GHC</secondary>
229 <para>When <literal>foreign import ccall "wrapper"</literal> is used
230 in a Haskell module, The C stub file <filename>M_stub.c</filename>
231 generated by GHC contains small helper functions used by the code
232 generated for the imported wrapper, so it must be linked in to the
233 final program. When linking the program, remember to include
234 <filename>M_stub.o</filename> in the final link command line, or
235 you'll get link errors for the missing function(s) (this isn't
236 necessary when building your program with <literal>ghc
237 ––make</literal>, as GHC will automatically link in the
238 correct bits).</para>
242 <sect2 id="glasgow-foreign-headers">
243 <title>Using function headers</title>
245 <indexterm><primary>C calls, function headers</primary></indexterm>
247 <para>When generating C (using the <option>-fvia-C</option>
248 directive), one can assist the C compiler in detecting type
249 errors by using the <option>-#include</option> directive
250 (<xref linkend="options-C-compiler">) to provide
251 <filename>.h</filename> files containing function
254 <para>For example,</para>
259 void initialiseEFS (HsInt size);
260 HsInt terminateEFS (void);
261 HsForeignObj emptyEFS(void);
262 HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x);
263 HsInt lookupEFS (HsForeignObj a, HsInt i);
266 <para>The types <literal>HsInt</literal>,
267 <literal>HsForeignObj</literal> etc. are described in the H98 FFI
270 <para>Note that this approach is only
271 <emphasis>essential</emphasis> for returning
272 <literal>float</literal>s (or if <literal>sizeof(int) !=
273 sizeof(int *)</literal> on your architecture) but is a Good
274 Thing for anyone who cares about writing solid code. You're
275 crazy not to do it.</para>
278 What if you are importing a module from another package, and
279 a cross-module inlining exposes a foreign call that needs a supporting
280 <option>-#include</option>? If the imported module is from the same package as
281 the module being compiled, you should supply all the <option>-#include</option>
282 that you supplied when compiling the imported module. If the imported module comes
283 from another package, you won't necessarily know what the appropriate
284 <option>-#include</option> options are; but they should be in the package
285 configuration, which GHC knows about. So if you are building a package, remember
286 to put all those <option>-#include</option> options into the package configuration.
287 See the <literal>c_includes</literal> field in <xref linkend="package-management">.
291 It is also possible, according the FFI specification, to put the
292 <option>-#include</option> option in the foreign import
295 foreign import "foo.h f" f :: Int -> IO Int
297 When compiling this module, GHC will generate a C file that includes
298 the specified <option>-#include</option>. However, GHC
299 <emphasis>disables</emphasis> cross-module inlinding for such foreign
300 calls, because it doesn't transport the <option>-#include</option>
301 information across module boundaries. (There is no fundamental reason for this;
302 it was just tiresome to implement. The wrapper, which unboxes the arguments
303 etc, is still inlined across modules.) So if you want the foreign call itself
304 to be inlined across modules, use the command-line and package-configuration
305 <option>-#include</option> mechanism.
313 ;;; Local Variables: ***
315 ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter") ***