067f790183c822d1a6a43c4877436c243ed55642
[ghc-hetmet.git] / docs / ffi.sgml
1 <Sect1 id="sec-ffi-intro">
2 <Title>Introduction
3 </Title>
4
5 <Para>
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 Green Card, both
15 of which are capable of generating Haskell code that uses this FFI.
16 </Para>
17
18 <Para>
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.
25 </Para>
26
27 </Sect1>
28
29 <Sect1 id="sec-ffi-primitive">
30 <Title>Calling foreign functions
31 </Title>
32
33 <Para>
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:
36 </Para>
37
38 <Para>
39
40 <ProgramListing>
41 topdecl 
42   : ...
43   ..
44   | 'foreign' 'import' [callconv] [ext_fun] ['unsafe'] varid '::' prim_type
45 </ProgramListing>
46
47 </Para>
48
49 <Para>
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&lowbar;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&lowbar;fun</Literal>) and its calling interface
55 (<Literal>callconv</Literal>.)
56 </Para>
57
58 <Para>
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.
66 </Para>
67
68 <Sect2 id="sec-ffi-prim-name">
69 <Title>Giving the external function a Haskell name
70 </Title>
71
72 <Para>
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 '.
78
79 <Footnote>
80 <Para>
81 Notice that with Haskell 98, underscore ('&lowbar;') is included in
82 the character class <Literal>small</Literal>.
83 </Para>
84 </Footnote>
85
86 </Para>
87
88 <Para>
89 <ProgramListing>
90 varid : small ( small | large | udigit | ' )*
91 </ProgramListing>
92 </Para>
93
94 </Sect2>
95
96 <Sect2 id="sec-ffi-prim-ext-name">
97 <Title>Naming the external function
98 </Title>
99
100 <Para>
101 The name of the external function is a string:
102 </Para>
103
104 <ProgramListing>
105 ext_fun  : string</ProgramListing>
106
107 <Para>
108 For example,
109 </Para>
110
111 <ProgramListing>
112 foreign import stdcall "RegCloseKey" regCloseKey :: Ptr a -> IO ()
113 </ProgramListing>
114
115 <Para>
116 states that the external function named <Function>RegCloseKey</Function> should be bound to the Haskell name <Function>regCloseKey</Function>.</Para>
117
118 <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>
125
126 <Para>
127 If the Haskell name of the imported function is identical to the
128 external name, the <Literal>ext&lowbar;fun</Literal> can be
129 omitted. e.g.:
130 </Para>
131
132 <Para>
133
134 <ProgramListing>
135 foreign import sin :: Double -> IO Double
136 </ProgramListing>
137
138 </Para>
139
140 <Para>
141 is identical to 
142 </Para>
143
144 <Para>
145
146 <ProgramListing>
147 foreign import "sin" sin :: Double -> IO Double
148 </ProgramListing>
149
150 </Para>
151
152 </Sect2>
153
154 <Sect2 id="sec-ffi-cconv">
155 <Title>Calling conventions
156 </Title>
157
158 <Para>
159 The number of calling conventions supported is fixed:
160 </Para>
161
162 <Para>
163
164 <ProgramListing>
165 callconv : ccall | stdcall
166 </ProgramListing>
167
168 </Para>
169
170 <Para>
171 <VariableList>
172
173 <VarListEntry>
174 <Term><Literal>ccall</Literal></Term>
175 <ListItem>
176 <Para>
177 The 'default' calling convention on a platform, i.e., the one
178 used to do (C) function calls.
179 </Para>
180
181 <Para>
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.
185 </Para>
186 </ListItem>
187 </VarListEntry>
188 <VarListEntry>
189 <Term><Literal>stdcall</Literal></Term>
190 <ListItem>
191 <Para>
192 A Win32 specific calling convention. The same as <Literal>ccall</Literal>, except
193 that the callee cleans up the C stack before returning.
194
195 <Footnote>
196 <Para>
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>.
201 </Para>
202 </Footnote>
203
204 </Para>
205 </ListItem>
206 </VarListEntry>
207 </VariableList>
208 </Para>
209
210 <Para>
211 <Emphasis remap="bf">Some remarks:</Emphasis>
212
213 <ItemizedList>
214 <ListItem>
215
216 <Para>
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>.
224 </Para>
225 </ListItem>
226 <ListItem>
227
228 <Para>
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.
237 </Para>
238 </ListItem>
239 <ListItem>
240
241 <Para>
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.
246 </Para>
247 </ListItem>
248
249 </ItemizedList>
250
251 </Para>
252
253 </Sect2>
254
255 <Sect2 id="sec-ffi-prim-types">
256 <Title>External function types
257 </Title>
258
259 <Para>
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):
262 </Para>
263
264 <Para>
265
266 <ProgramListing>
267 prim_type : IO prim_result
268           | prim_result
269           | prim_arg '->' prim_type
270 </ProgramListing>
271
272 </Para>
273
274 <Para>
275
276 <ItemizedList>
277 <ListItem>
278
279 <Para>
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.
283 </Para>
284 </ListItem>
285 <ListItem>
286
287 <Para>
288 The external function is strict in all its arguments.
289 </Para>
290 </ListItem>
291
292 </ItemizedList>
293
294 </Para>
295
296 <Para>
297 <XRef LinkEnd="sec-ffi-results"> defines
298 <Literal>prim&lowbar;result</Literal>; <XRef LinkEnd="sec-ffi-arguments">
299 defines <Literal>prim&lowbar;arg</Literal>.
300 </Para>
301
302 <Sect3 id="sec-ffi-arguments">
303 <Title>Argument types
304 </Title>
305
306 <Para>
307 The external function expects zero or more arguments. The set of legal
308 argument types is restricted to the following set:
309 </Para>
310
311 <Para>
312
313 <ProgramListing>
314 prim_arg : ext_ty | new_ty | ForeignPtr a
315
316 new_ty : a Haskell newtype of a prim_arg.
317
318 ext_ty : int_ty   | word_ty | float_ty
319        | Ptr a    | Char    | StablePtr a
320        | Bool
321
322 int_ty       : Int   | Int8   | Int16   | Int32 | Int64
323 word_ty      : Word8 | Word16 | Word32  | Word64
324 float_ty     : Float | Double
325 </ProgramListing>
326
327 </Para>
328
329 <Para>
330
331 <ItemizedList>
332 <ListItem>
333
334 <Para>
335 <Literal>ext&lowbar;ty</Literal> represent the set of basic types supported by
336 C-like languages, although the numeric types are explicitly sized.
337
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">
341 for details.
342
343 </Para>
344 </ListItem>
345 <ListItem>
346
347 <Para>
348 <Literal>prim&lowbar;arg</Literal> represent the set of permissible
349 argument types. In addition to <Literal>ext&lowbar;ty</Literal>,
350 <Literal>ForeignPtr</Literal> is also included.
351
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.
360
361 </Para>
362 </ListItem>
363 <ListItem>
364
365 <Para>
366 Haskell <Literal>newtype</Literal>s that wrap up a
367 <Literal>prim&lowbar;arg</Literal> type can also be passed to external
368 functions.
369 </Para>
370 </ListItem>
371 <ListItem>
372
373 <Para>
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.
377
378 </Para>
379 </ListItem>
380 <ListItem>
381
382 <Para>
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.
386 </Para>
387 </ListItem>
388
389 <ListItem>
390 <Para>
391 A GHC extension is the support for unboxed types:
392
393
394 <ProgramListing>
395 prim_arg : ...  | unboxed_h_ty
396 ext_ty   : .... | unboxed_ext_ty
397
398 unboxed_ext_ty : Int#   | Word#    | Char#
399                | Float# | Double#  | Addr# 
400                | StablePtr# a
401 unboxed_h_ty : MutableByteArray# | ForeignObj#
402              | ByteArray#
403 </ProgramListing>
404
405
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.)
410 </Para>
411 </ListItem>
412
413 </ItemizedList>
414
415 </Para>
416
417 </Sect3>
418
419 <Sect3 id="sec-ffi-results">
420 <Title>Result type
421 </Title>
422
423 <Para>
424 An external function is permitted to return the following
425 range of types:
426 </Para>
427
428 <Para>
429
430 <ProgramListing>
431 prim_result : ext_ty | new_ext_ty | ()
432
433 new_ext_ty : a Haskell newtype of an ext_ty.
434 </ProgramListing>
435
436 </Para>
437
438 <Para>
439 where <Literal>()</Literal> represents <Literal>void</Literal> / no result. 
440 </Para>
441
442 <Para>
443
444 <ItemizedList>
445 <ListItem>
446
447 <Para>
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.
451 </Para>
452 </ListItem>
453 <ListItem>
454
455 <Para>
456 Only external types (<Literal>ext&lowbar;ty</Literal>) can be passed
457 back, i.e., returning <Literal>ForeignPtr</Literal>s is not
458 supported/allowed.
459 </Para>
460 </ListItem>
461 <ListItem>
462
463 <Para>
464 Haskell newtypes that wrap up <Literal>ext&lowbar;ty</Literal> are also permitted.
465 </Para>
466 </ListItem>
467
468 </ItemizedList>
469
470 </Para>
471
472 </Sect3>
473
474 </Sect2>
475
476 <Sect2 id="sec-ffi-mapping">
477 <Title>Type mapping
478 </Title>
479
480 <Para>
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.
488 </Para>
489
490 <Para>
491
492 <Table id="sec-ffi-mapping-table">
493 <Title>Mapping of Haskell types to C types</Title>
494
495 <TGroup Cols="4">
496 <ColSpec Align="Left" Colsep="0">
497 <ColSpec Align="Left" Colsep="0">
498 <ColSpec Align="Left" Colsep="0">
499 <ColSpec Align="Left" Colsep="0">
500 <TBody>
501 <Row RowSep="1">
502 <Entry>Haskell type </Entry>
503 <Entry> C type </Entry>
504 <Entry> requirement </Entry>
505 <Entry> range (9) </Entry>
506 <Entry> </Entry>
507 <Entry> </Entry>
508 </Row>
509 <Row>
510 <Entry>
511 <Literal>Char</Literal> </Entry>
512 <Entry> <Literal>HsChar</Literal> </Entry>
513 <Entry> unspec. integral type </Entry>
514 <Entry> <Literal>HS&lowbar;CHAR&lowbar;MIN</Literal> .. <Literal>HS&lowbar;CHAR&lowbar;MAX</Literal></Entry>
515 </Row>
516 <Row>
517 <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&lowbar;INT&lowbar;MIN</Literal> ..
522 <Literal>HS&lowbar;INT&lowbar;MAX</Literal></Entry>
523 </Row>
524 <Row>
525 <Entry>
526 <Literal>Int8</Literal> (2) </Entry>
527 <Entry> <Literal>HsInt8</Literal> </Entry>
528 <Entry> 8 bit signed integral </Entry>
529 <Entry> <Literal>HS&lowbar;INT8&lowbar;MIN</Literal> 
530 ..
531 <Literal>HS&lowbar;INT8&lowbar;MAX</Literal></Entry>
532 </Row>
533 <Row>
534 <Entry>
535 <Literal>Int16</Literal> (2) </Entry>
536 <Entry> <Literal>HsInt16</Literal> </Entry>
537 <Entry> 16 bit signed integral </Entry>
538 <Entry> <Literal>HS&lowbar;INT16&lowbar;MIN</Literal>
539 .. <Literal>HS&lowbar;INT16&lowbar;MAX</Literal></Entry>
540 </Row>
541 <Row>
542 <Entry>
543 <Literal>Int32</Literal> (2) </Entry>
544 <Entry> <Literal>HsInt32</Literal> </Entry>
545 <Entry> 32 bit signed integral </Entry>
546 <Entry> <Literal>HS&lowbar;INT32&lowbar;MIN</Literal> ..
547 <Literal>HS&lowbar;INT32&lowbar;MAX</Literal></Entry>
548 </Row>
549 <Row>
550 <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&lowbar;INT64&lowbar;MIN</Literal> ..
555 <Literal>HS&lowbar;INT64&lowbar;MAX</Literal></Entry>
556 </Row>
557 <Row>
558 <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&lowbar;WORD8&lowbar;MAX</Literal></Entry>
564 </Row>
565 <Row>
566 <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&lowbar;WORD16&lowbar;MAX</Literal></Entry>
572 </Row>
573 <Row>
574 <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&lowbar;WORD32&lowbar;MAX</Literal></Entry>
580 </Row>
581 <Row>
582 <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&lowbar;WORD64&lowbar;MAX</Literal></Entry>
588 </Row>
589 <Row>
590 <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>
595 </Row>
596 <Row>
597 <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>
602 </Row>
603 <Row>
604 <Entry>
605 <Literal>Bool</Literal> </Entry>
606 <Entry> <Literal>HsBool</Literal> </Entry>
607 <Entry> unspec. integral type </Entry>
608 <Entry> (11) </Entry>
609 </Row>
610 <Row>
611 <Entry>
612 <Literal>Ptr a</Literal> </Entry>
613 <Entry> <Literal>HsPtr</Literal> </Entry>
614 <Entry> void* (6) </Entry>
615 <Entry> </Entry>
616 </Row>
617 <Row>
618 <Entry>
619 <Literal>ForeignPtr a</Literal> </Entry>
620 <Entry> <Literal>HsForeignPtr</Literal> </Entry>
621 <Entry> void* (7) </Entry>
622 <Entry> </Entry>
623 </Row>
624 <Row>
625 <Entry>
626 <Literal>StablePtr a</Literal> </Entry>
627 <Entry> <Literal>HsStablePtr</Literal> </Entry>
628 <Entry> void* (8) </Entry>
629 <Entry> </Entry>
630 </Row>
631 </TBody>
632
633 </TGroup>
634
635 </Table>
636
637 </Para>
638
639 <Para>
640 <Emphasis remap="bf">Some remarks:</Emphasis>
641
642 <OrderedList>
643 <ListItem>
644
645 <Para>
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.
649 </Para>
650 </ListItem>
651 <ListItem>
652
653 <Para>
654 The sized numeric types <Literal>Hs&lcub;Int,Word&rcub;&lcub;8,16,32,64&rcub;</Literal> have
655 a 1-1 mapping to ISO C 99's <Literal>&lcub;,u&rcub;int&lcub;8,16,32,64&rcub;&lowbar;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.
658 </Para>
659 </ListItem>
660 <ListItem>
661
662 <Para>
663 An implementation which does not support 64 bit integral types
664 on the C side should implement <Literal>Hs&lcub;Int,Word&rcub;64</Literal> as a struct. In
665 this case the bounds <Constant>HS&lowbar;INT64&lowbar;&lcub;MIN,MAX&rcub;</Constant> and <Constant>HS&lowbar;WORD64&lowbar;MAX</Constant>
666 are undefined.
667 </Para>
668 </ListItem>
669 <ListItem>
670
671 <Para>
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>.
675 </Para>
676 </ListItem>
677 <ListItem>
678
679 <Para>
680 It is guaranteed that <Literal>Hs&lcub;Float,Double&rcub;</Literal> are one of C's
681 floating-point types <Literal>float</Literal>/<Literal>double</Literal>/<Literal>long double</Literal>.
682 </Para>
683 </ListItem>
684 <ListItem>
685
686 <Para>
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&amp;R, Appendix A6.8).
690 </Para>
691 </ListItem>
692 <ListItem>
693
694 <Para>
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.
699 </Para>
700 </ListItem>
701 <ListItem>
702
703 <Para>
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. 
708 </Para>
709 </ListItem>
710 <ListItem>
711
712 <Para>
713 The bounds are preprocessor macros, so they can be used in
714 <Literal>&num;if</Literal> and for array bounds.
715 </Para>
716 </ListItem>
717 <ListItem>
718
719 <Para>
720 Floating-point limits are a little bit more complicated, so
721 preprocessor macros mirroring ISO C's <Filename>float.h</Filename> are provided:
722
723 <ProgramListing>
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
735 </ProgramListing>
736
737 </Para>
738 </ListItem>
739 <ListItem>
740
741 <Para>
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.
745 </Para>
746 </ListItem>
747 <ListItem>
748
749 <Para>
750 To avoid name clashes, identifiers starting with <Literal>Hs</Literal> and
751 macros starting with <Literal>HS&lowbar;</Literal> are reserved for the FFI.
752 </Para>
753 </ListItem>
754 <ListItem>
755
756 <Para>
757 <Emphasis>GHC only:</Emphasis> The GHC specific types <Literal>ByteArray</Literal> and
758 <Literal>MutableByteArray</Literal> both map to <Literal>char*</Literal>.
759 </Para>
760 </ListItem>
761
762 </OrderedList>
763
764 </Para>
765
766 </Sect2>
767
768 <Sect2 id="sec-ffi-prim-remarks">
769 <Title>Some <Literal>foreign import</Literal> wrinkles
770 </Title>
771
772 <Para>
773
774 <ItemizedList>
775 <ListItem>
776
777 <Para>
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.
785
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
789 how to do this.)
790
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.
794
795 </Para>
796 </ListItem>
797 <ListItem>
798
799 <Para>
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,
804
805
806 <ProgramListing>
807 foreign import "mumble" mumble :: ForeignPtr a -> IO ()
808
809 f :: Ptr a -> IO ()
810 f ptr = do
811   fo &#60;- newForeignObj ptr myFinalizer
812   mumble fo
813 </ProgramListing>
814
815
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.
823
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
828 valid) is avoided.
829
830
831 </Para>
832 </ListItem>
833
834 </ItemizedList>
835
836 </Para>
837
838 </Sect2>
839
840 </Sect1>
841
842 <Sect1 id="sec-ffi-prim-dynamic">
843 <Title>Invoking external functions via a pointer
844 </Title>
845
846 <Para>
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>. 
853 </Para>
854
855 <Para>
856 An extension of <Literal>foreign import</Literal> is the support for <Emphasis>dynamic</Emphasis> type
857 casts of external names/addresses:
858 </Para>
859
860 <Para>
861
862 <ProgramListing>
863 topdecl 
864    : ...
865    ..
866    | 'foreign' 'import' [callconv] 'dynamic' ['unsafe']
867             varid :: Addr -> (prim_args -> IO prim_result)
868 </ProgramListing>
869
870 </Para>
871
872 <Para>
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
878 arguments.
879 </Para>
880
881 <Para>
882 What are the uses of this? Native invocation of COM methods,
883 <Footnote>
884 <Para>
885 Or the interfacing to any other software component technologies.
886 </Para>
887 </Footnote>
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
890 and execute code.
891 </Para>
892
893 </Sect1>
894
895 <Sect1 id="sec-ffi-entry">
896 <Title>Exposing Haskell functions
897 </Title>
898
899 <Para>
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>:
904 </Para>
905
906 <Para>
907
908 <ProgramListing>
909 topdecl 
910   : ...
911   ..
912   | 'foreign' 'export' callconv [ext_name] varid :: prim_type
913 </ProgramListing>
914
915 </Para>
916
917 <Para>
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:
924 </Para>
925
926 <Para>
927
928 <ProgramListing>
929 foreign export ccall "foo" bar :: Int -> Addr -> IO Double
930 </ProgramListing>
931
932 </Para>
933
934 <Para>
935 will cause a Haskell system to generate the following C callable
936 function:
937 </Para>
938
939 <Para>
940
941 <ProgramListing>
942 HsDouble foo(HsInt arg1, HsAddr arg2);
943 </ProgramListing>
944
945 </Para>
946
947 <Para>
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>. 
950 </Para>
951
952 <Para>
953
954 <ItemizedList>
955 <ListItem>
956
957 <Para>
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&lowbar;type</Literal>.
960 </Para>
961 </ListItem>
962 <ListItem>
963
964 <Para>
965 It is not possible to directly export operator symbols.
966 </Para>
967 </ListItem>
968 <ListItem>
969
970 <Para>
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,
975 this is legal:
976
977
978 <ProgramListing>
979    f :: Num a => a -> a
980    foreign export ccall "fInt"   f :: Int -> Int
981    foreign export ccall "fFloat" f :: Float -> Float
982 </ProgramListing>
983
984
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>.
988
989 </Para>
990 </ListItem>
991 <ListItem>
992
993 <Para>
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
996 outside world.
997 </Para>
998 </ListItem>
999
1000 </ItemizedList>
1001
1002 </Para>
1003
1004 <Sect2 id="sec-ffi-callback">
1005 <Title>Exposing Haskell function values
1006 </Title>
1007
1008 <Para>
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:
1014 </Para>
1015
1016 <Para>
1017
1018 <ProgramListing>
1019 topdecl 
1020   : ...
1021   ..
1022   | 'foreign' 'export' [callconv] 'dynamic' varid :: prim_type -> IO Addr
1023 </ProgramListing>
1024
1025 </Para>
1026
1027 <Para>
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.
1032 </Para>
1033
1034 <Para>
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.
1038 </Para>
1039
1040 <Para>
1041 The mapping between the argument to a <Literal>foreign export dynamic</Literal>
1042 declaration and its corresponding C function pointer type, is as
1043 follows:
1044 </Para>
1045
1046 <Para>
1047
1048 <ProgramListing>
1049 typedef cType[[Res]] (*Varid_FunPtr)
1050         (cType[[Ty_1]] ,.., cType[[Ty_n]]);
1051 </ProgramListing>
1052
1053 </Para>
1054
1055 <Para>
1056 where <Literal>cType[[]]</Literal> is the Haskell to C type mapping presented
1057 in <XRef LinkEnd="sec-ffi-mapping">.
1058 </Para>
1059
1060 <Para>
1061 To make it all a bit more concrete, here's an example:
1062 </Para>
1063
1064 <Para>
1065
1066 <ProgramListing>
1067 foreign export dynamic mkCallback :: (Int -> IO Int) -> IO Addr
1068
1069 foreign import registerCallback :: Addr -> IO ()
1070
1071 exportCallback :: (Int -> IO Int) -> IO ()
1072 exportCallback f = do
1073   fx &#60;- mkCallback f
1074   registerCallback fx
1075 </ProgramListing>
1076
1077 </Para>
1078
1079 <Para>
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>,
1083 is:
1084 <Footnote>
1085 <Para>
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
1088 to do so.
1089 </Para>
1090 </Footnote>
1091
1092 </Para>
1093
1094 <Para>
1095
1096 <ProgramListing>
1097 typedef HsInt (*mkCallback_FunPtr) (HsInt arg1);
1098 </ProgramListing>
1099
1100 </Para>
1101
1102 <Para>
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
1109 done by calling:
1110 </Para>
1111
1112 <Para>
1113
1114 <ProgramListing>
1115 void freeHaskellFunctionPtr(void *ptr);
1116 </ProgramListing>
1117
1118 </Para>
1119
1120 <Para>
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,
1124 </Para>
1125
1126 <Para>
1127
1128 <ProgramListing>
1129 Foreign.freeHaskellFunctionPtr :: Addr -> IO ()
1130 </ProgramListing>
1131
1132 </Para>
1133
1134 </Sect2>
1135
1136 <Sect2 id="sec-ffi-foreign-label">
1137 <Title>Code addresses
1138 </Title>
1139
1140 <Para>
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:
1148 </Para>
1149
1150 <Para>
1151
1152 <ProgramListing>
1153 foreign label "freeAtLast" addrOf_freeAtLast :: Addr
1154 </ProgramListing>
1155
1156 </Para>
1157
1158 <Para>
1159 The meaning of this declaration is that <Literal>addrOf&lowbar;freeAtLast</Literal> will now
1160 contain the address of the label <Literal>freeAtLast</Literal>.
1161 </Para>
1162
1163 </Sect2>
1164
1165 </Sect1>
1166 <!-- This doesn't need to be seen in the docs
1167 <Sect1 id="sec-ffi-changelog">
1168 <Title>Change history
1169 </Title>
1170
1171 <Para>
1172
1173 <ItemizedList>
1174 <ListItem>
1175
1176 <Para>
1177 0.95 &gt; 0.96:
1178
1179 <ItemizedList>
1180 <ListItem>
1181
1182 <Para>
1183 changed the C representation of
1184 <Literal>Haskell&lowbar;ForeignPtr</Literal> from
1185 <Literal>(long*)</Literal> to <Literal>(void*)</Literal> ANSI C
1186 guarantees that <Literal>(void*)</Literal> is the widest possible data
1187 pointer.
1188 </Para>
1189 </ListItem>
1190 <ListItem>
1191
1192 <Para>
1193 Updated defnition of <Literal>varid</Literal> in
1194 <XRef LinkEnd="sec-ffi-prim-name"> to reflect Haskell98's.
1195 </Para>
1196 </ListItem>
1197 <ListItem>
1198
1199 <Para>
1200 Replaced confusing uses of <Literal>stdcall</Literal> with <Literal>ccall</Literal>.
1201 </Para>
1202 </ListItem>
1203
1204 </ItemizedList>
1205
1206 </Para>
1207 </ListItem>
1208 <ListItem>
1209
1210 <Para>
1211 0.96 &gt; 0.97:
1212
1213 <ItemizedList>
1214 <ListItem>
1215
1216 <Para>
1217 Simplified the calling convention section, support for Pascal (and
1218 fastcall) calling conventions dropped. 
1219 </Para>
1220 </ListItem>
1221 <ListItem>
1222
1223 <Para>
1224 Clarified that the arguments to a safe <Literal>foreign import</Literal> must have
1225 lifetimes that equal that of a C function application.
1226 </Para>
1227 </ListItem>
1228 <ListItem>
1229
1230 <Para>
1231 Outlawed the use of the (GHC specific) types <Literal>ByteArray</Literal>
1232 and <Literal>MutableByteArray</Literal> in safe <Literal>foreign import</Literal>s.
1233 </Para>
1234 </ListItem>
1235 <ListItem>
1236
1237 <Para>
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.
1240 </Para>
1241 </ListItem>
1242 <ListItem>
1243
1244 <Para>
1245 Simplified section which sketches a possible implementation.
1246 </Para>
1247 </ListItem>
1248 <ListItem>
1249
1250 <Para>
1251 Use <Literal>Hs</Literal> as prefix for the typedefs for the primitive Haskell
1252 FFI types rather than the longer <Literal>Haskell&lowbar;</Literal>.
1253 </Para>
1254 </ListItem>
1255
1256 </ItemizedList>
1257
1258 </Para>
1259 </ListItem>
1260 <ListItem>
1261
1262 <Para>
1263 0.97 &gt; 0.98:
1264
1265 <ItemizedList>
1266 <ListItem>
1267
1268 <Para>
1269 Leave out implementation section; of limited interest.
1270 </Para>
1271 </ListItem>
1272 <ListItem>
1273
1274 <Para>
1275 Outlined the criteria used to decide on what calling
1276 conventions to support.
1277 </Para>
1278 </ListItem>
1279 <ListItem>
1280
1281 <Para>
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
1284 functions.
1285 </Para>
1286 </ListItem>
1287
1288 </ItemizedList>
1289
1290 </Para>
1291 </ListItem>
1292 <ListItem>
1293
1294 <Para>
1295 0.98 &gt; 0.99:
1296
1297 <ItemizedList>
1298 <ListItem>
1299
1300 <Para>
1301 Updated the section on type mapping to integrate some comments
1302 from people on &lt;ffi@haskell.org&gt; (a fair chunk of the text
1303 in that section was contributed by Sven Panne.)
1304 </Para>
1305 </ListItem>
1306 <ListItem>
1307
1308 <Para>
1309 <Function>freeHaskellFunctionPtr</Function> should belong to module <Literal>Foreign</Literal>, not <Literal>IOExts</Literal>.
1310 </Para>
1311 </ListItem>
1312
1313 </ItemizedList>
1314
1315
1316 </Para>
1317 </ListItem>
1318 <ListItem>
1319
1320 <Para>
1321 0.99 &gt; 0.99.1:
1322
1323 <ItemizedList>
1324 <ListItem>
1325
1326 <Para>
1327 <Literal>Bool</Literal> is now an FFI-supported type (i.e., added it to
1328 <Literal>ext&lowbar;ty</Literal>.)
1329 </Para>
1330 </ListItem>
1331
1332 </ItemizedList>
1333
1334
1335 </Para>
1336 </ListItem>
1337
1338 </ItemizedList>
1339
1340 </Para>
1341
1342 </Sect1>
1343 -->