1 <Sect1 id="sec-ffi-intro">
6 The motivation behind this foreign function interface (FFI) specification is
7 to make it possible to describe in Haskell <Emphasis>source code</Emphasis>
8 the interface to foreign functionality in a Haskell system independent
9 manner. It builds on experiences made with the previous foreign function
10 interfaces provided by GHC and Hugs. However, the FFI specified in this
11 document is not in the market of trying to completely bridge the gap between
12 the actual type of an external function, and what is a
13 <Emphasis>convenient</Emphasis> type for that function to the Haskell
14 programmer. That is the domain of tools like HaskellDirect or GreenCard, both
15 of which are capable of generating Haskell code that uses this FFI.
19 In the following, we will discuss the language extensions of the FFI.
20 The extensions can be split up into two complementary halves; one half
21 that provides Haskell constructs for importing foreign functionality
22 into Haskell, the other which lets you expose Haskell functions to the
23 outside world. We start with the former, how to import external
24 functionality into Haskell.
29 <Sect1 id="sec-ffi-primitive">
30 <Title>Calling foreign functions
34 To bind a Haskell variable name and type to an external function, we
35 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:
44 | 'foreign' 'import' [callconv] [ext_fun] ['unsafe'] varid '::' prim_type
50 A <Literal>foreign import</Literal> declaration is only allowed as a toplevel
51 declaration. It consists of two parts, one giving the Haskell type
52 (<Literal>prim_type</Literal>), Haskell name (<Literal>varid</Literal>) and a flag indicating whether the
53 primitive is unsafe, the other giving details of the name of the
54 external function (<Literal>ext_fun</Literal>) and its calling interface
55 (<Literal>callconv</Literal>.)
59 Giving a Haskell name and type to an external entry point is clearly
60 an unsafe thing to do, as the external name will in most cases be
61 untyped. The onus is on the programmer using <Literal>foreign import</Literal> to
62 ensure that the Haskell type given correctly maps on to the
63 type of the external function.
64 <XRef LinkEnd="sec-ffi-mapping"> specifies the mapping from
65 Haskell types to external types.
68 <Sect2 id="sec-ffi-prim-name">
69 <Title>Giving the external function a Haskell name
73 The external function has to be given a Haskell name. The name
74 must be a Haskell <Literal>varid</Literal>, so the language rules regarding
75 variable names must be followed, i.e., it must start with a
76 lower case letter followed by a sequence of alphanumeric
77 (`in the Unicode sense') characters or '.
81 Notice that with Haskell 98, underscore ('_') is included in
82 the character class <Literal>small</Literal>.
90 varid : small ( small | large | udigit | ' )*
96 <Sect2 id="sec-ffi-prim-ext-name">
97 <Title>Naming the external function
101 The name of the external function is a string:
105 ext_fun : string</ProgramListing>
112 foreign import stdcall "RegCloseKey" regCloseKey :: Ptr a -> IO ()
116 states that the external function named <Function>RegCloseKey</Function> should be bound to the Haskell name <Function>regCloseKey</Function>.</Para>
119 The details of where exactly the external name can be found, such as
120 whether or not it is dynamically linked, and which library it might
121 come from, are implementation dependent. This information is expected
122 to be provided using a compiler-specific method (eg. GHC uses either
123 packages or command-line options to specify libraries and extra
124 include files).</para>
127 If the Haskell name of the imported function is identical to the
128 external name, the <Literal>ext_fun</Literal> can be
135 foreign import sin :: Double -> IO Double
147 foreign import "sin" sin :: Double -> IO Double
154 <Sect2 id="sec-ffi-cconv">
155 <Title>Calling conventions
159 The number of calling conventions supported is fixed:
165 callconv : ccall | stdcall
174 <Term><Literal>ccall</Literal></Term>
177 The 'default' calling convention on a platform, i.e., the one
178 used to do (C) function calls.
182 In the case of x86 platforms, the caller pushes function arguments
183 from right to left on the C stack before calling. The caller is
184 responsible for popping the arguments off of the C stack on return.
189 <Term><Literal>stdcall</Literal></Term>
192 A Win32 specific calling convention. The same as <Literal>ccall</Literal>, except
193 that the callee cleans up the C stack before returning.
197 The <Literal>stdcall</Literal> is a Microsoft Win32 specific wrinkle; it's used
198 throughout the Win32 API, for instance. On platforms where
199 <Literal>stdcall</Literal> isn't meaningful, it should be treated as being equal
200 to <Literal>ccall</Literal>.
211 <Emphasis remap="bf">Some remarks:</Emphasis>
217 Interoperating well with external code is the name of the game here,
218 so the guiding principle when deciding on what calling conventions
219 to include in <Literal>callconv</Literal> is that there's a demonstrated need for
220 a particular calling convention. Should it emerge that the inclusion
221 of other calling conventions will generally improve the quality of
222 this Haskell FFI, they will be considered for future inclusion in
223 <Literal>callconv</Literal>.
229 Supporting <Literal>stdcall</Literal> (and perhaps other platform-specific calling
230 conventions) raises the issue of whether a Haskell FFI should allow
231 the user to write platform-specific Haskell code. The calling
232 convention is clearly an integral part of an external function's
233 interface, so if the one used differs from the standard one specified
234 by the platform's ABI <Emphasis>and</Emphasis> that convention is used by a
235 non-trivial amount of external functions, the view of the FFI authors
236 is that a Haskell FFI should support it.
242 For <Literal>foreign import</Literal> (and other <Literal>foreign</Literal> declarations),
243 supplying the calling convention is optional. If it isn't supplied,
244 it is treated as if <Literal>ccall</Literal> was specified. Users are encouraged
245 to leave out the specification of the calling convention, if possible.
255 <Sect2 id="sec-ffi-prim-types">
256 <Title>External function types
260 The range of types that can be passed as arguments to an external
261 function is restricted (as are the range of results coming back):
267 prim_type : IO prim_result
269 | prim_arg '->' prim_type
280 If you associate a non-IO type with an external function, you
281 have the same 'proof obligations' as when you make use of
282 <Function>IOExts.unsafePerformIO</Function> in your Haskell programs.
288 The external function is strict in all its arguments.
297 <XRef LinkEnd="sec-ffi-results"> defines
298 <Literal>prim_result</Literal>; <XRef LinkEnd="sec-ffi-arguments">
299 defines <Literal>prim_arg</Literal>.
302 <Sect3 id="sec-ffi-arguments">
303 <Title>Argument types
307 The external function expects zero or more arguments. The set of legal
308 argument types is restricted to the following set:
314 prim_arg : ext_ty | new_ty | ForeignPtr a
316 new_ty : a Haskell newtype of a prim_arg.
318 ext_ty : int_ty | word_ty | float_ty
319 | Ptr a | Char | StablePtr a
322 int_ty : Int | Int8 | Int16 | Int32 | Int64
323 word_ty : Word8 | Word16 | Word32 | Word64
324 float_ty : Float | Double
335 <Literal>ext_ty</Literal> represent the set of basic types supported by
336 C-like languages, although the numeric types are explicitly sized.
338 The <Emphasis>stable pointer</Emphasis> <Literal>StablePtr</Literal> type looks out of place in
339 this list of C-like types, but it has a well-defined and simple
340 C mapping, see <XRef LinkEnd="sec-ffi-mapping">
348 <Literal>prim_arg</Literal> represent the set of permissible
349 argument types. In addition to <Literal>ext_ty</Literal>,
350 <Literal>ForeignPtr</Literal> is also included.
352 The <Literal>ForeignPtr</Literal> type represent values that are
353 pointers to some external entity/object. It differs from the
354 <Literal>Ptr</Literal> type in that <Literal>ForeignPtr</Literal>s are
355 <Emphasis>finalized</Emphasis>, i.e., once the garbage collector
356 determines that a <Literal>ForeignPtr</Literal> is unreachable, it
357 will invoke a finalising procedure attached to the
358 <Literal>ForeignPtr</Literal> to notify the outside world that we're
359 through with using it.
366 Haskell <Literal>newtype</Literal>s that wrap up a
367 <Literal>prim_arg</Literal> type can also be passed to external
374 Haskell type synonyms for any of the above can also be used
375 in <Literal>foreign import</Literal> declarations. Qualified names likewise,
376 i.e. <Literal>Word.Word32</Literal> is legal.
383 <Literal>foreign import</Literal> does not support the binding to external
384 constants/variables. A <Literal>foreign import</Literal> declaration that takes no
385 arguments represent a binding to a function with no arguments.
391 A GHC extension is the support for unboxed types:
395 prim_arg : ... | unboxed_h_ty
396 ext_ty : .... | unboxed_ext_ty
398 unboxed_ext_ty : Int# | Word# | Char#
399 | Float# | Double# | Addr#
401 unboxed_h_ty : MutableByteArray# | ForeignObj#
406 Clearly, if you want to be portable across Haskell systems, using
407 system-specific extensions such as this is not advisable; avoid
408 using them if you can. (Support for using unboxed types might
409 be withdrawn sometime in the future.)
419 <Sect3 id="sec-ffi-results">
424 An external function is permitted to return the following
431 prim_result : ext_ty | new_ext_ty | ()
433 new_ext_ty : a Haskell newtype of an ext_ty.
439 where <Literal>()</Literal> represents <Literal>void</Literal> / no result.
448 External functions cannot raise exceptions (IO exceptions or non-IO ones.)
449 It is the responsibility of the <Literal>foreign import</Literal> user to layer
450 any error handling on top of an external function.
456 Only external types (<Literal>ext_ty</Literal>) can be passed
457 back, i.e., returning <Literal>ForeignPtr</Literal>s is not
464 Haskell newtypes that wrap up <Literal>ext_ty</Literal> are also permitted.
476 <Sect2 id="sec-ffi-mapping">
481 For the FFI to be of any practical use, the properties and sizes of
482 the various types that can be communicated between the Haskell world
483 and the outside, needs to be precisely defined. We do this by
484 presenting a mapping to C, as it is commonly used and most other
485 languages define a mapping to it. Table
486 <XRef LinkEnd="sec-ffi-mapping-table">
487 defines the mapping between Haskell and C types.
492 <Table id="sec-ffi-mapping-table">
493 <Title>Mapping of Haskell types to C types</Title>
496 <ColSpec Align="Left" Colsep="0">
497 <ColSpec Align="Left" Colsep="0">
498 <ColSpec Align="Left" Colsep="0">
499 <ColSpec Align="Left" Colsep="0">
502 <Entry>Haskell type </Entry>
503 <Entry> C type </Entry>
504 <Entry> requirement </Entry>
505 <Entry> range (9) </Entry>
511 <Literal>Char</Literal> </Entry>
512 <Entry> <Literal>HsChar</Literal> </Entry>
513 <Entry> unspec. integral type </Entry>
514 <Entry> <Literal>HS_CHAR_MIN</Literal> .. <Literal>HS_CHAR_MAX</Literal></Entry>
518 <Literal>Int</Literal> </Entry>
519 <Entry> <Literal>HsInt</Literal> </Entry>
520 <Entry> signed integral of unspec. size(4) </Entry>
521 <Entry> <Literal>HS_INT_MIN</Literal> ..
522 <Literal>HS_INT_MAX</Literal></Entry>
526 <Literal>Int8</Literal> (2) </Entry>
527 <Entry> <Literal>HsInt8</Literal> </Entry>
528 <Entry> 8 bit signed integral </Entry>
529 <Entry> <Literal>HS_INT8_MIN</Literal>
531 <Literal>HS_INT8_MAX</Literal></Entry>
535 <Literal>Int16</Literal> (2) </Entry>
536 <Entry> <Literal>HsInt16</Literal> </Entry>
537 <Entry> 16 bit signed integral </Entry>
538 <Entry> <Literal>HS_INT16_MIN</Literal>
539 .. <Literal>HS_INT16_MAX</Literal></Entry>
543 <Literal>Int32</Literal> (2) </Entry>
544 <Entry> <Literal>HsInt32</Literal> </Entry>
545 <Entry> 32 bit signed integral </Entry>
546 <Entry> <Literal>HS_INT32_MIN</Literal> ..
547 <Literal>HS_INT32_MAX</Literal></Entry>
551 <Literal>Int64</Literal> (2,3) </Entry>
552 <Entry> <Literal>HsInt64</Literal> </Entry>
553 <Entry> 64 bit signed integral (3) </Entry>
554 <Entry> <Literal>HS_INT64_MIN</Literal> ..
555 <Literal>HS_INT64_MAX</Literal></Entry>
559 <Literal>Word8</Literal> (2) </Entry>
560 <Entry> <Literal>HsWord8</Literal> </Entry>
561 <Entry> 8 bit unsigned integral </Entry>
562 <Entry> <Literal>0</Literal> ..
563 <Literal>HS_WORD8_MAX</Literal></Entry>
567 <Literal>Word16</Literal> (2) </Entry>
568 <Entry> <Literal>HsWord16</Literal> </Entry>
569 <Entry> 16 bit unsigned integral </Entry>
570 <Entry> <Literal>0</Literal> ..
571 <Literal>HS_WORD16_MAX</Literal></Entry>
575 <Literal>Word32</Literal> (2) </Entry>
576 <Entry> <Literal>HsWord32</Literal> </Entry>
577 <Entry> 32 bit unsigned integral </Entry>
578 <Entry> <Literal>0</Literal> ..
579 <Literal>HS_WORD32_MAX</Literal></Entry>
583 <Literal>Word64</Literal> (2,3) </Entry>
584 <Entry> <Literal>HsWord64</Literal> </Entry>
585 <Entry> 64 bit unsigned integral (3) </Entry>
586 <Entry> <Literal>0</Literal> ..
587 <Literal>HS_WORD64_MAX</Literal></Entry>
591 <Literal>Float</Literal> </Entry>
592 <Entry> <Literal>HsFloat</Literal> </Entry>
593 <Entry> floating point of unspec. size (5) </Entry>
594 <Entry> (10) </Entry>
598 <Literal>Double</Literal> </Entry>
599 <Entry> <Literal>HsDouble</Literal> </Entry>
600 <Entry> floating point of unspec. size (5) </Entry>
601 <Entry> (10) </Entry>
605 <Literal>Bool</Literal> </Entry>
606 <Entry> <Literal>HsBool</Literal> </Entry>
607 <Entry> unspec. integral type </Entry>
608 <Entry> (11) </Entry>
612 <Literal>Ptr a</Literal> </Entry>
613 <Entry> <Literal>HsPtr</Literal> </Entry>
614 <Entry> void* (6) </Entry>
619 <Literal>ForeignPtr a</Literal> </Entry>
620 <Entry> <Literal>HsForeignPtr</Literal> </Entry>
621 <Entry> void* (7) </Entry>
626 <Literal>StablePtr a</Literal> </Entry>
627 <Entry> <Literal>HsStablePtr</Literal> </Entry>
628 <Entry> void* (8) </Entry>
640 <Emphasis remap="bf">Some remarks:</Emphasis>
646 A Haskell system that implements the FFI will supply a header file
647 <Filename>HsFFI.h</Filename> that includes target platform specific definitions
648 for the above types and values.
654 The sized numeric types <Literal>Hs{Int,Word}{8,16,32,64}</Literal> have
655 a 1-1 mapping to ISO C 99's <Literal>{,u}int{8,16,32,64}_t</Literal>. For systems
656 that doesn't support this revision of ISO C, a best-fit mapping
657 onto the supported C types is provided.
663 An implementation which does not support 64 bit integral types
664 on the C side should implement <Literal>Hs{Int,Word}64</Literal> as a struct. In
665 this case the bounds <Constant>HS_INT64_{MIN,MAX}</Constant> and <Constant>HS_WORD64_MAX</Constant>
672 A valid Haskell representation of <Literal>Int</Literal> has to be equal to or
673 wider than 30 bits. The <Literal>HsInt</Literal> synonym is guaranteed to map
674 onto a C type that satisifies Haskell's requirement for <Literal>Int</Literal>.
680 It is guaranteed that <Literal>Hs{Float,Double}</Literal> are one of C's
681 floating-point types <Literal>float</Literal>/<Literal>double</Literal>/<Literal>long double</Literal>.
687 It is guaranteed that <Literal>HsAddr</Literal> is of the same size as <Literal>void*</Literal>, so
688 any other pointer type can be converted to and from HsAddr without any
689 loss of information (K&R, Appendix A6.8).
695 Foreign objects are handled like <Literal>Ptr</Literal> by the FFI, so there
696 is again the guarantee that <Literal>HsForeignPtr</Literal> is the same as
697 <Literal>void*</Literal>. The separate name is meant as a reminder that there is
698 a finalizer attached to the object pointed to.
704 Stable pointers are passed as addresses by the FFI, but this is
705 only because a <Literal>void*</Literal> is used as a generic container in most
706 APIs, not because they are real addresses. To make this special
707 case clear, a separate C type is used here.
713 The bounds are preprocessor macros, so they can be used in
714 <Literal>#if</Literal> and for array bounds.
720 Floating-point limits are a little bit more complicated, so
721 preprocessor macros mirroring ISO C's <Filename>float.h</Filename> are provided:
724 HS_{FLOAT,DOUBLE}_RADIX
725 HS_{FLOAT,DOUBLE}_ROUNDS
726 HS_{FLOAT,DOUBLE}_EPSILON
727 HS_{FLOAT,DOUBLE}_DIG
728 HS_{FLOAT,DOUBLE}_MANT_DIG
729 HS_{FLOAT,DOUBLE}_MIN
730 HS_{FLOAT,DOUBLE}_MIN_EXP
731 HS_{FLOAT,DOUBLE}_MIN_10_EXP
732 HS_{FLOAT,DOUBLE}_MAX
733 HS_{FLOAT,DOUBLE}_MAX_EXP
734 HS_{FLOAT,DOUBLE}_MAX_10_EXP
742 It is guaranteed that Haskell's <Literal>False</Literal>/<Literal>True</Literal> map to
743 C's <Literal>0</Literal>/<Literal>1</Literal>, respectively, and vice versa. The mapping of
744 any other integral value to <Literal>Bool</Literal> is left unspecified.
750 To avoid name clashes, identifiers starting with <Literal>Hs</Literal> and
751 macros starting with <Literal>HS_</Literal> are reserved for the FFI.
757 <Emphasis>GHC only:</Emphasis> The GHC specific types <Literal>ByteArray</Literal> and
758 <Literal>MutableByteArray</Literal> both map to <Literal>char*</Literal>.
768 <Sect2 id="sec-ffi-prim-remarks">
769 <Title>Some <Literal>foreign import</Literal> wrinkles
778 By default, a <Literal>foreign import</Literal> function is <Emphasis>safe</Emphasis>. A safe
779 external function may cause a Haskell garbage collection as a result
780 of being called. This will typically happen when the imported
781 function end up calling Haskell functions that reside in the same
782 'Haskell world' (i.e., shares the same storage manager heap) -- see
783 <XRef LinkEnd="sec-ffi-entry"> for
784 details of how the FFI let's you call Haskell functions from the outside.
786 If the programmer can guarantee that the imported function won't
787 call back into Haskell, the <Literal>foreign import</Literal> can be marked as
788 'unsafe' (see <XRef LinkEnd="sec-ffi-primitive"> for details of
791 Unsafe calls are cheaper than safe ones, so distinguishing the two
792 classes of external calls may be worth your while if you're extra
793 conscious about performance.
800 A <Literal>foreign import</Literal>ed function should clearly not need to know that
801 it is being called from Haskell. One consequence of this is that the
802 lifetimes of the arguments that are passed from Haskell <Emphasis>must</Emphasis>
803 equal that of a normal C call. For instance, for the following decl,
807 foreign import "mumble" mumble :: ForeignPtr a -> IO ()
811 fo <- newForeignObj ptr myFinalizer
816 The <Literal>ForeignPtr</Literal> must live across the call to
817 <Function>mumble</Function> even if it is not subsequently
818 used/reachable. Why the insistence on this? Consider what happens if
819 <Function>mumble</Function> calls a function which calls back into the
820 Haskell world to execute a function, behind our back as it were. This
821 evaluation may possibly cause a garbage collection, with the result
822 that <Literal>fo</Literal> may end up being finalised.
824 By guaranteeing that <Literal>fo</Literal> will be considered live
825 across the call to <Function>mumble</Function>, the unfortunate
826 situation where <Literal>fo</Literal> is finalised (and hence the
827 reference passed to <Function>mumble</Function> is suddenly no longer
842 <Sect1 id="sec-ffi-prim-dynamic">
843 <Title>Invoking external functions via a pointer
847 A <Literal>foreign import</Literal> declaration imports an external
848 function into Haskell. (The name of the external function
849 is statically known, but the loading/linking of it may very well
850 be delayed until run-time.) A <Literal>foreign import</Literal> declaration is then
851 (approximately) just a type cast of an external function with a
852 <Emphasis>statically known name</Emphasis>.
856 An extension of <Literal>foreign import</Literal> is the support for <Emphasis>dynamic</Emphasis> type
857 casts of external names/addresses:
866 | 'foreign' 'import' [callconv] 'dynamic' ['unsafe']
867 varid :: Addr -> (prim_args -> IO prim_result)
873 i.e., identical to a <Literal>foreign import</Literal> declaration, but for the
874 specification of <Literal>dynamic</Literal> instead of the name of an external
875 function. The presence of <Literal>dynamic</Literal> indicates that when an
876 application of <Literal>varid</Literal> is evaluated, the function pointed to by its
877 first argument will be invoked, passing it the rest of <Literal>varid</Literal>'s
882 What are the uses of this? Native invocation of COM methods,
885 Or the interfacing to any other software component technologies.
888 Haskell libraries that want to be dressed up as C libs (and hence may have
889 to support C callbacks), Haskell code that need to dynamically load
895 <Sect1 id="sec-ffi-entry">
896 <Title>Exposing Haskell functions
900 So far we've provided the Haskell programmer with ways of importing
901 external functions into the Haskell world. The other half of the FFI
902 coin is how to expose Haskell functionality to the outside world. So,
903 dual to the <Literal>foreign import</Literal> declaration is <Literal>foreign export</Literal>:
912 | 'foreign' 'export' callconv [ext_name] varid :: prim_type
918 A <Literal>foreign export</Literal> declaration tells the compiler to expose a
919 locally defined Haskell function to the outside world, i.e., wrap
920 it up behind a calling interface that's useable from C. It is only
921 permitted at the toplevel, where you have to specify the type at
922 which you want to export the function, along with the calling
923 convention to use. For instance, the following export declaration:
929 foreign export ccall "foo" bar :: Int -> Addr -> IO Double
935 will cause a Haskell system to generate the following C callable
942 HsDouble foo(HsInt arg1, HsAddr arg2);
948 When invoked, it will call the Haskell function <Function>bar</Function>, passing
949 it the two arguments that was passed to <Function>foo()</Function>.
958 The range of types that can be passed as arguments and results
959 is restricted, since <Literal>varid</Literal> has got a <Literal>prim_type</Literal>.
965 It is not possible to directly export operator symbols.
971 The type checker will verify that the type given for the
972 <Literal>foreign export</Literal> declaration is compatible with the type given to
973 function definition itself. The type in the <Literal>foreign export</Literal> may
974 be less general than that of the function itself. For example,
980 foreign export ccall "fInt" f :: Int -> Int
981 foreign export ccall "fFloat" f :: Float -> Float
985 These declarations export two C-callable procedures <Literal>fInt</Literal> and
986 <Literal>fFloat</Literal>, both of which are implemented by the (overloaded)
987 Haskell function <Function>f</Function>.
994 The <Literal>foreign export</Literal>ed IO action must catch all exceptions, as
995 the FFI does not address how to signal Haskell exceptions to the
1004 <Sect2 id="sec-ffi-callback">
1005 <Title>Exposing Haskell function values
1009 The <Literal>foreign export</Literal> declaration gives the C programmer access to
1010 statically defined Haskell functions. It does not allow you to
1011 conveniently expose dynamically-created Haskell function values as C
1012 function pointers though. To permit this, the FFI supports
1013 <Emphasis>dynamic</Emphasis> <Literal>foreign export</Literal>s:
1022 | 'foreign' 'export' [callconv] 'dynamic' varid :: prim_type -> IO Addr
1028 A <Literal>foreign export dynamic</Literal> declaration declares a C function
1029 pointer <Emphasis>generator</Emphasis>. Given a Haskell function value of some restricted
1030 type, the generator wraps it up behind an externally callable interface,
1031 returning an <Literal>Addr</Literal> to an externally callable (C) function pointer.
1035 When that function pointer is eventually called, the corresponding
1036 Haskell function value is applied to the function pointer's arguments
1037 and evaluated, returning the result (if any) back to the caller.
1041 The mapping between the argument to a <Literal>foreign export dynamic</Literal>
1042 declaration and its corresponding C function pointer type, is as
1049 typedef cType[[Res]] (*Varid_FunPtr)
1050 (cType[[Ty_1]] ,.., cType[[Ty_n]]);
1056 where <Literal>cType[[]]</Literal> is the Haskell to C type mapping presented
1057 in <XRef LinkEnd="sec-ffi-mapping">.
1061 To make it all a bit more concrete, here's an example:
1067 foreign export dynamic mkCallback :: (Int -> IO Int) -> IO Addr
1069 foreign import registerCallback :: Addr -> IO ()
1071 exportCallback :: (Int -> IO Int) -> IO ()
1072 exportCallback f = do
1073 fx <- mkCallback f
1080 The <Literal>exportCallback</Literal> lets you register a Haskell function value as
1081 a callback function to some external library. The C type of the
1082 callback that the external library expects in <Literal>registerCallback()</Literal>,
1086 An FFI implementation is encouraged to generate the C typedef corresponding
1087 to a <Literal>foreign export dynamic</Literal> declaration, but isn't required
1097 typedef HsInt (*mkCallback_FunPtr) (HsInt arg1);
1103 Creating the view of a Haskell closure as a C function pointer entails
1104 registering the Haskell closure as a 'root' with the underlying
1105 Haskell storage system, so that it won't be garbage collected. The FFI
1106 implementation takes care of this, but when the outside world is
1107 through with using a C function pointer generated by a <Literal>foreign
1108 export dynamic</Literal> declaration, it needs to be explicitly freed. This is
1115 void freeHaskellFunctionPtr(void *ptr);
1121 In the event you need to free these function pointers from within
1122 Haskell, a standard 'foreign import'ed binding of the above C entry
1123 point is also provided,
1129 Foreign.freeHaskellFunctionPtr :: Addr -> IO ()
1136 <Sect2 id="sec-ffi-foreign-label">
1137 <Title>Code addresses
1141 The <Literal>foreign import</Literal> declaration allows us to invoke an external
1142 function by name from within the comforts of the Haskell world, while
1143 <Literal>foreign import dynamic</Literal> lets us invoke an external function by
1144 address. However, there's no way of getting at the code address of
1145 some particular external label though, which is at times useful,
1146 e.g. for the construction of method tables for, say, Haskell COM
1147 components. To support this, the FFI has got <Literal>foreign label</Literal>s:
1153 foreign label "freeAtLast" addrOf_freeAtLast :: Addr
1159 The meaning of this declaration is that <Literal>addrOf_freeAtLast</Literal> will now
1160 contain the address of the label <Literal>freeAtLast</Literal>.
1166 <!-- This doesn't need to be seen in the docs
1167 <Sect1 id="sec-ffi-changelog">
1168 <Title>Change history
1183 changed the C representation of
1184 <Literal>Haskell_ForeignPtr</Literal> from
1185 <Literal>(long*)</Literal> to <Literal>(void*)</Literal> ANSI C
1186 guarantees that <Literal>(void*)</Literal> is the widest possible data
1193 Updated defnition of <Literal>varid</Literal> in
1194 <XRef LinkEnd="sec-ffi-prim-name"> to reflect Haskell98's.
1200 Replaced confusing uses of <Literal>stdcall</Literal> with <Literal>ccall</Literal>.
1217 Simplified the calling convention section, support for Pascal (and
1218 fastcall) calling conventions dropped.
1224 Clarified that the arguments to a safe <Literal>foreign import</Literal> must have
1225 lifetimes that equal that of a C function application.
1231 Outlawed the use of the (GHC specific) types <Literal>ByteArray</Literal>
1232 and <Literal>MutableByteArray</Literal> in safe <Literal>foreign import</Literal>s.
1238 Added a note that support for the use of unboxed types in
1239 <Literal>foreign import</Literal> may be withdrawn/deprecated sometime in the future.
1245 Simplified section which sketches a possible implementation.
1251 Use <Literal>Hs</Literal> as prefix for the typedefs for the primitive Haskell
1252 FFI types rather than the longer <Literal>Haskell_</Literal>.
1269 Leave out implementation section; of limited interest.
1275 Outlined the criteria used to decide on what calling
1276 conventions to support.
1282 Include <Literal>newtype</Literal>s that wrap primitive types in the list
1283 of types that can be both passed to and returned from external
1301 Updated the section on type mapping to integrate some comments
1302 from people on <ffi@haskell.org> (a fair chunk of the text
1303 in that section was contributed by Sven Panne.)
1309 <Function>freeHaskellFunctionPtr</Function> should belong to module <Literal>Foreign</Literal>, not <Literal>IOExts</Literal>.
1327 <Literal>Bool</Literal> is now an FFI-supported type (i.e., added it to
1328 <Literal>ext_ty</Literal>.)