<!-- FFI docs as a chapter -->

<Chapter id="ffi">
<Title>Foreign function interface (FFI)</Title>

  <para>GHC (mostly) conforms to the Haskell 98 Foreign Function Interface
  Addendum 1.0, whose definition is available from <ULink
  URL="http://haskell.org/"><literal>http://haskell.org/</literal></ULink >.
  The FFI support in GHC diverges from the Addendum in the following ways:
  </para>

  <itemizedlist>
    <listitem>
      <para>The routines <literal>hs_init()</literal>,
      <literal>hs_exit()</literal>, and <literal>hs_set_argv()</literal> from
      Chapter 6.1 of the Addendum are not supported yet.</para>
    </listitem>

    <listitem>
      <para>Syntactic forms and library functions proposed in earlier versions
      of the FFI are still supported for backwards compatibility.</para>
    </listitem>

    <listitem>
      <para>GHC implements a number of GHC-specific extensions to the FFI
      Addendum.  These extensions are described in <xref
      linkend="sec-ffi-ghcexts">, but please note that programs using
      these features are not portable.  Hence, these features should be
      avoided where possible.</para>
    </listitem>
  </itemizedlist>

  <para>The FFI libraries are documented in the accompanying library
  documentation; see for example the <literal>Foreign</literal>
  module.</para>

  <sect1 id="sec-ffi-ghcexts">
    <title>GHC extensions to the FFI Addendum</title>

    <para>The FFI features that are described in this section are specific to
    GHC.  Avoid them where possible to not compromise the portability of the
    resulting code.</para>

    <sect2>
      <title>Arrays</title>

      <para>The types <literal>ByteArray</literal> and
      <literal>MutableByteArray</literal> may be used as basic foreign types
      (see FFI Addendum, Section 3.2).  In C land, they map to
      <literal>(char *)</literal>.</para>
    </sect2>

    <sect2>
      <title>Unboxed types</title>

      <para>The following unboxed types may be used as basic foreign types
      (see FFI Addendum, Section 3.2): <literal>Int#</literal>,
      <literal>Word#</literal>, <literal>Char#</literal>,
      <literal>Float#</literal>, <literal>Double#</literal>,
      <literal>Addr#</literal>, <literal>StablePtr# a</literal>,
      <literal>MutableByteArray#</literal>, <literal>ForeignObj#</literal>,
      and <literal>ByteArray#</literal>.</para>
    </sect2>

  </sect1>

  <sect1 id="sec-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>

    <sect2 id="foreign-export-ghc">
      <title>Using <literal>foreign export</literal> and <literal>foreign
      import ccall "wrapper"</literal> with GHC</title>

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

      <para>When GHC compiles a module (say <filename>M.hs</filename>)
      which uses <literal>foreign export</literal> or <literal>foreign
      import "wrapper"</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
      <filename>M_stub.o</filename> at the same time.</para>

      <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 ccall 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>

	<para>NOTE: when linking the final program, it is normally
	easiest to do the link using GHC, although this isn't
	essential.  If you do use GHC, then don't forget the flag
	<option>-no-hs-main</option><indexterm><primary><option>-no-hs-main</option></primary>
	  </indexterm>, otherwise GHC will try to link
	to the <literal>Main</literal> Haskell module.</para>
      </sect3>

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

	<indexterm><primary><literal>foreign import
	ccall "wrapper"</literal></primary><secondary>with GHC</secondary>
	</indexterm>

	<para>When <literal>foreign import ccall "wrapper"</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 imported wrapper, 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
        &ndash;&ndash;make</literal>, as GHC will automatically link in the
        correct bits).</para>
      </sect3>
    </sect2>
    
    <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 the H98 FFI
      Addendum.</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>
</Chapter>

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