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

<Chapter id="ffi">
chak's avatar
chak committed
4
<Title>Foreign function interface (FFI)</Title>
5

chak's avatar
chak committed
6 7 8 9 10
  <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>
11 12 13

  <itemizedlist>
    <listitem>
chak's avatar
chak committed
14 15 16
      <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>
17 18 19
    </listitem>

    <listitem>
chak's avatar
chak committed
20 21 22 23 24 25 26 27 28 29
      <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>
30 31 32
    </listitem>
  </itemizedlist>

33 34 35
  <para>The FFI libraries are documented in the accompanying library
  documentation; see for example the <literal>Foreign</literal>
  module.</para>
chak's avatar
chak committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

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

chak's avatar
chak committed
67
  <sect1 id="sec-ffi-ghc">
68 69 70 71 72
    <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>

73
    <sect2 id="foreign-export-ghc">
chak's avatar
chak committed
74 75
      <title>Using <literal>foreign export</literal> and <literal>foreign
      import ccall "wrapper"</literal> with GHC</title>
76 77

      <indexterm><primary><literal>foreign export
78
      </literal></primary><secondary>with GHC</secondary>
79 80 81
      </indexterm>

      <para>When GHC compiles a module (say <filename>M.hs</filename>)
82
      which uses <literal>foreign export</literal> or <literal>foreign
chak's avatar
chak committed
83
      import "wrapper"</literal>, it generates two
84 85 86
      additional files, <filename>M_stub.c</filename> and
      <filename>M_stub.h</filename>.  GHC will automatically compile
      <filename>M_stub.c</filename> to generate
87 88
      <filename>M_stub.o</filename> at the same time.</para>

89 90 91 92 93 94 95 96 97
      <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

chak's avatar
chak committed
98
foreign export ccall foo :: Int -> IO Int
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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

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>
193 194 195 196 197 198 199

	<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>
200 201 202
      </sect3>

      <sect3 id="foreign-export-dynamic-ghc">
chak's avatar
chak committed
203
	<title>Using <literal>foreign import ccall "wrapper"</literal> with
204 205
	GHC</title>

chak's avatar
chak committed
206 207
	<indexterm><primary><literal>foreign import
	ccall "wrapper"</literal></primary><secondary>with GHC</secondary>
208 209
	</indexterm>

chak's avatar
chak committed
210 211 212 213 214 215 216 217 218 219
	<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>
220
      </sect3>
221
    </sect2>
222
    
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    <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>,
chak's avatar
chak committed
249 250
      <literal>HsForeignObj</literal> etc. are described in the H98 FFI
      Addendum.</para>
251 252 253 254 255 256 257 258 259 260

      <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
261
</Chapter>
262 263 264 265 266 267 268

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