1 <!DOCTYPE Article PUBLIC "-//OASIS//DTD DocBook V3.1//EN">
7 <Title>A Haskell foreign function interface</Title>
8 <Author><OtherName>The GHC Team</OtherName></Author>
9 <Address><Email>glasgow-haskell-{users,bugs}@dcs.gla.ac.uk</Email>
11 <Edition>version 0.99</Edition>
12 <PubDate>May 2000</PubDate>
16 <Sect1 id="sec-intro">
21 The motivation behind this foreign function interface(FFI)
22 specification is to make it possible to describe in Haskell <Emphasis>source
23 code</Emphasis> the interface to foreign functionality in a Haskell system
24 independent manner. It builds on experiences made with the previous
25 foreign function interfaces provided by GHC and Hugs.
29 The FFI specified in this document is not in the market of trying to
30 completely bridge the gap between the actual type of an external
31 function, and what is a <Emphasis>convenient</Emphasis> type for that function to the
32 Haskell programmer. That is the domain of tools like HaskellDirect or
33 Green Card, both of which are capable of generating Haskell code that
38 The FFI can be split up into two complementary halves; one half that
39 provides Haskell constructs for importing foreign functionality into
40 Haskell, the other which lets you expose Haskell functions to the
41 outside world. We start with the former, how to import external
42 functionality into Haskell.
47 <Sect1 id="sec-primitive">
48 <Title>Calling foreign functions
52 To bind a Haskell variable name and type to an external function, we
53 introduce a new construct: <Literal>foreign import</Literal>. It defines the type of a Haskell function together with the name of an external function that actually implements it. The syntax of <Literal>foreign import</Literal> construct is as follows:
62 | 'foreign' 'import' [callconv] [ext_fun] ['unsafe'] varid '::' prim_type
68 A <Literal>foreign import</Literal> declaration is only allowed as a toplevel
69 declaration. It consists of two parts, one giving the Haskell type
70 (<Literal>prim_type</Literal>), Haskell name (<Literal>varid</Literal>) and a flag indicating whether the
71 primitive is unsafe, the other giving details of the name of the
72 external function (<Literal>ext_fun</Literal>) and its calling interface
73 (<Literal>callconv</Literal>.)
77 Giving a Haskell name and type to an external entry point is clearly
78 an unsafe thing to do, as the external name will in most cases be
79 untyped. The onus is on the programmer using <Literal>foreign import</Literal> to
80 ensure that the Haskell type given correctly maps on to the
81 type of the external function. Section
82 <XRef LinkEnd="sec-mapping"> specifies the mapping from
83 Haskell types to external types.
86 <Sect2 id="sec-prim-name">
87 <Title>Giving the external function a Haskell name
91 The external function has to be given a Haskell name. The name
92 must be a Haskell <Literal>varid</Literal>, so the language rules regarding
93 variable names must be followed, i.e., it must start with a
94 lower case letter followed by a sequence of alphanumeric
95 (`in the Unicode sense') characters or '.
99 Notice that with Haskell 98, underscore ('_') is included in
100 the character class <Literal>small</Literal>.
108 varid : small ( small | large | udigit | ' )*
114 <Sect2 id="sec-prim-ext-name">
115 <Title>Naming the external function
119 The name of the external function consists of two parts,
120 one specifying its location, the other its name:
126 ext_fun : ext_loc ext_name
142 foreign import stdcall "Advapi32" "RegCloseKey" regCloseKey :: Addr -> IO ()
148 states that the external function named <Function>RegCloseKey</Function> at location
149 <Function>Advapi32</Function> should be bound to the Haskell name <Function>regCloseKey</Function>.
150 For a Win32 Haskell implementation that supports the loading of DLLs
151 on-the-fly, this declaration will most likely cause the run-time
152 system to load the <Filename>Advapi32.dll</Filename> DLL before looking up the
153 function <Function>RegCloseKey()</Function> therein to get at the function pointer
154 to use when invoking <Function>regCloseKey</Function>.
158 Compiled implementations may do something completely different, i.e.,
159 mangle "RegCloseKey" to convert it into an archive/import library
160 symbol, that's assumed to be in scope when linking. The details of
161 which are platform (and compiler command-line) dependent.
165 If the location part is left out, the name of the external function
166 specifies a symbol that is assumed to be in scope when linking.
170 The location part can either contain an absolute `address' (i.e.,
171 path) of the archive/DLL, or just its name, leaving it up to the
172 underlying system (system meaning both RTS/compiler and OS) to resolve
173 the name to its real location.
177 An implementation is <Emphasis>expected</Emphasis> to be able to intelligently
178 transform the <Literal>ext_loc</Literal> location to fit platform-specific
179 practices for naming dynamic libraries. For instance, given the
186 foreign import "Foo" "foo" foo :: Int -> Int -> IO ()
192 an implementation should map <Filename>Foo</Filename> to <Filename>"Foo.dll"</Filename> on a Win32
193 platform, and <Filename>libFoo.so</Filename> on ELF platforms. If the lookup of the
194 dynamic library with this transformed location name should fail, the
195 implementation should then attempt to use the original name before
196 eventually giving up. As part of their documentation, implementations
197 of <Literal>foreign import</Literal> should specify the exact details of how
198 <Literal>ext_loc</Literal>s are transformed and resolved, including the list of
199 directories searched (and the order in which they are.)
203 In the case the Haskell name of the imported function is identical to
204 the external name, the <Literal>ext_fun</Literal> can be omitted. i.e.,
210 foreign import sin :: Double -> IO Double
222 foreign import "sin" sin :: Double -> IO Double
229 <Sect2 id="sec-cconv">
230 <Title>Calling conventions
234 The number of calling conventions supported is fixed:
240 callconv : ccall | stdcall
249 <Term><Literal>ccall</Literal></Term>
252 The 'default' calling convention on a platform, i.e., the one
253 used to do (C) function calls.
257 In the case of x86 platforms, the caller pushes function arguments
258 from right to left on the C stack before calling. The caller is
259 responsible for popping the arguments off of the C stack on return.
264 <Term><Literal>stdcall</Literal></Term>
267 A Win32 specific calling convention. The same as <Literal>ccall</Literal>, except
268 that the callee cleans up the C stack before returning.
272 The <Literal>stdcall</Literal> is a Microsoft Win32 specific wrinkle; it used
273 throughout the Win32 API, for instance. On platforms where
274 <Literal>stdcall</Literal> isn't meaningful, it should be treated as being equal
275 to <Literal>ccall</Literal>.
286 <Emphasis remap="bf">Some remarks:</Emphasis>
292 Interoperating well with external code is the name of the game here,
293 so the guiding principle when deciding on what calling conventions
294 to include in <Literal>callconv</Literal> is that there's a demonstrated need for
295 a particular calling convention. Should it emerge that the inclusion
296 of other calling conventions will generally improve the quality of
297 this Haskell FFI, they will be considered for future inclusion in
298 <Literal>callconv</Literal>.
304 Supporting <Literal>stdcall</Literal> (and perhaps other platform-specific calling
305 conventions) raises the issue of whether a Haskell FFI should allow
306 the user to write platform-specific Haskell code. The calling
307 convention is clearly an integral part of an external function's
308 interface, so if the one used differs from the standard one specified
309 by the platform's ABI <Emphasis>and</Emphasis> that convention is used by a
310 non-trivial amount of external functions, the view of the FFI authors
311 is that a Haskell FFI should support it.
317 For <Literal>foreign import</Literal> (and other <Literal>foreign</Literal> declarations),
318 supplying the calling convention is optional. If it isn't supplied,
319 it is treated as if <Literal>ccall</Literal> was specified. Users are encouraged
320 to leave out the specification of the calling convention, if possible.
330 <Sect2 id="sec-prim-types">
331 <Title>External function types
335 The range of types that can be passed as arguments to an external
336 function is restricted (as are the range of results coming back):
342 prim_type : IO prim_result
344 | prim_arg '->' prim_type
355 If you associate a non-IO type with an external function, you
356 have the same 'proof obligations' as when you make use of
357 <Function>IOExts.unsafePerformIO</Function> in your Haskell programs.
363 The external function is strict in all its arguments.
369 <Emphasis>GHC only:</Emphasis> The GHC FFI implementation provides one extension
370 to <Literal>prim_type</Literal>:
375 | unsafe_arr_ty '->' prim_type
377 unsafe_arr_ty : ByteArray a
378 | MutableByteArray i s a
382 GHC permits the passing of its byte array primitive types
383 to external functions. There's some restrictions on when
384 they can be used; see Section <XRef LinkEnd="sec-arguments">
394 Section <XRef LinkEnd="sec-results"> defines
395 <Literal>prim_result</Literal>; Section <XRef LinkEnd="sec-arguments">
396 defines <Literal>prim_arg</Literal>.
399 <Sect3 id="sec-arguments">
400 <Title>Argument types
404 The external function expects zero or more arguments. The set of legal
405 argument types is restricted to the following set:
411 prim_arg : ext_ty | new_ty | ForeignObj
413 new_ty : a Haskell newtype of a prim_arg.
415 ext_ty : int_ty | word_ty | float_ty
416 | Addr | Char | StablePtr a
419 int_ty : Int | Int8 | Int16 | Int32 | Int64
420 word_ty : Word8 | Word16 | Word32 | Word64
421 float_ty : Float | Double
432 <Literal>ext_ty</Literal> represent the set of basic types supported by
433 C-like languages, although the numeric types are explicitly sized.
435 The <Emphasis>stable pointer</Emphasis> <Literal>StablePtr</Literal> type looks out of place in
436 this list of C-like types, but it has a well-defined and simple
437 C mapping, see Section <XRef LinkEnd="sec-mapping">
445 <Literal>prim_arg</Literal> represent the set of permissible argument types. In
446 addition to <Literal>ext_ty</Literal>, <Literal>ForeignObj</Literal> is also included.
448 The <Literal>ForeignObj</Literal> type represent values that are pointers to some
449 external entity/object. It differs from the <Literal>Addr</Literal> type in that
450 <Literal>ForeignObj</Literal>s are <Emphasis>finalized</Emphasis>, i.e., once the garbage collector
451 determines that a <Literal>ForeignObj</Literal> is unreachable, it will invoke a
452 finalising procedure attached to the <Literal>ForeignObj</Literal> to notify the
453 outside world that we're through with using it.
460 Haskell <Literal>newtype</Literal>s that wrap up a <Literal>prim_arg</Literal> type can also
461 be passed to external functions.
467 Haskell type synonyms for any of the above can also be used
468 in <Literal>foreign import</Literal> declarations. Qualified names likewise,
469 i.e. <Literal>Word.Word32</Literal> is legal.
476 <Literal>foreign import</Literal> does not support the binding to external
477 constants/variables. A <Literal>foreign import</Literal> declaration that takes no
478 arguments represent a binding to a function with no arguments.
484 <Emphasis>GHC only:</Emphasis> GHC's implementation of the FFI provides
491 Support for passing heap allocated byte arrays to an external
496 | prim_arg '->' prim_type
497 | unsafe_arr_ty '->' prim_type
499 unsafe_arr_ty : ByteArray a
500 | MutableByteArray i s a
504 GHC's <Literal>ByteArray</Literal> and <Literal>MutableByteArray</Literal> primitive types are
505 (im)mutable chunks of memory allocated on the Haskell heap, and
506 pointers to these can be passed to <Literal>foreign import</Literal>ed external
507 functions provided they are marked as <Literal>unsafe</Literal>. Since it is
508 inherently unsafe to hand out references to objects in the Haskell
509 heap if the external call may cause a garbage collection to happen,
510 you have to annotate the <Literal>foreign import</Literal> declaration with
511 the attribute <Literal>unsafe</Literal>. By doing so, the user explicitly states
512 that the external function won't provoke a garbage collection,
513 so passing out heap references to the external function is allright.
520 Another GHC extension is the support for unboxed types:
524 prim_arg : ... | unboxed_h_ty
525 ext_ty : .... | unboxed_ext_ty
527 unboxed_ext_ty : Int# | Word# | Char#
528 | Float# | Double# | Addr#
530 unboxed_h_ty : MutableByteArray# | ForeignObj#
535 Clearly, if you want to be portable across Haskell systems, using
536 system-specific extensions such as this is not advisable; avoid
537 using them if you can. (Support for using unboxed types might
538 be withdrawn sometime in the future.)
553 <Sect3 id="sec-results">
558 An external function is permitted to return the following
565 prim_result : ext_ty | new_ext_ty | ()
567 new_ext_ty : a Haskell newtype of an ext_ty.
573 where <Literal>()</Literal> represents <Literal>void</Literal> / no result.
582 External functions cannot raise exceptions (IO exceptions or non-IO ones.)
583 It is the responsibility of the <Literal>foreign import</Literal> user to layer
584 any error handling on top of an external function.
590 Only external types (<Literal>ext_ty</Literal>) can be passed back, i.e., returning
591 <Literal>ForeignObj</Literal>s is not supported/allowed.
597 Haskell newtypes that wrap up <Literal>ext_ty</Literal> are also permitted.
609 <Sect2 id="sec-mapping">
614 For the FFI to be of any practical use, the properties and sizes of
615 the various types that can be communicated between the Haskell world
616 and the outside, needs to be precisely defined. We do this by
617 presenting a mapping to C, as it is commonly used and most other
618 languages define a mapping to it. Table
619 <XRef LinkEnd="sec-mapping-table">
620 defines the mapping between Haskell and C types.
625 <Table id="sec-mapping-table">
626 <Title>Mapping of Haskell types to C types</Title>
629 <ColSpec Align="Left" Colsep="0">
630 <ColSpec Align="Left" Colsep="0">
631 <ColSpec Align="Left" Colsep="0">
632 <ColSpec Align="Left" Colsep="0">
633 <ColSpec Align="Left" Colsep="0">
634 <ColSpec Align="Left" Colsep="0">
637 <Entry>Haskell type </Entry>
638 <Entry> C type </Entry>
639 <Entry> requirement </Entry>
640 <Entry> range (9) </Entry>
646 <Literal>Char</Literal> </Entry>
647 <Entry> <Literal>HsChar</Literal> </Entry>
648 <Entry> unspec. integral type </Entry>
649 <Entry> <Literal>HS_CHAR_MIN</Literal> </Entry>
651 <Entry> <Literal>HS_CHAR_MAX</Literal></Entry>
655 <Literal>Int</Literal> </Entry>
656 <Entry> <Literal>HsInt</Literal> </Entry>
657 <Entry> signed integral of unspec. size(4) </Entry>
658 <Entry> <Literal>HS_INT_MIN</Literal> </Entry>
660 <Entry> <Literal>HS_INT_MAX</Literal></Entry>
664 <Literal>Int8</Literal> (2) </Entry>
665 <Entry> <Literal>HsInt8</Literal> </Entry>
666 <Entry> 8 bit signed integral </Entry>
667 <Entry> <Literal>HS_INT8_MIN</Literal> </Entry>
669 <Entry> <Literal>HS_INT8_MAX</Literal></Entry>
673 <Literal>Int16</Literal> (2) </Entry>
674 <Entry> <Literal>HsInt16</Literal> </Entry>
675 <Entry> 16 bit signed integral </Entry>
676 <Entry> <Literal>HS_INT16_MIN</Literal> </Entry>
678 <Entry> <Literal>HS_INT16_MAX</Literal></Entry>
682 <Literal>Int32</Literal> (2) </Entry>
683 <Entry> <Literal>HsInt32</Literal> </Entry>
684 <Entry> 32 bit signed integral </Entry>
685 <Entry> <Literal>HS_INT32_MIN</Literal> </Entry>
687 <Entry> <Literal>HS_INT32_MAX</Literal></Entry>
691 <Literal>Int64</Literal> (2,3) </Entry>
692 <Entry> <Literal>HsInt64</Literal> </Entry>
693 <Entry> 64 bit signed integral (3) </Entry>
694 <Entry> <Literal>HS_INT64_MIN</Literal> </Entry>
696 <Entry> <Literal>HS_INT64_MAX</Literal></Entry>
700 <Literal>Word8</Literal> (2) </Entry>
701 <Entry> <Literal>HsWord8</Literal> </Entry>
702 <Entry> 8 bit unsigned integral </Entry>
703 <Entry> <Literal>0</Literal> </Entry>
705 <Entry> <Literal>HS_WORD8_MAX</Literal></Entry>
709 <Literal>Word16</Literal> (2) </Entry>
710 <Entry> <Literal>HsWord16</Literal> </Entry>
711 <Entry> 16 bit unsigned integral </Entry>
712 <Entry> <Literal>0</Literal> </Entry>
714 <Entry> <Literal>HS_WORD16_MAX</Literal></Entry>
718 <Literal>Word32</Literal> (2) </Entry>
719 <Entry> <Literal>HsWord32</Literal> </Entry>
720 <Entry> 32 bit unsigned integral </Entry>
721 <Entry> <Literal>0</Literal> </Entry>
723 <Entry> <Literal>HS_WORD32_MAX</Literal></Entry>
727 <Literal>Word64</Literal> (2,3) </Entry>
728 <Entry> <Literal>HsWord64</Literal> </Entry>
729 <Entry> 64 bit unsigned integral (3) </Entry>
730 <Entry> <Literal>0</Literal> </Entry>
732 <Entry> <Literal>HS_WORD64_MAX</Literal></Entry>
736 <Literal>Float</Literal> </Entry>
737 <Entry> <Literal>HsFloat</Literal> </Entry>
738 <Entry> floating point of unspec. size (5) </Entry>
739 <Entry> (10) </Entry>
745 <Literal>Double</Literal> </Entry>
746 <Entry> <Literal>HsDouble</Literal> </Entry>
747 <Entry> floating point of unspec. size (5) </Entry>
748 <Entry> (10) </Entry>
754 <Literal>Bool</Literal> </Entry>
755 <Entry> <Literal>HsBool</Literal> </Entry>
756 <Entry> unspec. integral type </Entry>
757 <Entry> (11) </Entry>
763 <Literal>Addr</Literal> </Entry>
764 <Entry> <Literal>HsAddr</Literal> </Entry>
765 <Entry> void* (6) </Entry>
772 <Literal>ForeignObj</Literal> </Entry>
773 <Entry> <Literal>HsForeignObj</Literal> </Entry>
774 <Entry> void* (7) </Entry>
781 <Literal>StablePtr</Literal> </Entry>
782 <Entry> <Literal>HsStablePtr</Literal> </Entry>
783 <Entry> void* (8) </Entry>
801 <Emphasis remap="bf">Some remarks:</Emphasis>
807 A Haskell system that implements the FFI will supply a header file
808 <Filename>HsFFI.h</Filename> that includes target platform specific definitions
809 for the above types and values.
815 The sized numeric types <Literal>Hs{Int,Word}{8,16,32,64}</Literal> have
816 a 1-1 mapping to ISO C 99's <Literal>{,u}int{8,16,32,64}_t</Literal>. For systems
817 that doesn't support this revision of ISO C, a best-fit mapping
818 onto the supported C types is provided.
824 An implementation which does not support 64 bit integral types
825 on the C side should implement <Literal>Hs{Int,Word}64</Literal> as a struct. In
826 this case the bounds <Constant>HS_INT64_{MIN,MAX}</Constant> and <Constant>HS_WORD64_MAX</Constant>
833 A valid Haskell representation of <Literal>Int</Literal> has to be equal to or
834 wider than 30 bits. The <Literal>HsInt</Literal> synonym is guaranteed to map
835 onto a C type that satisifies Haskell's requirement for <Literal>Int</Literal>.
841 It is guaranteed that <Literal>Hs{Float,Double}</Literal> are one of C's
842 floating-point types <Literal>float</Literal>/<Literal>double</Literal>/<Literal>long double</Literal>.
848 It is guaranteed that <Literal>HsAddr</Literal> is of the same size as <Literal>void*</Literal>, so
849 any other pointer type can be converted to and from HsAddr without any
850 loss of information (K&R, Appendix A6.8).
856 Foreign objects are handled like <Literal>Addr</Literal> by the FFI, so there
857 is again the guarantee that <Literal>HsForeignObj</Literal> is the same as
858 <Literal>void*</Literal>. The separate name is meant as a reminder that there is
859 a finalizer attached to the object pointed to.
865 Stable pointers are passed as addresses by the FFI, but this is
866 only because a <Literal>void*</Literal> is used as a generic container in most
867 APIs, not because they are real addresses. To make this special
868 case clear, a separate C type is used here.
874 The bounds are preprocessor macros, so they can be used in
875 <Literal>#if</Literal> and for array bounds.
881 Floating-point limits are a little bit more complicated, so
882 preprocessor macros mirroring ISO C's <Filename>float.h</Filename> are provided:
885 HS_{FLOAT,DOUBLE}_RADIX
886 HS_{FLOAT,DOUBLE}_ROUNDS
887 HS_{FLOAT,DOUBLE}_EPSILON
888 HS_{FLOAT,DOUBLE}_DIG
889 HS_{FLOAT,DOUBLE}_MANT_DIG
890 HS_{FLOAT,DOUBLE}_MIN
891 HS_{FLOAT,DOUBLE}_MIN_EXP
892 HS_{FLOAT,DOUBLE}_MIN_10_EXP
893 HS_{FLOAT,DOUBLE}_MAX
894 HS_{FLOAT,DOUBLE}_MAX_EXP
895 HS_{FLOAT,DOUBLE}_MAX_10_EXP
903 It is guaranteed that Haskell's <Literal>False</Literal>/<Literal>True</Literal> map to
904 C's <Literal>0</Literal>/<Literal>1</Literal>, respectively, and vice versa. The mapping of
905 any other integral value to <Literal>Bool</Literal> is left unspecified.
911 To avoid name clashes, identifiers starting with <Literal>Hs</Literal> and
912 macros starting with <Literal>HS_</Literal> are reserved for the FFI.
918 <Emphasis>GHC only:</Emphasis> The GHC specific types <Literal>ByteArray</Literal> and
919 <Literal>MutableByteArray</Literal> both map to <Literal>char*</Literal>.
929 <Sect2 id="sec-prim-remarks">
930 <Title>Some <Literal>foreign import</Literal> wrinkles
939 By default, a <Literal>foreign import</Literal> function is <Emphasis>safe</Emphasis>. A safe
940 external function may cause a Haskell garbage collection as a result
941 of being called. This will typically happen when the imported
942 function end up calling Haskell functions that reside in the same
943 'Haskell world' (i.e., shares the same storage manager heap) -- see
944 Section <XRef LinkEnd="sec-entry"> for
945 details of how the FFI let's you call Haskell functions from the outside.
947 If the programmer can guarantee that the imported function won't
948 call back into Haskell, the <Literal>foreign import</Literal> can be marked as
949 'unsafe' (see Section <XRef LinkEnd="sec-primitive"> for details of
952 Unsafe calls are cheaper than safe ones, so distinguishing the two
953 classes of external calls may be worth your while if you're extra
954 conscious about performance.
961 A <Literal>foreign import</Literal>ed function should clearly not need to know that
962 it is being called from Haskell. One consequence of this is that the
963 lifetimes of the arguments that are passed from Haskell <Emphasis>must</Emphasis>
964 equal that of a normal C call. For instance, for the following decl,
968 foreign import "mumble" mumble :: ForeignObj -> IO ()
970 f :: Addr -> IO ()
972 fo <- makeForeignObj ptr myFinalizer
977 The <Literal>ForeignObj</Literal> must live across the call to <Function>mumble</Function> even if
978 it is not subsequently used/reachable. Why the insistence on this?
979 Consider what happens if <Function>mumble</Function> calls a function which calls back
980 into the Haskell world to execute a function, behind our back as it
981 were. This evaluation may possibly cause a garbage collection, with
982 the result that <Literal>fo</Literal> may end up being finalised.
984 By guaranteeing that <Literal>fo</Literal> will be considered live across the call
985 to <Function>mumble</Function>, the unfortunate situation where <Literal>fo</Literal> is finalised
986 (and hence the reference passed to <Function>mumble</Function> is suddenly no longer
1001 <Sect1 id="sec-prim-dynamic">
1002 <Title>Invoking external functions via a pointer
1006 A <Literal>foreign import</Literal> declaration imports an external
1007 function into Haskell. (The name of the external function
1008 is statically known, but the loading/linking of it may very well
1009 be delayed until run-time.) A <Literal>foreign import</Literal> declaration is then
1010 (approximately) just a type cast of an external function with a
1011 <Emphasis>statically known name</Emphasis>.
1015 An extension of <Literal>foreign import</Literal> is the support for <Emphasis>dynamic</Emphasis> type
1016 casts of external names/addresses:
1025 | 'foreign' 'import' [callconv] 'dynamic' ['unsafe']
1026 varid :: Addr -> (prim_args -> IO prim_result)
1032 i.e., identical to a <Literal>foreign import</Literal> declaration, but for the
1033 specification of <Literal>dynamic</Literal> instead of the name of an external
1034 function. The presence of <Literal>dynamic</Literal> indicates that when an
1035 application of <Literal>varid</Literal> is evaluated, the function pointed to by its
1036 first argument will be invoked, passing it the rest of <Literal>varid</Literal>'s
1041 What are the uses of this? Native invocation of COM methods,
1044 Or the interfacing to any other software component technologies.
1047 Haskell libraries that want to be dressed up as C libs (and hence may have
1048 to support C callbacks), Haskell code that need to dynamically load
1054 <Sect1 id="sec-entry">
1055 <Title>Exposing Haskell functions
1059 So far we've provided the Haskell programmer with ways of importing
1060 external functions into the Haskell world. The other half of the FFI
1061 coin is how to expose Haskell functionality to the outside world. So,
1062 dual to the <Literal>foreign import</Literal> declaration is <Literal>foreign export</Literal>:
1071 | 'foreign' 'export' callconv [ext_name] varid :: prim_type
1077 A <Literal>foreign export</Literal> declaration tells the compiler to expose a
1078 locally defined Haskell function to the outside world, i.e., wrap
1079 it up behind a calling interface that's useable from C. It is only
1080 permitted at the toplevel, where you have to specify the type at
1081 which you want to export the function, along with the calling
1082 convention to use. For instance, the following export declaration:
1088 foreign export ccall "foo" bar :: Int -> Addr -> IO Double
1094 will cause a Haskell system to generate the following C callable
1101 HsDouble foo(HsInt arg1, HsAddr arg2);
1107 When invoked, it will call the Haskell function <Function>bar</Function>, passing
1108 it the two arguments that was passed to <Function>foo()</Function>.
1117 The range of types that can be passed as arguments and results
1118 is restricted, since <Literal>varid</Literal> has got a <Literal>prim_type</Literal>.
1124 It is not possible to directly export operator symbols.
1130 The type checker will verify that the type given for the
1131 <Literal>foreign export</Literal> declaration is compatible with the type given to
1132 function definition itself. The type in the <Literal>foreign export</Literal> may
1133 be less general than that of the function itself. For example,
1138 f :: Num a => a -> a
1139 foreign export ccall "fInt" f :: Int -> Int
1140 foreign export ccall "fFloat" f :: Float -> Float
1144 These declarations export two C-callable procedures <Literal>fInt</Literal> and
1145 <Literal>fFloat</Literal>, both of which are implemented by the (overloaded)
1146 Haskell function <Function>f</Function>.
1153 The <Literal>foreign export</Literal>ed IO action must catch all exceptions, as
1154 the FFI does not address how to signal Haskell exceptions to the
1163 <Sect2 id="sec-callback">
1164 <Title>Exposing Haskell function values
1168 The <Literal>foreign export</Literal> declaration gives the C programmer access to
1169 statically defined Haskell functions. It does not allow you to
1170 conveniently expose dynamically-created Haskell function values as C
1171 function pointers though. To permit this, the FFI supports
1172 <Emphasis>dynamic</Emphasis> <Literal>foreign export</Literal>s:
1181 | 'foreign' 'export' [callconv] 'dynamic' varid :: prim_type -> IO Addr
1187 A <Literal>foreign export dynamic</Literal> declaration declares a C function
1188 pointer <Emphasis>generator</Emphasis>. Given a Haskell function value of some restricted
1189 type, the generator wraps it up behind an externally callable interface,
1190 returning an <Literal>Addr</Literal> to an externally callable (C) function pointer.
1194 When that function pointer is eventually called, the corresponding
1195 Haskell function value is applied to the function pointer's arguments
1196 and evaluated, returning the result (if any) back to the caller.
1200 The mapping between the argument to a <Literal>foreign export dynamic</Literal>
1201 declaration and its corresponding C function pointer type, is as
1208 typedef cType[[Res]] (*Varid_FunPtr)
1209 (cType[[Ty_1]] ,.., cType[[Ty_n]]);
1215 where <Literal>cType[[]]</Literal> is the Haskell to C type mapping presented
1216 in Section <XRef LinkEnd="sec-mapping">.
1220 To make it all a bit more concrete, here's an example:
1226 foreign export dynamic mkCallback :: (Int -> IO Int) -> IO Addr
1228 foreign import registerCallback :: Addr -> IO ()
1230 exportCallback :: (Int -> IO Int) -> IO ()
1231 exportCallback f = do
1232 fx <- mkCallback f
1239 The <Literal>exportCallback</Literal> lets you register a Haskell function value as
1240 a callback function to some external library. The C type of the
1241 callback that the external library expects in <Literal>registerCallback()</Literal>,
1245 An FFI implementation is encouraged to generate the C typedef corresponding
1246 to a <Literal>foreign export dynamic</Literal> declaration, but isn't required
1256 typedef HsInt (*mkCallback_FunPtr) (HsInt arg1);
1262 Creating the view of a Haskell closure as a C function pointer entails
1263 registering the Haskell closure as a 'root' with the underlying
1264 Haskell storage system, so that it won't be garbage collected. The FFI
1265 implementation takes care of this, but when the outside world is
1266 through with using a C function pointer generated by a <Literal>foreign
1267 export dynamic</Literal> declaration, it needs to be explicitly freed. This is
1274 void freeHaskellFunctionPtr(void *ptr);
1280 In the event you need to free these function pointers from within
1281 Haskell, a standard 'foreign import'ed binding of the above C entry
1282 point is also provided,
1288 Foreign.freeHaskellFunctionPtr :: Addr -> IO ()
1295 <Sect2 id="sec-foreign-label">
1296 <Title>Code addresses
1300 The <Literal>foreign import</Literal> declaration allows us to invoke an external
1301 function by name from within the comforts of the Haskell world, while
1302 <Literal>foreign import dynamic</Literal> lets us invoke an external function by
1303 address. However, there's no way of getting at the code address of
1304 some particular external label though, which is at times useful,
1305 e.g. for the construction of method tables for, say, Haskell COM
1306 components. To support this, the FFI has got <Literal>foreign label</Literal>s:
1312 foreign label "freeAtLast" addrOf_freeAtLast :: Addr
1318 The meaning of this declaration is that <Literal>addrOf_freeAtLast</Literal> will now
1319 contain the address of the label <Literal>freeAtLast</Literal>.
1326 <Sect1 id="sec-changelog">
1327 <Title>Change history
1342 changed the C representation of <Literal>Haskell_ForeignObj</Literal> from
1343 <Literal>(long*)</Literal> to <Literal>(void*)</Literal> -- ANSI C guarantees that <Literal>(void*)</Literal>
1344 is the widest possible data pointer.
1350 Updated defnition of <Literal>varid</Literal> in Section
1351 <XRef LinkEnd="sec-prim-name"> to reflect Haskell98's.
1357 Replaced confusing uses of <Literal>stdcall</Literal> with <Literal>ccall</Literal>.
1374 Simplified the calling convention section, support for Pascal (and
1375 fastcall) calling conventions dropped.
1381 Clarified that the arguments to a safe <Literal>foreign import</Literal> must have
1382 lifetimes that equal that of a C function application.
1388 Outlawed the use of the (GHC specific) types <Literal>ByteArray</Literal>
1389 and <Literal>MutableByteArray</Literal> in safe <Literal>foreign import</Literal>s.
1395 Added a note that support for the use of unboxed types in
1396 <Literal>foreign import</Literal> may be withdrawn/deprecated sometime in the future.
1402 Simplified section which sketches a possible implementation.
1408 Use <Literal>Hs</Literal> as prefix for the typedefs for the primitive Haskell
1409 FFI types rather than the longer <Literal>Haskell_</Literal>.
1426 Leave out implementation section; of limited interest.
1432 Outlined the criteria used to decide on what calling
1433 conventions to support.
1439 Include <Literal>newtype</Literal>s that wrap primitive types in the list
1440 of types that can be both passed to and returned from external
1458 Updated the section on type mapping to integrate some comments
1459 from people on <ffi@haskell.org> (a fair chunk of the text
1460 in that section was contributed by Sven Panne.)
1466 <Function>freeHaskellFunctionPtr</Function> should belong to module <Literal>Foreign</Literal>, not <Literal>IOExts</Literal>.
1484 <Literal>Bool</Literal> is now an FFI-supported type (i.e., added it to
1485 <Literal>ext_ty</Literal>.)