1 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
4 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
5 <title>The GHC Commentary - Alien Functions</title>
8 <body BGCOLOR="FFFFFF">
9 <h1>The GHC Commentary - Alien Functions</h1>
11 GHC implements experimental (by now it is actually quite well tested)
12 support for access to foreign functions and generally the interaction
13 between Haskell code and code written in other languages. Code
14 generation in this context can get quite tricky. This section attempts
15 to cast some light on this aspect of the compiler.
17 <h4>FFI Stub Files</h4>
19 For each Haskell module that contains a <code>foreign export
20 dynamic</code> declaration, GHC generates a <code>_stub.c</code> file
21 that needs to be linked with any program that imports the Haskell
22 module. When asked about it <a
23 href="mailto:simonmar@microsoft.com">Simon Marlow</a> justified the
24 existence of these files as follows:
26 The stub files contain the helper function which invokes the Haskell
27 code when called from C.
29 Each time the foreign export dynamic is invoked to create a new
30 callback function, a small piece of code has to be dynamically
31 generated (by code in <a
32 href="http://cvs.haskell.org/cgi-bin/cvsweb.cgi/fptools/ghc/rts/Adjustor.c"><code>Adjustor.c</code></a>). It is the address of this dynamically generated bit of
33 code that is returned as the <code>Addr</code> (or <a
34 href="http://cvs.haskell.org/cgi-bin/cvsweb.cgi/fptools/hslibs/lang/Ptr.lhs"><code>Ptr</code></a>).
35 When called from C, the dynamically generated code must somehow invoke
36 the Haskell function which was originally passed to the
37 f.e.d. function -- it does this by invoking the helper function,
39 href="http://cvs.haskell.org/cgi-bin/cvsweb.cgi/fptools/hslibs/lang/StablePtr.lhs"><code>StablePtr</code></a>
40 to the Haskell function. It's split this way for two reasons: the
41 same helper function can be used each time the f.e.d. function is
42 called, and to keep the amount of dynamically generated code to a
46 The stub code is generated by <a
47 href="http://cvs.haskell.org/cgi-bin/cvsweb.cgi/fptools/ghc/compiler/deSugar/DsForeign.lhs"><code>DSForeign</code></a><code>.fexportEntry</code>.
52 Last modified: Fri Aug 10 11:47:41 EST 2001