ffi-chap.sgml 7.68 KB
Newer Older
rrt's avatar
rrt committed
1 2 3
<!-- FFI docs as a chapter -->

<Chapter id="ffi">
rrt's avatar
rrt committed
4
<Title>Foreign function interface</Title>
5

6 7
  <para>The foreign function interface consists of the following
  components:</para>
8 9 10 11 12 13 14 15 16 17 18 19

  <itemizedlist>
    <listitem>
      <para>The Foreign Function Interface language specification
      (which constitutes most of this Chapter, beginning with <xref
      linkend="sec-ffi-intro">).  You must use the
      <option>-fglasgow-exts</option> command-line option to make GHC
      understand the <literal>foreign</literal> declarations defined
      by the FFI.</para>
    </listitem>

    <listitem>
20 21 22 23 24
      <para>Several library modules which provide access to types used
      by foreign languages and utilties for marshalling values to and
      from foreign functions, and for converting errors in the foreign
      language into Haskell IO errors.  See <xref linkend="sec-Foreign"> for
      more details.  </para>
25 26 27
    </listitem>
  </itemizedlist>

rrt's avatar
rrt committed
28
&ffi-body;
29 30 31 32 33 34 35

  <sect1 id="ffi-ghc">
    <title>Using the FFI with GHC</title>

    <para>The following sections also give some hints and tips on the
    use of the foreign function interface in GHC.</para>

36 37
    <sect2 id="foreign-export-ghc">
      <title>Using <literal>foreign export</literal> with GHC</title>
38 39

      <indexterm><primary><literal>foreign export
40
      </literal></primary><secondary>with GHC</secondary>
41 42 43
      </indexterm>

      <para>When GHC compiles a module (say <filename>M.hs</filename>)
44 45 46 47 48
      which uses <literal>foreign export</literal> or <literal>foreign
      export dynamic</literal>, it generates two
      additional files, <filename>M_stub.c</filename> and
      <filename>M_stub.h</filename>.  GHC will automatically compile
      <filename>M_stub.c</filename> to generate
49 50
      <filename>M_stub.o</filename> at the same time.</para>

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
      <para>For a plain <literal>foreign export</literal>, the file
      <filename>M_stub.h</filename> contains a C prototype for the
      foreign exported function, and <filename>M_stub.c</filename>
      contains its definition.  For example, if we compile the
      following module:</para>

<programlisting>
module Foo where

foreign export foo :: Int -> IO Int

foo :: Int -> IO Int
foo n = return (length (f n))

f :: Int -> [Int]
f 0 = []
f n = n:(f (n-1))</programlisting>

      <para>Then <filename>Foo_stub.h</filename> will contain
      something like this:</para>

<programlisting>
#include "HsFFI.h"
extern HsInt foo(HsInt a0);</programlisting>

      <para>and <filename>Foo_stub.c</filename> contains the
      compiler-generated definition of <literal>foo()</literal>.  To
      invoke <literal>foo()</literal> from C, just <literal>#include
      "Foo_stub.h"</literal> and call <literal>foo()</literal>.</para>

      <sect3> 
	<title>Using your own <literal>main()</literal></title>

	<para>Normally, GHC's runtime system provides a
	<literal>main()</literal>, which arranges to invoke
	<literal>Main.main</literal> in the Haskell program.  However,
	you might want to link some Haskell code into a program which
	has a main function written in another languagem, say C.  In
	order to do this, you have to initialize the Haskell runtime
	system explicitly.</para>

	<para>Let's take the example from above, and invoke it from a
	standalone C program.  Here's the C code:</para>

<programlisting>
#include &lt;stdio.h&gt;
#include "foo_stub.h"

#include "RtsAPI.h"

extern void __stginit_Foo ( void );

int main(int argc, char *argv[])
{
  int i;

  startupHaskell(argc, argv, __stginit_Foo);

  for (i = 0; i < 5; i++) {
    printf("%d\n", foo(2500));
  }

  shutdownHaskell();

  return 0;
}</programlisting>

	<para>The call to <literal>startupHaskell()</literal>
	initializes GHC's runtime system.  Do NOT try to invoke any
	Haskell functions before calling
	<literal>startupHaskell()</literal>: strange things will
	undoubtedly happen.</para>

	<para>We pass <literal>argc</literal> and
	<literal>argv</literal> to <literal>startupHaskell()</literal>
	so that it can separate out any arguments for the RTS
	(i.e. those arguments between
	<literal>+RTS...-RTS</literal>).</para>

	<para>The third argument to <literal>startupHaskell()</literal>
	is used for initializing the Haskell modules in the program.
	It must be the name of the initialization function for the
	"top" module in the program/library - in other words, the
	module which directly or indirectly imports all the other
	Haskell modules in the program.  In a standalone Haskell
	program this would be module <literal>Main</literal>, but when
	you are only using the Haskell code as a library it may not
	be.  If your library doesn't have such a module, then it is
	straightforward to create one, purely for this initialization
	process.  The name of the initialization function for module
	<replaceable>M</replaceable> is
	<literal>__stginit_<replaceable>M</replaceable></literal>, and
	it may be declared as an external function symbol as in the
	code above.</para>

	<para>After we've finished invoking our Haskell functions, we
	can call <literal>shutdownHaskell()</literal>, which
	terminates the RTS.  It runs any outstanding finalizers and
	generates any profiling or stats output that might have been
	requested.</para>

	<para>The functions <literal>startupHaskell()</literal> and
	<literal>shutdownHaskell()</literal> may be called only once
	each, and only in that order.</para>
      </sect3>

      <sect3 id="foreign-export-dynamic-ghc">
	<title>Using <literal>foreign export dynamic</literal> with
	GHC</title>

	<indexterm><primary><literal>foreign export
	dynamic</literal></primary><secondary>with GHC</secondary>
	</indexterm>

	<para>When <literal>foreign export dynamic</literal> is used
        in a Haskell module, The C stub file
        <filename>M_stub.c</filename> generated by GHC contains small
        helper functions used by the code generated for the
        <literal>foreign export dynamic</literal>, so it must be
        linked in to the final program.  When linking the program,
        remember to include <filename>M_stub.o</filename> in the final
        link command line, or you'll get link errors for the missing
        function(s) (this isn't necessary when building your program
        with <literal>ghc --make</literal>, as GHC will automatically
        link in the correct bits).</para>
      </sect3>
177
    </sect2>
178
    
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    <sect2 id="glasgow-foreign-headers">
      <title>Using function headers</title>

      <indexterm><primary>C calls, function headers</primary></indexterm>

      <para>When generating C (using the <option>-fvia-C</option>

      directive), one can assist the C compiler in detecting type
      errors by using the <option>-&num;include</option> directive
      (<xref linkend="options-C-compiler">) to provide
      <filename>.h</filename> files containing function
      headers.</para>

      <para>For example,</para>

<programlisting>
#include "HsFFI.h"

void         initialiseEFS (HsInt size);
HsInt        terminateEFS (void);
HsForeignObj emptyEFS(void);
HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x);
HsInt        lookupEFS (HsForeignObj a, HsInt i);
</programlisting>

      <para>The types <literal>HsInt</literal>,
      <literal>HsForeignObj</literal> etc. are described in <xref
      linkend="sec-ffi-mapping-table">.</para>

      <para>Note that this approach is only
      <emphasis>essential</emphasis> for returning
      <literal>float</literal>s (or if <literal>sizeof(int) !=
      sizeof(int *)</literal> on your architecture) but is a Good
      Thing for anyone who cares about writing solid code.  You're
      crazy not to do it.</para>

    </sect2>
  </sect1>
rrt's avatar
rrt committed
217
</Chapter>
218 219 220 221 222 223 224

<!-- Emacs stuff:
     ;;; Local Variables: ***
     ;;; mode: sgml ***
     ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter") ***
     ;;; End: ***
 -->