6 The motivation behind this foreign function interface(FFI)
7 specification is to make it possible to describe in Haskell <Emphasis>source
8 code</Emphasis> the interface to foreign functionality in a Haskell system
9 independent manner. It builds on experiences made with the previous
10 foreign function interfaces provided by GHC and Hugs.
14 The FFI specified in this document is not in the market of trying to
15 completely bridge the gap between the actual type of an external
16 function, and what is a <Emphasis>convenient</Emphasis> type for that function to the
17 Haskell programmer. That is the domain of tools like HaskellDirect or
18 Green Card, both of which are capable of generating Haskell code that
23 The FFI can be split up into two complementary halves; one half that
24 provides Haskell constructs for importing foreign functionality into
25 Haskell, the other which lets you expose Haskell functions to the
26 outside world. We start with the former, how to import external
27 functionality into Haskell.
32 <Sect1 id="sec-primitive">
33 <Title>Calling foreign functions
37 To bind a Haskell variable name and type to an external function, we
38 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:
47 | 'foreign' 'import' [callconv] [ext_fun] ['unsafe'] varid '::' prim_type
53 A <Literal>foreign import</Literal> declaration is only allowed as a toplevel
54 declaration. It consists of two parts, one giving the Haskell type
55 (<Literal>prim_type</Literal>), Haskell name (<Literal>varid</Literal>) and a flag indicating whether the
56 primitive is unsafe, the other giving details of the name of the
57 external function (<Literal>ext_fun</Literal>) and its calling interface
58 (<Literal>callconv</Literal>.)
62 Giving a Haskell name and type to an external entry point is clearly
63 an unsafe thing to do, as the external name will in most cases be
64 untyped. The onus is on the programmer using <Literal>foreign import</Literal> to
65 ensure that the Haskell type given correctly maps on to the
66 type of the external function. Section
67 <XRef LinkEnd="sec-mapping"> specifies the mapping from
68 Haskell types to external types.
71 <Sect2 id="sec-prim-name">
72 <Title>Giving the external function a Haskell name
76 The external function has to be given a Haskell name. The name
77 must be a Haskell <Literal>varid</Literal>, so the language rules regarding
78 variable names must be followed, i.e., it must start with a
79 lower case letter followed by a sequence of alphanumeric
80 (`in the Unicode sense') characters or '.
84 Notice that with Haskell 98, underscore ('_') is included in
85 the character class <Literal>small</Literal>.
93 varid : small ( small | large | udigit | ' )*
99 <Sect2 id="sec-prim-ext-name">
100 <Title>Naming the external function
104 The name of the external function consists of two parts,
105 one specifying its location, the other its name:
111 ext_fun : ext_loc ext_name
127 foreign import stdcall "Advapi32" "RegCloseKey" regCloseKey :: Addr -> IO ()
133 states that the external function named <Function>RegCloseKey</Function> at location
134 <Function>Advapi32</Function> should be bound to the Haskell name <Function>regCloseKey</Function>.
135 For a Win32 Haskell implementation that supports the loading of DLLs
136 on-the-fly, this declaration will most likely cause the run-time
137 system to load the <Filename>Advapi32.dll</Filename> DLL before looking up the
138 function <Function>RegCloseKey()</Function> therein to get at the function pointer
139 to use when invoking <Function>regCloseKey</Function>.
143 Compiled implementations may do something completely different, i.e.,
144 mangle "RegCloseKey" to convert it into an archive/import library
145 symbol, that's assumed to be in scope when linking. The details of
146 which are platform (and compiler command-line) dependent.
150 If the location part is left out, the name of the external function
151 specifies a symbol that is assumed to be in scope when linking.
155 The location part can either contain an absolute `address' (i.e.,
156 path) of the archive/DLL, or just its name, leaving it up to the
157 underlying system (system meaning both RTS/compiler and OS) to resolve
158 the name to its real location.
162 An implementation is <Emphasis>expected</Emphasis> to be able to intelligently
163 transform the <Literal>ext_loc</Literal> location to fit platform-specific
164 practices for naming dynamic libraries. For instance, given the
171 foreign import "Foo" "foo" foo :: Int -> Int -> IO ()
177 an implementation should map <Filename>Foo</Filename> to <Filename>"Foo.dll"</Filename> on a Win32
178 platform, and <Filename>libFoo.so</Filename> on ELF platforms. If the lookup of the
179 dynamic library with this transformed location name should fail, the
180 implementation should then attempt to use the original name before
181 eventually giving up. As part of their documentation, implementations
182 of <Literal>foreign import</Literal> should specify the exact details of how
183 <Literal>ext_loc</Literal>s are transformed and resolved, including the list of
184 directories searched (and the order in which they are.)
188 In the case the Haskell name of the imported function is identical to
189 the external name, the <Literal>ext_fun</Literal> can be omitted. i.e.,
195 foreign import sin :: Double -> IO Double
207 foreign import "sin" sin :: Double -> IO Double
214 <Sect2 id="sec-cconv">
215 <Title>Calling conventions
219 The number of calling conventions supported is fixed:
225 callconv : ccall | stdcall
234 <Term><Literal>ccall</Literal></Term>
237 The 'default' calling convention on a platform, i.e., the one
238 used to do (C) function calls.
242 In the case of x86 platforms, the caller pushes function arguments
243 from right to left on the C stack before calling. The caller is
244 responsible for popping the arguments off of the C stack on return.
249 <Term><Literal>stdcall</Literal></Term>
252 A Win32 specific calling convention. The same as <Literal>ccall</Literal>, except
253 that the callee cleans up the C stack before returning.
257 The <Literal>stdcall</Literal> is a Microsoft Win32 specific wrinkle; it used
258 throughout the Win32 API, for instance. On platforms where
259 <Literal>stdcall</Literal> isn't meaningful, it should be treated as being equal
260 to <Literal>ccall</Literal>.
271 <Emphasis remap="bf">Some remarks:</Emphasis>
277 Interoperating well with external code is the name of the game here,
278 so the guiding principle when deciding on what calling conventions
279 to include in <Literal>callconv</Literal> is that there's a demonstrated need for
280 a particular calling convention. Should it emerge that the inclusion
281 of other calling conventions will generally improve the quality of
282 this Haskell FFI, they will be considered for future inclusion in
283 <Literal>callconv</Literal>.
289 Supporting <Literal>stdcall</Literal> (and perhaps other platform-specific calling
290 conventions) raises the issue of whether a Haskell FFI should allow
291 the user to write platform-specific Haskell code. The calling
292 convention is clearly an integral part of an external function's
293 interface, so if the one used differs from the standard one specified
294 by the platform's ABI <Emphasis>and</Emphasis> that convention is used by a
295 non-trivial amount of external functions, the view of the FFI authors
296 is that a Haskell FFI should support it.
302 For <Literal>foreign import</Literal> (and other <Literal>foreign</Literal> declarations),
303 supplying the calling convention is optional. If it isn't supplied,
304 it is treated as if <Literal>ccall</Literal> was specified. Users are encouraged
305 to leave out the specification of the calling convention, if possible.
315 <Sect2 id="sec-prim-types">
316 <Title>External function types
320 The range of types that can be passed as arguments to an external
321 function is restricted (as are the range of results coming back):
327 prim_type : IO prim_result
329 | prim_arg '->' prim_type
340 If you associate a non-IO type with an external function, you
341 have the same 'proof obligations' as when you make use of
342 <Function>IOExts.unsafePerformIO</Function> in your Haskell programs.
348 The external function is strict in all its arguments.
354 <Emphasis>GHC only:</Emphasis> The GHC FFI implementation provides one extension
355 to <Literal>prim_type</Literal>:
360 | unsafe_arr_ty '->' prim_type
362 unsafe_arr_ty : ByteArray a
363 | MutableByteArray i s a
367 GHC permits the passing of its byte array primitive types
368 to external functions. There's some restrictions on when
369 they can be used; see Section <XRef LinkEnd="sec-arguments">
379 Section <XRef LinkEnd="sec-results"> defines
380 <Literal>prim_result</Literal>; Section <XRef LinkEnd="sec-arguments">
381 defines <Literal>prim_arg</Literal>.
384 <Sect3 id="sec-arguments">
385 <Title>Argument types
389 The external function expects zero or more arguments. The set of legal
390 argument types is restricted to the following set:
396 prim_arg : ext_ty | new_ty | ForeignObj
398 new_ty : a Haskell newtype of a prim_arg.
400 ext_ty : int_ty | word_ty | float_ty
401 | Addr | Char | StablePtr a
404 int_ty : Int | Int8 | Int16 | Int32 | Int64
405 word_ty : Word8 | Word16 | Word32 | Word64
406 float_ty : Float | Double
417 <Literal>ext_ty</Literal> represent the set of basic types supported by
418 C-like languages, although the numeric types are explicitly sized.
420 The <Emphasis>stable pointer</Emphasis> <Literal>StablePtr</Literal> type looks out of place in
421 this list of C-like types, but it has a well-defined and simple
422 C mapping, see Section <XRef LinkEnd="sec-mapping">
430 <Literal>prim_arg</Literal> represent the set of permissible argument types. In
431 addition to <Literal>ext_ty</Literal>, <Literal>ForeignObj</Literal> is also included.
433 The <Literal>ForeignObj</Literal> type represent values that are pointers to some
434 external entity/object. It differs from the <Literal>Addr</Literal> type in that
435 <Literal>ForeignObj</Literal>s are <Emphasis>finalized</Emphasis>, i.e., once the garbage collector
436 determines that a <Literal>ForeignObj</Literal> is unreachable, it will invoke a
437 finalising procedure attached to the <Literal>ForeignObj</Literal> to notify the
438 outside world that we're through with using it.
445 Haskell <Literal>newtype</Literal>s that wrap up a <Literal>prim_arg</Literal> type can also
446 be passed to external functions.
452 Haskell type synonyms for any of the above can also be used
453 in <Literal>foreign import</Literal> declarations. Qualified names likewise,
454 i.e. <Literal>Word.Word32</Literal> is legal.
461 <Literal>foreign import</Literal> does not support the binding to external
462 constants/variables. A <Literal>foreign import</Literal> declaration that takes no
463 arguments represent a binding to a function with no arguments.
469 <Emphasis>GHC only:</Emphasis> GHC's implementation of the FFI provides
476 Support for passing heap allocated byte arrays to an external
481 | prim_arg '->' prim_type
482 | unsafe_arr_ty '->' prim_type
484 unsafe_arr_ty : ByteArray a
485 | MutableByteArray i s a
489 GHC's <Literal>ByteArray</Literal> and <Literal>MutableByteArray</Literal> primitive types are
490 (im)mutable chunks of memory allocated on the Haskell heap, and
491 pointers to these can be passed to <Literal>foreign import</Literal>ed external
492 functions provided they are marked as <Literal>unsafe</Literal>. Since it is
493 inherently unsafe to hand out references to objects in the Haskell
494 heap if the external call may cause a garbage collection to happen,
495 you have to annotate the <Literal>foreign import</Literal> declaration with
496 the attribute <Literal>unsafe</Literal>. By doing so, the user explicitly states
497 that the external function won't provoke a garbage collection,
498 so passing out heap references to the external function is allright.
505 Another GHC extension is the support for unboxed types:
509 prim_arg : ... | unboxed_h_ty
510 ext_ty : .... | unboxed_ext_ty
512 unboxed_ext_ty : Int# | Word# | Char#
513 | Float# | Double# | Addr#
515 unboxed_h_ty : MutableByteArray# | ForeignObj#
520 Clearly, if you want to be portable across Haskell systems, using
521 system-specific extensions such as this is not advisable; avoid
522 using them if you can. (Support for using unboxed types might
523 be withdrawn sometime in the future.)
538 <Sect3 id="sec-results">
543 An external function is permitted to return the following
550 prim_result : ext_ty | new_ext_ty | ()
552 new_ext_ty : a Haskell newtype of an ext_ty.
558 where <Literal>()</Literal> represents <Literal>void</Literal> / no result.
567 External functions cannot raise exceptions (IO exceptions or non-IO ones.)
568 It is the responsibility of the <Literal>foreign import</Literal> user to layer
569 any error handling on top of an external function.
575 Only external types (<Literal>ext_ty</Literal>) can be passed back, i.e., returning
576 <Literal>ForeignObj</Literal>s is not supported/allowed.
582 Haskell newtypes that wrap up <Literal>ext_ty</Literal> are also permitted.
594 <Sect2 id="sec-mapping">
599 For the FFI to be of any practical use, the properties and sizes of
600 the various types that can be communicated between the Haskell world
601 and the outside, needs to be precisely defined. We do this by
602 presenting a mapping to C, as it is commonly used and most other
603 languages define a mapping to it. Table
604 <XRef LinkEnd="sec-mapping-table">
605 defines the mapping between Haskell and C types.
610 <Table id="sec-mapping-table">
611 <Title>Mapping of Haskell types to C types</Title>
614 <ColSpec Align="Left" Colsep="0">
615 <ColSpec Align="Left" Colsep="0">
616 <ColSpec Align="Left" Colsep="0">
617 <ColSpec Align="Left" Colsep="0">
620 <Entry>Haskell type </Entry>
621 <Entry> C type </Entry>
622 <Entry> requirement </Entry>
623 <Entry> range (9) </Entry>
629 <Literal>Char</Literal> </Entry>
630 <Entry> <Literal>HsChar</Literal> </Entry>
631 <Entry> unspec. integral type </Entry>
632 <Entry> <Literal>HS_CHAR_MIN</Literal> .. <Literal>HS_CHAR_MAX</Literal></Entry>
636 <Literal>Int</Literal> </Entry>
637 <Entry> <Literal>HsInt</Literal> </Entry>
638 <Entry> signed integral of unspec. size(4) </Entry>
639 <Entry> <Literal>HS_INT_MIN</Literal> ..
640 <Literal>HS_INT_MAX</Literal></Entry>
644 <Literal>Int8</Literal> (2) </Entry>
645 <Entry> <Literal>HsInt8</Literal> </Entry>
646 <Entry> 8 bit signed integral </Entry>
647 <Entry> <Literal>HS_INT8_MIN</Literal>
649 <Literal>HS_INT8_MAX</Literal></Entry>
653 <Literal>Int16</Literal> (2) </Entry>
654 <Entry> <Literal>HsInt16</Literal> </Entry>
655 <Entry> 16 bit signed integral </Entry>
656 <Entry> <Literal>HS_INT16_MIN</Literal>
657 .. <Literal>HS_INT16_MAX</Literal></Entry>
661 <Literal>Int32</Literal> (2) </Entry>
662 <Entry> <Literal>HsInt32</Literal> </Entry>
663 <Entry> 32 bit signed integral </Entry>
664 <Entry> <Literal>HS_INT32_MIN</Literal> ..
665 <Literal>HS_INT32_MAX</Literal></Entry>
669 <Literal>Int64</Literal> (2,3) </Entry>
670 <Entry> <Literal>HsInt64</Literal> </Entry>
671 <Entry> 64 bit signed integral (3) </Entry>
672 <Entry> <Literal>HS_INT64_MIN</Literal> ..
673 <Literal>HS_INT64_MAX</Literal></Entry>
677 <Literal>Word8</Literal> (2) </Entry>
678 <Entry> <Literal>HsWord8</Literal> </Entry>
679 <Entry> 8 bit unsigned integral </Entry>
680 <Entry> <Literal>0</Literal> ..
681 <Literal>HS_WORD8_MAX</Literal></Entry>
685 <Literal>Word16</Literal> (2) </Entry>
686 <Entry> <Literal>HsWord16</Literal> </Entry>
687 <Entry> 16 bit unsigned integral </Entry>
688 <Entry> <Literal>0</Literal> ..
689 <Literal>HS_WORD16_MAX</Literal></Entry>
693 <Literal>Word32</Literal> (2) </Entry>
694 <Entry> <Literal>HsWord32</Literal> </Entry>
695 <Entry> 32 bit unsigned integral </Entry>
696 <Entry> <Literal>0</Literal> ..
697 <Literal>HS_WORD32_MAX</Literal></Entry>
701 <Literal>Word64</Literal> (2,3) </Entry>
702 <Entry> <Literal>HsWord64</Literal> </Entry>
703 <Entry> 64 bit unsigned integral (3) </Entry>
704 <Entry> <Literal>0</Literal> ..
705 <Literal>HS_WORD64_MAX</Literal></Entry>
709 <Literal>Float</Literal> </Entry>
710 <Entry> <Literal>HsFloat</Literal> </Entry>
711 <Entry> floating point of unspec. size (5) </Entry>
712 <Entry> (10) </Entry>
716 <Literal>Double</Literal> </Entry>
717 <Entry> <Literal>HsDouble</Literal> </Entry>
718 <Entry> floating point of unspec. size (5) </Entry>
719 <Entry> (10) </Entry>
723 <Literal>Bool</Literal> </Entry>
724 <Entry> <Literal>HsBool</Literal> </Entry>
725 <Entry> unspec. integral type </Entry>
726 <Entry> (11) </Entry>
730 <Literal>Addr</Literal> </Entry>
731 <Entry> <Literal>HsAddr</Literal> </Entry>
732 <Entry> void* (6) </Entry>
737 <Literal>ForeignObj</Literal> </Entry>
738 <Entry> <Literal>HsForeignObj</Literal> </Entry>
739 <Entry> void* (7) </Entry>
744 <Literal>StablePtr</Literal> </Entry>
745 <Entry> <Literal>HsStablePtr</Literal> </Entry>
746 <Entry> void* (8) </Entry>
758 <Emphasis remap="bf">Some remarks:</Emphasis>
764 A Haskell system that implements the FFI will supply a header file
765 <Filename>HsFFI.h</Filename> that includes target platform specific definitions
766 for the above types and values.
772 The sized numeric types <Literal>Hs{Int,Word}{8,16,32,64}</Literal> have
773 a 1-1 mapping to ISO C 99's <Literal>{,u}int{8,16,32,64}_t</Literal>. For systems
774 that doesn't support this revision of ISO C, a best-fit mapping
775 onto the supported C types is provided.
781 An implementation which does not support 64 bit integral types
782 on the C side should implement <Literal>Hs{Int,Word}64</Literal> as a struct. In
783 this case the bounds <Constant>HS_INT64_{MIN,MAX}</Constant> and <Constant>HS_WORD64_MAX</Constant>
790 A valid Haskell representation of <Literal>Int</Literal> has to be equal to or
791 wider than 30 bits. The <Literal>HsInt</Literal> synonym is guaranteed to map
792 onto a C type that satisifies Haskell's requirement for <Literal>Int</Literal>.
798 It is guaranteed that <Literal>Hs{Float,Double}</Literal> are one of C's
799 floating-point types <Literal>float</Literal>/<Literal>double</Literal>/<Literal>long double</Literal>.
805 It is guaranteed that <Literal>HsAddr</Literal> is of the same size as <Literal>void*</Literal>, so
806 any other pointer type can be converted to and from HsAddr without any
807 loss of information (K&R, Appendix A6.8).
813 Foreign objects are handled like <Literal>Addr</Literal> by the FFI, so there
814 is again the guarantee that <Literal>HsForeignObj</Literal> is the same as
815 <Literal>void*</Literal>. The separate name is meant as a reminder that there is
816 a finalizer attached to the object pointed to.
822 Stable pointers are passed as addresses by the FFI, but this is
823 only because a <Literal>void*</Literal> is used as a generic container in most
824 APIs, not because they are real addresses. To make this special
825 case clear, a separate C type is used here.
831 The bounds are preprocessor macros, so they can be used in
832 <Literal>#if</Literal> and for array bounds.
838 Floating-point limits are a little bit more complicated, so
839 preprocessor macros mirroring ISO C's <Filename>float.h</Filename> are provided:
842 HS_{FLOAT,DOUBLE}_RADIX
843 HS_{FLOAT,DOUBLE}_ROUNDS
844 HS_{FLOAT,DOUBLE}_EPSILON
845 HS_{FLOAT,DOUBLE}_DIG
846 HS_{FLOAT,DOUBLE}_MANT_DIG
847 HS_{FLOAT,DOUBLE}_MIN
848 HS_{FLOAT,DOUBLE}_MIN_EXP
849 HS_{FLOAT,DOUBLE}_MIN_10_EXP
850 HS_{FLOAT,DOUBLE}_MAX
851 HS_{FLOAT,DOUBLE}_MAX_EXP
852 HS_{FLOAT,DOUBLE}_MAX_10_EXP
860 It is guaranteed that Haskell's <Literal>False</Literal>/<Literal>True</Literal> map to
861 C's <Literal>0</Literal>/<Literal>1</Literal>, respectively, and vice versa. The mapping of
862 any other integral value to <Literal>Bool</Literal> is left unspecified.
868 To avoid name clashes, identifiers starting with <Literal>Hs</Literal> and
869 macros starting with <Literal>HS_</Literal> are reserved for the FFI.
875 <Emphasis>GHC only:</Emphasis> The GHC specific types <Literal>ByteArray</Literal> and
876 <Literal>MutableByteArray</Literal> both map to <Literal>char*</Literal>.
886 <Sect2 id="sec-prim-remarks">
887 <Title>Some <Literal>foreign import</Literal> wrinkles
896 By default, a <Literal>foreign import</Literal> function is <Emphasis>safe</Emphasis>. A safe
897 external function may cause a Haskell garbage collection as a result
898 of being called. This will typically happen when the imported
899 function end up calling Haskell functions that reside in the same
900 'Haskell world' (i.e., shares the same storage manager heap) -- see
901 Section <XRef LinkEnd="sec-entry"> for
902 details of how the FFI let's you call Haskell functions from the outside.
904 If the programmer can guarantee that the imported function won't
905 call back into Haskell, the <Literal>foreign import</Literal> can be marked as
906 'unsafe' (see Section <XRef LinkEnd="sec-primitive"> for details of
909 Unsafe calls are cheaper than safe ones, so distinguishing the two
910 classes of external calls may be worth your while if you're extra
911 conscious about performance.
918 A <Literal>foreign import</Literal>ed function should clearly not need to know that
919 it is being called from Haskell. One consequence of this is that the
920 lifetimes of the arguments that are passed from Haskell <Emphasis>must</Emphasis>
921 equal that of a normal C call. For instance, for the following decl,
925 foreign import "mumble" mumble :: ForeignObj -> IO ()
927 f :: Addr -> IO ()
929 fo <- newForeignObj ptr myFinalizer
934 The <Literal>ForeignObj</Literal> must live across the call to <Function>mumble</Function> even if
935 it is not subsequently used/reachable. Why the insistence on this?
936 Consider what happens if <Function>mumble</Function> calls a function which calls back
937 into the Haskell world to execute a function, behind our back as it
938 were. This evaluation may possibly cause a garbage collection, with
939 the result that <Literal>fo</Literal> may end up being finalised.
941 By guaranteeing that <Literal>fo</Literal> will be considered live across the call
942 to <Function>mumble</Function>, the unfortunate situation where <Literal>fo</Literal> is finalised
943 (and hence the reference passed to <Function>mumble</Function> is suddenly no longer
958 <Sect1 id="sec-prim-dynamic">
959 <Title>Invoking external functions via a pointer
963 A <Literal>foreign import</Literal> declaration imports an external
964 function into Haskell. (The name of the external function
965 is statically known, but the loading/linking of it may very well
966 be delayed until run-time.) A <Literal>foreign import</Literal> declaration is then
967 (approximately) just a type cast of an external function with a
968 <Emphasis>statically known name</Emphasis>.
972 An extension of <Literal>foreign import</Literal> is the support for <Emphasis>dynamic</Emphasis> type
973 casts of external names/addresses:
982 | 'foreign' 'import' [callconv] 'dynamic' ['unsafe']
983 varid :: Addr -> (prim_args -> IO prim_result)
989 i.e., identical to a <Literal>foreign import</Literal> declaration, but for the
990 specification of <Literal>dynamic</Literal> instead of the name of an external
991 function. The presence of <Literal>dynamic</Literal> indicates that when an
992 application of <Literal>varid</Literal> is evaluated, the function pointed to by its
993 first argument will be invoked, passing it the rest of <Literal>varid</Literal>'s
998 What are the uses of this? Native invocation of COM methods,
1001 Or the interfacing to any other software component technologies.
1004 Haskell libraries that want to be dressed up as C libs (and hence may have
1005 to support C callbacks), Haskell code that need to dynamically load
1011 <Sect1 id="sec-entry">
1012 <Title>Exposing Haskell functions
1016 So far we've provided the Haskell programmer with ways of importing
1017 external functions into the Haskell world. The other half of the FFI
1018 coin is how to expose Haskell functionality to the outside world. So,
1019 dual to the <Literal>foreign import</Literal> declaration is <Literal>foreign export</Literal>:
1028 | 'foreign' 'export' callconv [ext_name] varid :: prim_type
1034 A <Literal>foreign export</Literal> declaration tells the compiler to expose a
1035 locally defined Haskell function to the outside world, i.e., wrap
1036 it up behind a calling interface that's useable from C. It is only
1037 permitted at the toplevel, where you have to specify the type at
1038 which you want to export the function, along with the calling
1039 convention to use. For instance, the following export declaration:
1045 foreign export ccall "foo" bar :: Int -> Addr -> IO Double
1051 will cause a Haskell system to generate the following C callable
1058 HsDouble foo(HsInt arg1, HsAddr arg2);
1064 When invoked, it will call the Haskell function <Function>bar</Function>, passing
1065 it the two arguments that was passed to <Function>foo()</Function>.
1074 The range of types that can be passed as arguments and results
1075 is restricted, since <Literal>varid</Literal> has got a <Literal>prim_type</Literal>.
1081 It is not possible to directly export operator symbols.
1087 The type checker will verify that the type given for the
1088 <Literal>foreign export</Literal> declaration is compatible with the type given to
1089 function definition itself. The type in the <Literal>foreign export</Literal> may
1090 be less general than that of the function itself. For example,
1095 f :: Num a => a -> a
1096 foreign export ccall "fInt" f :: Int -> Int
1097 foreign export ccall "fFloat" f :: Float -> Float
1101 These declarations export two C-callable procedures <Literal>fInt</Literal> and
1102 <Literal>fFloat</Literal>, both of which are implemented by the (overloaded)
1103 Haskell function <Function>f</Function>.
1110 The <Literal>foreign export</Literal>ed IO action must catch all exceptions, as
1111 the FFI does not address how to signal Haskell exceptions to the
1120 <Sect2 id="sec-callback">
1121 <Title>Exposing Haskell function values
1125 The <Literal>foreign export</Literal> declaration gives the C programmer access to
1126 statically defined Haskell functions. It does not allow you to
1127 conveniently expose dynamically-created Haskell function values as C
1128 function pointers though. To permit this, the FFI supports
1129 <Emphasis>dynamic</Emphasis> <Literal>foreign export</Literal>s:
1138 | 'foreign' 'export' [callconv] 'dynamic' varid :: prim_type -> IO Addr
1144 A <Literal>foreign export dynamic</Literal> declaration declares a C function
1145 pointer <Emphasis>generator</Emphasis>. Given a Haskell function value of some restricted
1146 type, the generator wraps it up behind an externally callable interface,
1147 returning an <Literal>Addr</Literal> to an externally callable (C) function pointer.
1151 When that function pointer is eventually called, the corresponding
1152 Haskell function value is applied to the function pointer's arguments
1153 and evaluated, returning the result (if any) back to the caller.
1157 The mapping between the argument to a <Literal>foreign export dynamic</Literal>
1158 declaration and its corresponding C function pointer type, is as
1165 typedef cType[[Res]] (*Varid_FunPtr)
1166 (cType[[Ty_1]] ,.., cType[[Ty_n]]);
1172 where <Literal>cType[[]]</Literal> is the Haskell to C type mapping presented
1173 in Section <XRef LinkEnd="sec-mapping">.
1177 To make it all a bit more concrete, here's an example:
1183 foreign export dynamic mkCallback :: (Int -> IO Int) -> IO Addr
1185 foreign import registerCallback :: Addr -> IO ()
1187 exportCallback :: (Int -> IO Int) -> IO ()
1188 exportCallback f = do
1189 fx <- mkCallback f
1196 The <Literal>exportCallback</Literal> lets you register a Haskell function value as
1197 a callback function to some external library. The C type of the
1198 callback that the external library expects in <Literal>registerCallback()</Literal>,
1202 An FFI implementation is encouraged to generate the C typedef corresponding
1203 to a <Literal>foreign export dynamic</Literal> declaration, but isn't required
1213 typedef HsInt (*mkCallback_FunPtr) (HsInt arg1);
1219 Creating the view of a Haskell closure as a C function pointer entails
1220 registering the Haskell closure as a 'root' with the underlying
1221 Haskell storage system, so that it won't be garbage collected. The FFI
1222 implementation takes care of this, but when the outside world is
1223 through with using a C function pointer generated by a <Literal>foreign
1224 export dynamic</Literal> declaration, it needs to be explicitly freed. This is
1231 void freeHaskellFunctionPtr(void *ptr);
1237 In the event you need to free these function pointers from within
1238 Haskell, a standard 'foreign import'ed binding of the above C entry
1239 point is also provided,
1245 Foreign.freeHaskellFunctionPtr :: Addr -> IO ()
1252 <Sect2 id="sec-foreign-label">
1253 <Title>Code addresses
1257 The <Literal>foreign import</Literal> declaration allows us to invoke an external
1258 function by name from within the comforts of the Haskell world, while
1259 <Literal>foreign import dynamic</Literal> lets us invoke an external function by
1260 address. However, there's no way of getting at the code address of
1261 some particular external label though, which is at times useful,
1262 e.g. for the construction of method tables for, say, Haskell COM
1263 components. To support this, the FFI has got <Literal>foreign label</Literal>s:
1269 foreign label "freeAtLast" addrOf_freeAtLast :: Addr
1275 The meaning of this declaration is that <Literal>addrOf_freeAtLast</Literal> will now
1276 contain the address of the label <Literal>freeAtLast</Literal>.
1282 <!-- This doesn't need to be seen in the docs
1283 <Sect1 id="sec-changelog">
1284 <Title>Change history
1299 changed the C representation of <Literal>Haskell_ForeignObj</Literal> from
1300 <Literal>(long*)</Literal> to <Literal>(void*)</Literal> ANSI C guarantees that <Literal>(void*)</Literal>
1301 is the widest possible data pointer.
1307 Updated defnition of <Literal>varid</Literal> in Section
1308 <XRef LinkEnd="sec-prim-name"> to reflect Haskell98's.
1314 Replaced confusing uses of <Literal>stdcall</Literal> with <Literal>ccall</Literal>.
1331 Simplified the calling convention section, support for Pascal (and
1332 fastcall) calling conventions dropped.
1338 Clarified that the arguments to a safe <Literal>foreign import</Literal> must have
1339 lifetimes that equal that of a C function application.
1345 Outlawed the use of the (GHC specific) types <Literal>ByteArray</Literal>
1346 and <Literal>MutableByteArray</Literal> in safe <Literal>foreign import</Literal>s.
1352 Added a note that support for the use of unboxed types in
1353 <Literal>foreign import</Literal> may be withdrawn/deprecated sometime in the future.
1359 Simplified section which sketches a possible implementation.
1365 Use <Literal>Hs</Literal> as prefix for the typedefs for the primitive Haskell
1366 FFI types rather than the longer <Literal>Haskell_</Literal>.
1383 Leave out implementation section; of limited interest.
1389 Outlined the criteria used to decide on what calling
1390 conventions to support.
1396 Include <Literal>newtype</Literal>s that wrap primitive types in the list
1397 of types that can be both passed to and returned from external
1415 Updated the section on type mapping to integrate some comments
1416 from people on <ffi@haskell.org> (a fair chunk of the text
1417 in that section was contributed by Sven Panne.)
1423 <Function>freeHaskellFunctionPtr</Function> should belong to module <Literal>Foreign</Literal>, not <Literal>IOExts</Literal>.
1441 <Literal>Bool</Literal> is now an FFI-supported type (i.e., added it to
1442 <Literal>ext_ty</Literal>.)