[project @ 2001-09-14 15:56:40 by simonmar]
[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</Title>
5
6   <para>The foreign interface consists of the following components:</para>
7
8   <itemizedlist>
9     <listitem>
10       <para>The Foreign Function Interface language specification
11       (which constitutes most of this Chapter, beginning with <xref
12       linkend="sec-ffi-intro">).  You must use the
13       <option>-fglasgow-exts</option> command-line option to make GHC
14       understand the <literal>foreign</literal> declarations defined
15       by the FFI.</para>
16     </listitem>
17
18     <listitem>
19       <para>The <literal>Foreign</literal> module (see <xref
20       linkend="sec-Foreign">) collects together several interfaces
21       which are useful in specifying foreign language interfaces,
22       including the following:</para>
23
24       <itemizedlist>
25         <listitem>
26           <para>The <literal>ForeignObj</literal> module (see <xref
27           linkend="sec-ForeignObj">), for managing pointers from
28           Haskell into the outside world.</para>
29         </listitem>
30         
31         <listitem>
32           <para>The <literal>StablePtr</literal> module (see <xref
33           linkend="sec-stable-pointers">), for managing pointers into
34           Haskell from the outside world.</para>
35         </listitem>
36       
37         <listitem>
38           <para>The <literal>CTypes</literal> module (see <xref
39           linkend="sec-CTypes">) gives Haskell equivalents for the
40           standard C datatypes, for use in making Haskell bindings to
41           existing C libraries.</para>
42         </listitem>
43       
44         <listitem>
45           <para>The <literal>CTypesISO</literal> module (see <xref
46           linkend="sec-CTypesISO">) gives Haskell equivalents for C
47           types defined by the ISO C standard.</para>
48         </listitem>
49         
50         <listitem>
51           <para>The <literal>Storable</literal> library, for primitive
52           marshalling of data types between Haskell and the foreign
53           language.</para>
54         </listitem>
55       </itemizedlist>
56       
57     </listitem>
58   </itemizedlist>
59
60 &ffi-body;
61
62   <sect1 id="ffi-ghc">
63     <title>Using the FFI with GHC</title>
64
65     <para>The following sections also give some hints and tips on the
66     use of the foreign function interface in GHC.</para>
67
68     <sect2 id="foreign-export-ghc">
69       <title>Using <literal>foreign export</literal> with GHC</title>
70
71       <indexterm><primary><literal>foreign export
72       </literal></primary><secondary>with GHC</secondary>
73       </indexterm>
74
75       <para>When GHC compiles a module (say <filename>M.hs</filename>)
76       which uses <literal>foreign export</literal> or <literal>foreign
77       export dynamic</literal>, it generates two
78       additional files, <filename>M_stub.c</filename> and
79       <filename>M_stub.h</filename>.  GHC will automatically compile
80       <filename>M_stub.c</filename> to generate
81       <filename>M_stub.o</filename> at the same time.</para>
82
83       <para>For a plain <literal>foreign export</literal>, the file
84       <filename>M_stub.h</filename> contains a C prototype for the
85       foreign exported function, and <filename>M_stub.c</filename>
86       contains its definition.  For example, if we compile the
87       following module:</para>
88
89 <programlisting>
90 module Foo where
91
92 foreign export foo :: Int -> IO Int
93
94 foo :: Int -> IO Int
95 foo n = return (length (f n))
96
97 f :: Int -> [Int]
98 f 0 = []
99 f n = n:(f (n-1))</programlisting>
100
101       <para>Then <filename>Foo_stub.h</filename> will contain
102       something like this:</para>
103
104 <programlisting>
105 #include "HsFFI.h"
106 extern HsInt foo(HsInt a0);</programlisting>
107
108       <para>and <filename>Foo_stub.c</filename> contains the
109       compiler-generated definition of <literal>foo()</literal>.  To
110       invoke <literal>foo()</literal> from C, just <literal>#include
111       "Foo_stub.h"</literal> and call <literal>foo()</literal>.</para>
112
113       <sect3> 
114         <title>Using your own <literal>main()</literal></title>
115
116         <para>Normally, GHC's runtime system provides a
117         <literal>main()</literal>, which arranges to invoke
118         <literal>Main.main</literal> in the Haskell program.  However,
119         you might want to link some Haskell code into a program which
120         has a main function written in another languagem, say C.  In
121         order to do this, you have to initialize the Haskell runtime
122         system explicitly.</para>
123
124         <para>Let's take the example from above, and invoke it from a
125         standalone C program.  Here's the C code:</para>
126
127 <programlisting>
128 #include &lt;stdio.h&gt;
129 #include "foo_stub.h"
130
131 #include "RtsAPI.h"
132
133 extern void __stginit_Foo ( void );
134
135 int main(int argc, char *argv[])
136 {
137   int i;
138
139   startupHaskell(argc, argv, __stginit_Foo);
140
141   for (i = 0; i < 5; i++) {
142     printf("%d\n", foo(2500));
143   }
144
145   shutdownHaskell();
146
147   return 0;
148 }</programlisting>
149
150         <para>The call to <literal>startupHaskell()</literal>
151         initializes GHC's runtime system.  Do NOT try to invoke any
152         Haskell functions before calling
153         <literal>startupHaskell()</literal>: strange things will
154         undoubtedly happen.</para>
155
156         <para>We pass <literal>argc</literal> and
157         <literal>argv</literal> to <literal>startupHaskell()</literal>
158         so that it can separate out any arguments for the RTS
159         (i.e. those arguments between
160         <literal>+RTS...-RTS</literal>).</para>
161
162         <para>The third argument to <literal>startupHaskell()</literal>
163         is used for initializing the Haskell modules in the program.
164         It must be the name of the initialization function for the
165         "top" module in the program/library - in other words, the
166         module which directly or indirectly imports all the other
167         Haskell modules in the program.  In a standalone Haskell
168         program this would be module <literal>Main</literal>, but when
169         you are only using the Haskell code as a library it may not
170         be.  If your library doesn't have such a module, then it is
171         straightforward to create one, purely for this initialization
172         process.  The name of the initialization function for module
173         <replaceable>M</replaceable> is
174         <literal>__stginit_<replaceable>M</replaceable></literal>, and
175         it may be declared as an external function symbol as in the
176         code above.</para>
177
178         <para>After we've finished invoking our Haskell functions, we
179         can call <literal>shutdownHaskell()</literal>, which
180         terminates the RTS.  It runs any outstanding finalizers and
181         generates any profiling or stats output that might have been
182         requested.</para>
183
184         <para>The functions <literal>startupHaskell()</literal> and
185         <literal>shutdownHaskell()</literal> may be called only once
186         each, and only in that order.</para>
187       </sect3>
188
189       <sect3 id="foreign-export-dynamic-ghc">
190         <title>Using <literal>foreign export dynamic</literal> with
191         GHC</title>
192
193         <indexterm><primary><literal>foreign export
194         dynamic</literal></primary><secondary>with GHC</secondary>
195         </indexterm>
196
197         <para>When <literal>foreign export dynamic</literal> is used
198         in a Haskell module, The C stub file
199         <filename>M_stub.c</filename> generated by GHC contains small
200         helper functions used by the code generated for the
201         <literal>foreign export dynamic</literal>, so it must be
202         linked in to the final program.  When linking the program,
203         remember to include <filename>M_stub.o</filename> in the final
204         link command line, or you'll get link errors for the missing
205         function(s) (this isn't necessary when building your program
206         with <literal>ghc --make</literal>, as GHC will automatically
207         link in the correct bits).</para>
208       </sect3>
209     </sect2>
210     
211     <sect2 id="glasgow-foreign-headers">
212       <title>Using function headers</title>
213
214       <indexterm><primary>C calls, function headers</primary></indexterm>
215
216       <para>When generating C (using the <option>-fvia-C</option>
217
218       directive), one can assist the C compiler in detecting type
219       errors by using the <option>-&num;include</option> directive
220       (<xref linkend="options-C-compiler">) to provide
221       <filename>.h</filename> files containing function
222       headers.</para>
223
224       <para>For example,</para>
225
226 <programlisting>
227 #include "HsFFI.h"
228
229 void         initialiseEFS (HsInt size);
230 HsInt        terminateEFS (void);
231 HsForeignObj emptyEFS(void);
232 HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x);
233 HsInt        lookupEFS (HsForeignObj a, HsInt i);
234 </programlisting>
235
236       <para>The types <literal>HsInt</literal>,
237       <literal>HsForeignObj</literal> etc. are described in <xref
238       linkend="sec-ffi-mapping-table">.</para>
239
240       <para>Note that this approach is only
241       <emphasis>essential</emphasis> for returning
242       <literal>float</literal>s (or if <literal>sizeof(int) !=
243       sizeof(int *)</literal> on your architecture) but is a Good
244       Thing for anyone who cares about writing solid code.  You're
245       crazy not to do it.</para>
246
247     </sect2>
248   </sect1>
249 </Chapter>
250
251 <!-- Emacs stuff:
252      ;;; Local Variables: ***
253      ;;; mode: sgml ***
254      ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter") ***
255      ;;; End: ***
256  -->