[project @ 2002-05-15 08:59:58 by chak]
[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>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>
17     </listitem>
18
19     <listitem>
20       <para>Syntactic forms and library functions proposed in earlier versions
21       of the FFI are still supported for backwards compatibility.</para>
22     </listitem>
23
24     <listitem>
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>
30     </listitem>
31   </itemizedlist>
32
33   <para>The FFI libraries are documented in <xref
34   linkend="sec-Foreign">.</para>
35
36
37   <sect1 id="sec-ffi-ghcexts">
38     <title>GHC extensions to the FFI Addendum</title>
39
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>
43
44     <sect2>
45       <title>Arrays</title>
46
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>
51     </sect2>
52
53     <sect2>
54       <title>Unboxed types</title>
55
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>
63     </sect2>
64
65   </sect1>
66
67   <sect1 id="sec-ffi-ghc">
68     <title>Using the FFI with GHC</title>
69
70     <para>The following sections also give some hints and tips on the
71     use of the foreign function interface in GHC.</para>
72
73     <sect2 id="foreign-export-ghc">
74       <title>Using <literal>foreign export</literal> and <literal>foreign
75       import ccall "wrapper"</literal> with GHC</title>
76
77       <indexterm><primary><literal>foreign export
78       </literal></primary><secondary>with GHC</secondary>
79       </indexterm>
80
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>
88
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>
94
95 <programlisting>
96 module Foo where
97
98 foreign export ccall foo :: Int -> IO Int
99
100 foo :: Int -> IO Int
101 foo n = return (length (f n))
102
103 f :: Int -> [Int]
104 f 0 = []
105 f n = n:(f (n-1))</programlisting>
106
107       <para>Then <filename>Foo_stub.h</filename> will contain
108       something like this:</para>
109
110 <programlisting>
111 #include "HsFFI.h"
112 extern HsInt foo(HsInt a0);</programlisting>
113
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>
118
119       <sect3> 
120         <title>Using your own <literal>main()</literal></title>
121
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>
129
130         <para>Let's take the example from above, and invoke it from a
131         standalone C program.  Here's the C code:</para>
132
133 <programlisting>
134 #include &lt;stdio.h&gt;
135 #include "foo_stub.h"
136
137 #include "RtsAPI.h"
138
139 extern void __stginit_Foo ( void );
140
141 int main(int argc, char *argv[])
142 {
143   int i;
144
145   startupHaskell(argc, argv, __stginit_Foo);
146
147   for (i = 0; i < 5; i++) {
148     printf("%d\n", foo(2500));
149   }
150
151   shutdownHaskell();
152
153   return 0;
154 }</programlisting>
155
156         <para>The call to <literal>startupHaskell()</literal>
157         initializes GHC's runtime system.  Do NOT try to invoke any
158         Haskell functions before calling
159         <literal>startupHaskell()</literal>: strange things will
160         undoubtedly happen.</para>
161
162         <para>We pass <literal>argc</literal> and
163         <literal>argv</literal> to <literal>startupHaskell()</literal>
164         so that it can separate out any arguments for the RTS
165         (i.e. those arguments between
166         <literal>+RTS...-RTS</literal>).</para>
167
168         <para>The third argument to <literal>startupHaskell()</literal>
169         is used for initializing the Haskell modules in the program.
170         It must be the name of the initialization function for the
171         "top" module in the program/library - in other words, the
172         module which directly or indirectly imports all the other
173         Haskell modules in the program.  In a standalone Haskell
174         program this would be module <literal>Main</literal>, but when
175         you are only using the Haskell code as a library it may not
176         be.  If your library doesn't have such a module, then it is
177         straightforward to create one, purely for this initialization
178         process.  The name of the initialization function for module
179         <replaceable>M</replaceable> is
180         <literal>__stginit_<replaceable>M</replaceable></literal>, and
181         it may be declared as an external function symbol as in the
182         code above.</para>
183
184         <para>After we've finished invoking our Haskell functions, we
185         can call <literal>shutdownHaskell()</literal>, which
186         terminates the RTS.  It runs any outstanding finalizers and
187         generates any profiling or stats output that might have been
188         requested.</para>
189
190         <para>The functions <literal>startupHaskell()</literal> and
191         <literal>shutdownHaskell()</literal> may be called only once
192         each, and only in that order.</para>
193
194         <para>NOTE: when linking the final program, it is normally
195         easiest to do the link using GHC, although this isn't
196         essential.  If you do use GHC, then don't forget the flag
197         <option>-no-hs-main</option><indexterm><primary><option>-no-hs-main</option></primary>
198           </indexterm>, otherwise GHC will try to link
199         to the <literal>Main</literal> Haskell module.</para>
200       </sect3>
201
202       <sect3 id="foreign-export-dynamic-ghc">
203         <title>Using <literal>foreign import ccall "wrapper"</literal> with
204         GHC</title>
205
206         <indexterm><primary><literal>foreign import
207         ccall "wrapper"</literal></primary><secondary>with GHC</secondary>
208         </indexterm>
209
210         <para>When <literal>foreign import ccall "wrapper"</literal> is used
211         in a Haskell module, The C stub file <filename>M_stub.c</filename>
212         generated by GHC contains small helper functions used by the code
213         generated for the imported wrapper, so it must be linked in to the
214         final program.  When linking the program, remember to include
215         <filename>M_stub.o</filename> in the final link command line, or
216         you'll get link errors for the missing function(s) (this isn't
217         necessary when building your program with <literal>ghc
218         &ndash;&ndash;make</literal>, as GHC will automatically link in the
219         correct bits).</para>
220       </sect3>
221     </sect2>
222     
223     <sect2 id="glasgow-foreign-headers">
224       <title>Using function headers</title>
225
226       <indexterm><primary>C calls, function headers</primary></indexterm>
227
228       <para>When generating C (using the <option>-fvia-C</option>
229
230       directive), one can assist the C compiler in detecting type
231       errors by using the <option>-&num;include</option> directive
232       (<xref linkend="options-C-compiler">) to provide
233       <filename>.h</filename> files containing function
234       headers.</para>
235
236       <para>For example,</para>
237
238 <programlisting>
239 #include "HsFFI.h"
240
241 void         initialiseEFS (HsInt size);
242 HsInt        terminateEFS (void);
243 HsForeignObj emptyEFS(void);
244 HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x);
245 HsInt        lookupEFS (HsForeignObj a, HsInt i);
246 </programlisting>
247
248       <para>The types <literal>HsInt</literal>,
249       <literal>HsForeignObj</literal> etc. are described in the H98 FFI
250       Addendum.</para>
251
252       <para>Note that this approach is only
253       <emphasis>essential</emphasis> for returning
254       <literal>float</literal>s (or if <literal>sizeof(int) !=
255       sizeof(int *)</literal> on your architecture) but is a Good
256       Thing for anyone who cares about writing solid code.  You're
257       crazy not to do it.</para>
258
259     </sect2>
260   </sect1>
261 </Chapter>
262
263 <!-- Emacs stuff:
264      ;;; Local Variables: ***
265      ;;; mode: sgml ***
266      ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter") ***
267      ;;; End: ***
268  -->