[project @ 2000-06-08 10:48:58 by rrt]
[ghc-hetmet.git] / docs / ffi.sgml
1 <Sect1 id="sec-intro">
2 <Title>Introduction
3 </Title>
4
5 <Para>
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.
11 </Para>
12
13 <Para>
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
19 uses this FFI.
20 </Para>
21
22 <Para>
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.
28 </Para>
29
30 </Sect1>
31
32 <Sect1 id="sec-primitive">
33 <Title>Calling foreign functions
34 </Title>
35
36 <Para>
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:
39 </Para>
40
41 <Para>
42
43 <ProgramListing>
44 topdecl 
45   : ...
46   ..
47   | 'foreign' 'import' [callconv] [ext_fun] ['unsafe'] varid '::' prim_type
48 </ProgramListing>
49
50 </Para>
51
52 <Para>
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&lowbar;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&lowbar;fun</Literal>) and its calling interface
58 (<Literal>callconv</Literal>.)
59 </Para>
60
61 <Para>
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.
69 </Para>
70
71 <Sect2 id="sec-prim-name">
72 <Title>Giving the external function a Haskell name
73 </Title>
74
75 <Para>
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 '.
81
82 <Footnote>
83 <Para>
84 Notice that with Haskell 98, underscore ('&lowbar;') is included in
85 the character class <Literal>small</Literal>.
86 </Para>
87 </Footnote>
88
89 </Para>
90
91 <Para>
92 <ProgramListing>
93 varid : small ( small | large | udigit | ' )*
94 </ProgramListing>
95 </Para>
96
97 </Sect2>
98
99 <Sect2 id="sec-prim-ext-name">
100 <Title>Naming the external function
101 </Title>
102
103 <Para>
104 The name of the external function consists of two parts,
105 one specifying its location, the other its name:
106 </Para>
107
108 <Para>
109
110 <ProgramListing>
111 ext_fun  : ext_loc ext_name
112          | ext_name
113
114 ext_name : string
115 ext_loc  : string
116 </ProgramListing>
117
118 </Para>
119
120 <Para>
121 For example,
122 </Para>
123
124 <Para>
125
126 <ProgramListing>
127 foreign import stdcall "Advapi32" "RegCloseKey" regCloseKey :: Addr -&#62; IO ()
128 </ProgramListing>
129
130 </Para>
131
132 <Para>
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>. 
140 </Para>
141
142 <Para>
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.
147 </Para>
148
149 <Para>
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.
152 </Para>
153
154 <Para>
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.
159 </Para>
160
161 <Para>
162 An implementation is <Emphasis>expected</Emphasis> to be able to intelligently
163 transform the <Literal>ext&lowbar;loc</Literal> location to fit platform-specific
164 practices for naming dynamic libraries. For instance, given the
165 declaration
166 </Para>
167
168 <Para>
169
170 <ProgramListing>
171 foreign import "Foo" "foo" foo :: Int -&#62; Int -&#62; IO ()
172 </ProgramListing>
173
174 </Para>
175
176 <Para>
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&lowbar;loc</Literal>s are transformed and resolved, including the list of
184 directories searched (and the order in which they are.)
185 </Para>
186
187 <Para>
188 In the case the Haskell name of the imported function is identical to
189 the external name, the <Literal>ext&lowbar;fun</Literal> can be omitted. i.e.,
190 </Para>
191
192 <Para>
193
194 <ProgramListing>
195 foreign import sin :: Double -&#62; IO Double
196 </ProgramListing>
197
198 </Para>
199
200 <Para>
201 is identical to 
202 </Para>
203
204 <Para>
205
206 <ProgramListing>
207 foreign import "sin" sin :: Double -&#62; IO Double
208 </ProgramListing>
209
210 </Para>
211
212 </Sect2>
213
214 <Sect2 id="sec-cconv">
215 <Title>Calling conventions
216 </Title>
217
218 <Para>
219 The number of calling conventions supported is fixed:
220 </Para>
221
222 <Para>
223
224 <ProgramListing>
225 callconv : ccall | stdcall
226 </ProgramListing>
227
228 </Para>
229
230 <Para>
231 <VariableList>
232
233 <VarListEntry>
234 <Term><Literal>ccall</Literal></Term>
235 <ListItem>
236 <Para>
237 The 'default' calling convention on a platform, i.e., the one
238 used to do (C) function calls.
239 </Para>
240
241 <Para>
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.
245 </Para>
246 </ListItem>
247 </VarListEntry>
248 <VarListEntry>
249 <Term><Literal>stdcall</Literal></Term>
250 <ListItem>
251 <Para>
252 A Win32 specific calling convention. The same as <Literal>ccall</Literal>, except
253 that the callee cleans up the C stack before returning.
254
255 <Footnote>
256 <Para>
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>.
261 </Para>
262 </Footnote>
263
264 </Para>
265 </ListItem>
266 </VarListEntry>
267 </VariableList>
268 </Para>
269
270 <Para>
271 <Emphasis remap="bf">Some remarks:</Emphasis>
272
273 <ItemizedList>
274 <ListItem>
275
276 <Para>
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>.
284 </Para>
285 </ListItem>
286 <ListItem>
287
288 <Para>
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.
297 </Para>
298 </ListItem>
299 <ListItem>
300
301 <Para>
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.
306 </Para>
307 </ListItem>
308
309 </ItemizedList>
310
311 </Para>
312
313 </Sect2>
314
315 <Sect2 id="sec-prim-types">
316 <Title>External function types
317 </Title>
318
319 <Para>
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):
322 </Para>
323
324 <Para>
325
326 <ProgramListing>
327 prim_type : IO prim_result
328           | prim_result
329           | prim_arg '-&#62;' prim_type
330 </ProgramListing>
331
332 </Para>
333
334 <Para>
335
336 <ItemizedList>
337 <ListItem>
338
339 <Para>
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.
343 </Para>
344 </ListItem>
345 <ListItem>
346
347 <Para>
348 The external function is strict in all its arguments.
349 </Para>
350 </ListItem>
351 <ListItem>
352
353 <Para>
354 <Emphasis>GHC only:</Emphasis> The GHC FFI implementation provides one extension
355 to <Literal>prim&lowbar;type</Literal>:
356
357
358 <ProgramListing>
359 prim_type : ... 
360           | unsafe_arr_ty '-&#62;' prim_type
361
362 unsafe_arr_ty : ByteArray a
363               | MutableByteArray i s a
364 </ProgramListing>
365
366
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">
370 for more details.
371 </Para>
372 </ListItem>
373
374 </ItemizedList>
375
376 </Para>
377
378 <Para>
379 Section <XRef LinkEnd="sec-results"> defines
380 <Literal>prim&lowbar;result</Literal>; Section <XRef LinkEnd="sec-arguments">
381 defines <Literal>prim&lowbar;arg</Literal>.
382 </Para>
383
384 <Sect3 id="sec-arguments">
385 <Title>Argument types
386 </Title>
387
388 <Para>
389 The external function expects zero or more arguments. The set of legal
390 argument types is restricted to the following set:
391 </Para>
392
393 <Para>
394
395 <ProgramListing>
396 prim_arg : ext_ty | new_ty | ForeignObj
397
398 new_ty : a Haskell newtype of a prim_arg.
399
400 ext_ty : int_ty   | word_ty | float_ty
401        | Addr     | Char    | StablePtr a
402        | Bool
403
404 int_ty       : Int   | Int8   | Int16   | Int32 | Int64
405 word_ty      : Word8 | Word16 | Word32  | Word64
406 float_ty     : Float | Double
407 </ProgramListing>
408
409 </Para>
410
411 <Para>
412
413 <ItemizedList>
414 <ListItem>
415
416 <Para>
417 <Literal>ext&lowbar;ty</Literal> represent the set of basic types supported by
418 C-like languages, although the numeric types are explicitly sized.
419
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">
423 for details.
424
425 </Para>
426 </ListItem>
427 <ListItem>
428
429 <Para>
430 <Literal>prim&lowbar;arg</Literal> represent the set of permissible argument types. In
431 addition to <Literal>ext&lowbar;ty</Literal>, <Literal>ForeignObj</Literal> is also included.
432
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.
439
440 </Para>
441 </ListItem>
442 <ListItem>
443
444 <Para>
445 Haskell <Literal>newtype</Literal>s that wrap up a <Literal>prim&lowbar;arg</Literal> type can also
446 be passed to external functions. 
447 </Para>
448 </ListItem>
449 <ListItem>
450
451 <Para>
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.
455
456 </Para>
457 </ListItem>
458 <ListItem>
459
460 <Para>
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.
464 </Para>
465 </ListItem>
466 <ListItem>
467
468 <Para>
469 <Emphasis>GHC only:</Emphasis> GHC's implementation of the FFI provides
470 two extensions:
471
472 <ItemizedList>
473 <ListItem>
474
475 <Para>
476 Support for passing heap allocated byte arrays to an external
477 function
478
479 <ProgramListing>
480 prim_type : ... 
481           | prim_arg '-&#62;' prim_type
482           | unsafe_arr_ty '-&#62;' prim_type
483
484 unsafe_arr_ty : ByteArray a
485               | MutableByteArray i s a
486 </ProgramListing>
487
488
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.
499
500 </Para>
501 </ListItem>
502 <ListItem>
503
504 <Para>
505 Another GHC extension is the support for unboxed types:
506
507
508 <ProgramListing>
509 prim_arg : ...  | unboxed_h_ty
510 ext_ty   : .... | unboxed_ext_ty
511
512 unboxed_ext_ty : Int#   | Word#    | Char#
513                | Float# | Double#  | Addr# 
514                | StablePtr# a
515 unboxed_h_ty : MutableByteArray# | ForeignObj#
516              | ByteArray#
517 </ProgramListing>
518
519
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.)
524 </Para>
525 </ListItem>
526
527 </ItemizedList>
528
529 </Para>
530 </ListItem>
531
532 </ItemizedList>
533
534 </Para>
535
536 </Sect3>
537
538 <Sect3 id="sec-results">
539 <Title>Result type
540 </Title>
541
542 <Para>
543 An external function is permitted to return the following
544 range of types:
545 </Para>
546
547 <Para>
548
549 <ProgramListing>
550 prim_result : ext_ty | new_ext_ty | ()
551
552 new_ext_ty : a Haskell newtype of an ext_ty.
553 </ProgramListing>
554
555 </Para>
556
557 <Para>
558 where <Literal>()</Literal> represents <Literal>void</Literal> / no result. 
559 </Para>
560
561 <Para>
562
563 <ItemizedList>
564 <ListItem>
565
566 <Para>
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.
570 </Para>
571 </ListItem>
572 <ListItem>
573
574 <Para>
575 Only external types (<Literal>ext&lowbar;ty</Literal>) can be passed back, i.e., returning
576 <Literal>ForeignObj</Literal>s is not supported/allowed. 
577 </Para>
578 </ListItem>
579 <ListItem>
580
581 <Para>
582 Haskell newtypes that wrap up <Literal>ext&lowbar;ty</Literal> are also permitted.
583 </Para>
584 </ListItem>
585
586 </ItemizedList>
587
588 </Para>
589
590 </Sect3>
591
592 </Sect2>
593
594 <Sect2 id="sec-mapping">
595 <Title>Type mapping
596 </Title>
597
598 <Para>
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.
606 </Para>
607
608 <Para>
609
610 <Table id="sec-mapping-table">
611 <Title>Mapping of Haskell types to C types</Title>
612
613 <TGroup Cols="6">
614 <ColSpec Align="Left" Colsep="0">
615 <ColSpec Align="Left" Colsep="0">
616 <ColSpec Align="Left" Colsep="0">
617 <ColSpec Align="Left" Colsep="0">
618 <ColSpec Align="Left" Colsep="0">
619 <ColSpec Align="Left" Colsep="0">
620 <TBody>
621 <Row RowSep="1">
622 <Entry>Haskell type </Entry>
623 <Entry> C type </Entry>
624 <Entry> requirement </Entry>
625 <Entry> range (9) </Entry>
626 <Entry> </Entry>
627 <Entry> </Entry>
628 </Row>
629 <Row>
630 <Entry>
631 <Literal>Char</Literal> </Entry>
632 <Entry> <Literal>HsChar</Literal> </Entry>
633 <Entry> unspec. integral type </Entry>
634 <Entry> <Literal>HS&lowbar;CHAR&lowbar;MIN</Literal> </Entry>
635 <Entry>..</Entry>
636 <Entry> <Literal>HS&lowbar;CHAR&lowbar;MAX</Literal></Entry>
637 </Row>
638 <Row>
639 <Entry>
640 <Literal>Int</Literal> </Entry>
641 <Entry> <Literal>HsInt</Literal> </Entry>
642 <Entry> signed integral of unspec. size(4) </Entry>
643 <Entry> <Literal>HS&lowbar;INT&lowbar;MIN</Literal> </Entry>
644 <Entry>..</Entry>
645 <Entry> <Literal>HS&lowbar;INT&lowbar;MAX</Literal></Entry>
646 </Row>
647 <Row>
648 <Entry>
649 <Literal>Int8</Literal> (2) </Entry>
650 <Entry> <Literal>HsInt8</Literal> </Entry>
651 <Entry> 8 bit signed integral </Entry>
652 <Entry> <Literal>HS&lowbar;INT8&lowbar;MIN</Literal> </Entry>
653 <Entry>..</Entry>
654 <Entry> <Literal>HS&lowbar;INT8&lowbar;MAX</Literal></Entry>
655 </Row>
656 <Row>
657 <Entry>
658 <Literal>Int16</Literal> (2) </Entry>
659 <Entry> <Literal>HsInt16</Literal> </Entry>
660 <Entry> 16 bit signed integral </Entry>
661 <Entry> <Literal>HS&lowbar;INT16&lowbar;MIN</Literal> </Entry>
662 <Entry>..</Entry>
663 <Entry> <Literal>HS&lowbar;INT16&lowbar;MAX</Literal></Entry>
664 </Row>
665 <Row>
666 <Entry>
667 <Literal>Int32</Literal> (2) </Entry>
668 <Entry> <Literal>HsInt32</Literal> </Entry>
669 <Entry> 32 bit signed integral </Entry>
670 <Entry> <Literal>HS&lowbar;INT32&lowbar;MIN</Literal> </Entry>
671 <Entry>..</Entry>
672 <Entry> <Literal>HS&lowbar;INT32&lowbar;MAX</Literal></Entry>
673 </Row>
674 <Row>
675 <Entry>
676 <Literal>Int64</Literal> (2,3) </Entry>
677 <Entry> <Literal>HsInt64</Literal> </Entry>
678 <Entry> 64 bit signed integral (3) </Entry>
679 <Entry> <Literal>HS&lowbar;INT64&lowbar;MIN</Literal> </Entry>
680 <Entry>..</Entry>
681 <Entry> <Literal>HS&lowbar;INT64&lowbar;MAX</Literal></Entry>
682 </Row>
683 <Row>
684 <Entry>
685 <Literal>Word8</Literal> (2) </Entry>
686 <Entry> <Literal>HsWord8</Literal> </Entry>
687 <Entry> 8 bit unsigned integral </Entry>
688 <Entry> <Literal>0</Literal> </Entry>
689 <Entry>..</Entry>
690 <Entry> <Literal>HS&lowbar;WORD8&lowbar;MAX</Literal></Entry>
691 </Row>
692 <Row>
693 <Entry>
694 <Literal>Word16</Literal> (2) </Entry>
695 <Entry> <Literal>HsWord16</Literal> </Entry>
696 <Entry> 16 bit unsigned integral </Entry>
697 <Entry> <Literal>0</Literal> </Entry>
698 <Entry>..</Entry>
699 <Entry> <Literal>HS&lowbar;WORD16&lowbar;MAX</Literal></Entry>
700 </Row>
701 <Row>
702 <Entry>
703 <Literal>Word32</Literal> (2) </Entry>
704 <Entry> <Literal>HsWord32</Literal> </Entry>
705 <Entry> 32 bit unsigned integral </Entry>
706 <Entry> <Literal>0</Literal> </Entry>
707 <Entry>..</Entry>
708 <Entry> <Literal>HS&lowbar;WORD32&lowbar;MAX</Literal></Entry>
709 </Row>
710 <Row>
711 <Entry>
712 <Literal>Word64</Literal> (2,3) </Entry>
713 <Entry> <Literal>HsWord64</Literal> </Entry>
714 <Entry> 64 bit unsigned integral (3) </Entry>
715 <Entry> <Literal>0</Literal> </Entry>
716 <Entry>..</Entry>
717 <Entry> <Literal>HS&lowbar;WORD64&lowbar;MAX</Literal></Entry>
718 </Row>
719 <Row>
720 <Entry>
721 <Literal>Float</Literal> </Entry>
722 <Entry> <Literal>HsFloat</Literal> </Entry>
723 <Entry> floating point of unspec. size (5) </Entry>
724 <Entry> (10) </Entry>
725 <Entry> </Entry>
726 <Entry> </Entry>
727 </Row>
728 <Row>
729 <Entry>
730 <Literal>Double</Literal> </Entry>
731 <Entry> <Literal>HsDouble</Literal> </Entry>
732 <Entry> floating point of unspec. size (5) </Entry>
733 <Entry> (10) </Entry>
734 <Entry> </Entry>
735 <Entry> </Entry>
736 </Row>
737 <Row>
738 <Entry>
739 <Literal>Bool</Literal> </Entry>
740 <Entry> <Literal>HsBool</Literal> </Entry>
741 <Entry> unspec. integral type </Entry>
742 <Entry> (11) </Entry>
743 <Entry> </Entry>
744 <Entry> </Entry>
745 </Row>
746 <Row>
747 <Entry>
748 <Literal>Addr</Literal> </Entry>
749 <Entry> <Literal>HsAddr</Literal> </Entry>
750 <Entry> void* (6) </Entry>
751 <Entry> </Entry>
752 <Entry> </Entry>
753 <Entry> </Entry>
754 </Row>
755 <Row>
756 <Entry>
757 <Literal>ForeignObj</Literal> </Entry>
758 <Entry> <Literal>HsForeignObj</Literal> </Entry>
759 <Entry> void* (7) </Entry>
760 <Entry> </Entry>
761 <Entry> </Entry>
762 <Entry> </Entry>
763 </Row>
764 <Row>
765 <Entry>
766 <Literal>StablePtr</Literal> </Entry>
767 <Entry> <Literal>HsStablePtr</Literal> </Entry>
768 <Entry> void* (8) </Entry>
769 <Entry> </Entry>
770 <Entry> </Entry>
771 <Entry> </Entry>
772 </Row>
773 <Row>
774 <Entry>
775 </Entry>
776 </Row>
777 </TBody>
778
779 </TGroup>
780
781 </Table>
782
783 </Para>
784
785 <Para>
786 <Emphasis remap="bf">Some remarks:</Emphasis>
787
788 <OrderedList>
789 <ListItem>
790
791 <Para>
792 A Haskell system that implements the FFI will supply a header file
793 <Filename>HsFFI.h</Filename> that includes target platform specific definitions
794 for the above types and values.
795 </Para>
796 </ListItem>
797 <ListItem>
798
799 <Para>
800 The sized numeric types <Literal>Hs&lcub;Int,Word&rcub;&lcub;8,16,32,64&rcub;</Literal> have
801 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
802 that doesn't support this revision of ISO C, a best-fit mapping
803 onto the supported C types is provided.
804 </Para>
805 </ListItem>
806 <ListItem>
807
808 <Para>
809 An implementation which does not support 64 bit integral types
810 on the C side should implement <Literal>Hs&lcub;Int,Word&rcub;64</Literal> as a struct. In
811 this case the bounds <Constant>HS&lowbar;INT64&lowbar;&lcub;MIN,MAX&rcub;</Constant> and <Constant>HS&lowbar;WORD64&lowbar;MAX</Constant>
812 are undefined.
813 </Para>
814 </ListItem>
815 <ListItem>
816
817 <Para>
818 A valid Haskell representation of <Literal>Int</Literal> has to be equal to or
819 wider than 30 bits. The <Literal>HsInt</Literal> synonym is guaranteed to map
820 onto a C type that satisifies Haskell's requirement for <Literal>Int</Literal>.
821 </Para>
822 </ListItem>
823 <ListItem>
824
825 <Para>
826 It is guaranteed that <Literal>Hs&lcub;Float,Double&rcub;</Literal> are one of C's
827 floating-point types <Literal>float</Literal>/<Literal>double</Literal>/<Literal>long double</Literal>.
828 </Para>
829 </ListItem>
830 <ListItem>
831
832 <Para>
833 It is guaranteed that <Literal>HsAddr</Literal> is of the same size as <Literal>void*</Literal>, so
834 any other pointer type can be converted to and from HsAddr without any
835 loss of information (K&amp;R, Appendix A6.8).
836 </Para>
837 </ListItem>
838 <ListItem>
839
840 <Para>
841 Foreign objects are handled like <Literal>Addr</Literal> by the FFI, so there
842 is again the guarantee that <Literal>HsForeignObj</Literal> is the same as
843 <Literal>void*</Literal>. The separate name is meant as a reminder that there is
844 a finalizer attached to the object pointed to.
845 </Para>
846 </ListItem>
847 <ListItem>
848
849 <Para>
850 Stable pointers are passed as addresses by the FFI, but this is
851 only because a <Literal>void*</Literal> is used as a generic container in most
852 APIs, not because they are real addresses. To make this special
853 case clear, a separate C type is used here. 
854 </Para>
855 </ListItem>
856 <ListItem>
857
858 <Para>
859 The bounds are preprocessor macros, so they can be used in
860 <Literal>&num;if</Literal> and for array bounds.
861 </Para>
862 </ListItem>
863 <ListItem>
864
865 <Para>
866 Floating-point limits are a little bit more complicated, so
867 preprocessor macros mirroring ISO C's <Filename>float.h</Filename> are provided:
868
869 <ProgramListing>
870 HS_{FLOAT,DOUBLE}_RADIX
871 HS_{FLOAT,DOUBLE}_ROUNDS
872 HS_{FLOAT,DOUBLE}_EPSILON
873 HS_{FLOAT,DOUBLE}_DIG
874 HS_{FLOAT,DOUBLE}_MANT_DIG
875 HS_{FLOAT,DOUBLE}_MIN
876 HS_{FLOAT,DOUBLE}_MIN_EXP
877 HS_{FLOAT,DOUBLE}_MIN_10_EXP
878 HS_{FLOAT,DOUBLE}_MAX
879 HS_{FLOAT,DOUBLE}_MAX_EXP
880 HS_{FLOAT,DOUBLE}_MAX_10_EXP
881 </ProgramListing>
882
883 </Para>
884 </ListItem>
885 <ListItem>
886
887 <Para>
888 It is guaranteed that Haskell's <Literal>False</Literal>/<Literal>True</Literal> map to
889 C's <Literal>0</Literal>/<Literal>1</Literal>, respectively, and vice versa. The mapping of
890 any other integral value to <Literal>Bool</Literal> is left unspecified.
891 </Para>
892 </ListItem>
893 <ListItem>
894
895 <Para>
896 To avoid name clashes, identifiers starting with <Literal>Hs</Literal> and
897 macros starting with <Literal>HS&lowbar;</Literal> are reserved for the FFI.
898 </Para>
899 </ListItem>
900 <ListItem>
901
902 <Para>
903 <Emphasis>GHC only:</Emphasis> The GHC specific types <Literal>ByteArray</Literal> and
904 <Literal>MutableByteArray</Literal> both map to <Literal>char*</Literal>.
905 </Para>
906 </ListItem>
907
908 </OrderedList>
909
910 </Para>
911
912 </Sect2>
913
914 <Sect2 id="sec-prim-remarks">
915 <Title>Some <Literal>foreign import</Literal> wrinkles
916 </Title>
917
918 <Para>
919
920 <ItemizedList>
921 <ListItem>
922
923 <Para>
924 By default, a <Literal>foreign import</Literal> function is <Emphasis>safe</Emphasis>. A safe
925 external function may cause a Haskell garbage collection as a result
926 of being called. This will typically happen when the imported
927 function end up calling Haskell functions that reside in the same
928 'Haskell world' (i.e., shares the same storage manager heap) -- see
929 Section <XRef LinkEnd="sec-entry"> for
930 details of how the FFI let's you call Haskell functions from the outside.
931
932 If the programmer can guarantee that the imported function won't
933 call back into Haskell, the <Literal>foreign import</Literal> can be marked as
934 'unsafe' (see Section <XRef LinkEnd="sec-primitive"> for details of
935 how to do this.)
936
937 Unsafe calls are cheaper than safe ones, so distinguishing the two
938 classes of external calls may be worth your while if you're extra
939 conscious about performance.
940
941 </Para>
942 </ListItem>
943 <ListItem>
944
945 <Para>
946 A <Literal>foreign import</Literal>ed function should clearly not need to know that
947 it is being called from Haskell. One consequence of this is that the
948 lifetimes of the arguments that are passed from Haskell <Emphasis>must</Emphasis>
949 equal that of a normal C call. For instance, for the following decl,
950
951
952 <ProgramListing>
953 foreign import "mumble" mumble :: ForeignObj -&#62; IO ()
954
955 f :: Addr -&#62; IO ()
956 f ptr = do
957   fo &#60;- makeForeignObj ptr myFinalizer
958   mumble fo
959 </ProgramListing>
960
961
962 The <Literal>ForeignObj</Literal> must live across the call to <Function>mumble</Function> even if
963 it is not subsequently used/reachable. Why the insistence on this?
964 Consider what happens if <Function>mumble</Function> calls a function which calls back
965 into the Haskell world to execute a function, behind our back as it
966 were. This evaluation may possibly cause a garbage collection, with
967 the result that <Literal>fo</Literal> may end up being finalised.
968
969 By guaranteeing that <Literal>fo</Literal> will be considered live across the call
970 to <Function>mumble</Function>, the unfortunate situation where <Literal>fo</Literal> is finalised
971 (and hence the reference passed to <Function>mumble</Function> is suddenly no longer
972 valid) is avoided.
973
974
975 </Para>
976 </ListItem>
977
978 </ItemizedList>
979
980 </Para>
981
982 </Sect2>
983
984 </Sect1>
985
986 <Sect1 id="sec-prim-dynamic">
987 <Title>Invoking external functions via a pointer
988 </Title>
989
990 <Para>
991 A <Literal>foreign import</Literal> declaration imports an external 
992 function into Haskell. (The name of the external function
993 is statically known, but the loading/linking of it may very well
994 be delayed until run-time.) A <Literal>foreign import</Literal> declaration is then
995 (approximately) just a type cast of an external function with a
996 <Emphasis>statically known name</Emphasis>. 
997 </Para>
998
999 <Para>
1000 An extension of <Literal>foreign import</Literal> is the support for <Emphasis>dynamic</Emphasis> type
1001 casts of external names/addresses:
1002 </Para>
1003
1004 <Para>
1005
1006 <ProgramListing>
1007 topdecl 
1008    : ...
1009    ..
1010    | 'foreign' 'import' [callconv] 'dynamic' ['unsafe']
1011             varid :: Addr -&#62; (prim_args -&#62; IO prim_result)
1012 </ProgramListing>
1013
1014 </Para>
1015
1016 <Para>
1017 i.e., identical to a <Literal>foreign import</Literal> declaration, but for the
1018 specification of <Literal>dynamic</Literal> instead of the name of an external
1019 function. The presence of <Literal>dynamic</Literal> indicates that when an
1020 application of <Literal>varid</Literal> is evaluated, the function pointed to by its
1021 first argument will be invoked, passing it the rest of <Literal>varid</Literal>'s
1022 arguments.
1023 </Para>
1024
1025 <Para>
1026 What are the uses of this? Native invocation of COM methods,
1027 <Footnote>
1028 <Para>
1029 Or the interfacing to any other software component technologies.
1030 </Para>
1031 </Footnote>
1032 Haskell libraries that want to be dressed up as C libs (and hence may have
1033 to support C callbacks), Haskell code that need to dynamically load
1034 and execute code.
1035 </Para>
1036
1037 </Sect1>
1038
1039 <Sect1 id="sec-entry">
1040 <Title>Exposing Haskell functions
1041 </Title>
1042
1043 <Para>
1044 So far we've provided the Haskell programmer with ways of importing
1045 external functions into the Haskell world. The other half of the FFI
1046 coin is how to expose Haskell functionality to the outside world. So,
1047 dual to the <Literal>foreign import</Literal> declaration is <Literal>foreign export</Literal>:
1048 </Para>
1049
1050 <Para>
1051
1052 <ProgramListing>
1053 topdecl 
1054   : ...
1055   ..
1056   | 'foreign' 'export' callconv [ext_name] varid :: prim_type
1057 </ProgramListing>
1058
1059 </Para>
1060
1061 <Para>
1062 A <Literal>foreign export</Literal> declaration tells the compiler to expose a
1063 locally defined Haskell function to the outside world, i.e., wrap
1064 it up behind a calling interface that's useable from C. It is only
1065 permitted at the toplevel, where you have to specify the type at
1066 which you want to export the function, along with the calling
1067 convention to use. For instance, the following export declaration:
1068 </Para>
1069
1070 <Para>
1071
1072 <ProgramListing>
1073 foreign export ccall "foo" bar :: Int -&#62; Addr -&#62; IO Double
1074 </ProgramListing>
1075
1076 </Para>
1077
1078 <Para>
1079 will cause a Haskell system to generate the following C callable
1080 function:
1081 </Para>
1082
1083 <Para>
1084
1085 <ProgramListing>
1086 HsDouble foo(HsInt arg1, HsAddr arg2);
1087 </ProgramListing>
1088
1089 </Para>
1090
1091 <Para>
1092 When invoked, it will call the Haskell function <Function>bar</Function>, passing
1093 it the two arguments that was passed to <Function>foo()</Function>. 
1094 </Para>
1095
1096 <Para>
1097
1098 <ItemizedList>
1099 <ListItem>
1100
1101 <Para>
1102 The range of types that can be passed as arguments and results
1103 is restricted, since <Literal>varid</Literal> has got a <Literal>prim&lowbar;type</Literal>.
1104 </Para>
1105 </ListItem>
1106 <ListItem>
1107
1108 <Para>
1109 It is not possible to directly export operator symbols.
1110 </Para>
1111 </ListItem>
1112 <ListItem>
1113
1114 <Para>
1115 The type checker will verify that the type given for the
1116 <Literal>foreign export</Literal> declaration is compatible with the type given to
1117 function definition itself.  The type in the <Literal>foreign export</Literal> may
1118 be less general than that of the function itself.  For example,
1119 this is legal:
1120
1121
1122 <ProgramListing>
1123    f :: Num a =&#62; a -&#62; a
1124    foreign export ccall "fInt"   f :: Int -&#62; Int
1125    foreign export ccall "fFloat" f :: Float -&#62; Float
1126 </ProgramListing>
1127
1128
1129 These declarations export two C-callable procedures <Literal>fInt</Literal> and
1130 <Literal>fFloat</Literal>, both of which are implemented by the (overloaded)
1131 Haskell function <Function>f</Function>.
1132
1133 </Para>
1134 </ListItem>
1135 <ListItem>
1136
1137 <Para>
1138 The <Literal>foreign export</Literal>ed IO action must catch all exceptions, as
1139 the FFI does not address how to signal Haskell exceptions to the
1140 outside world.
1141 </Para>
1142 </ListItem>
1143
1144 </ItemizedList>
1145
1146 </Para>
1147
1148 <Sect2 id="sec-callback">
1149 <Title>Exposing Haskell function values
1150 </Title>
1151
1152 <Para>
1153 The <Literal>foreign export</Literal> declaration gives the C programmer access to
1154 statically defined Haskell functions. It does not allow you to
1155 conveniently expose dynamically-created Haskell function values as C
1156 function pointers though. To permit this, the FFI supports
1157 <Emphasis>dynamic</Emphasis> <Literal>foreign export</Literal>s:
1158 </Para>
1159
1160 <Para>
1161
1162 <ProgramListing>
1163 topdecl 
1164   : ...
1165   ..
1166   | 'foreign' 'export' [callconv] 'dynamic' varid :: prim_type -&#62; IO Addr
1167 </ProgramListing>
1168
1169 </Para>
1170
1171 <Para>
1172 A <Literal>foreign export dynamic</Literal> declaration declares a C function
1173 pointer <Emphasis>generator</Emphasis>. Given a Haskell function value of some restricted
1174 type, the generator wraps it up behind an externally callable interface,
1175 returning an <Literal>Addr</Literal> to an externally callable (C) function pointer.
1176 </Para>
1177
1178 <Para>
1179 When that function pointer is eventually called, the corresponding
1180 Haskell function value is applied to the function pointer's arguments
1181 and evaluated, returning the result (if any) back to the caller.
1182 </Para>
1183
1184 <Para>
1185 The mapping between the argument to a <Literal>foreign export dynamic</Literal>
1186 declaration and its corresponding C function pointer type, is as
1187 follows:
1188 </Para>
1189
1190 <Para>
1191
1192 <ProgramListing>
1193 typedef cType[[Res]] (*Varid_FunPtr)
1194         (cType[[Ty_1]] ,.., cType[[Ty_n]]);
1195 </ProgramListing>
1196
1197 </Para>
1198
1199 <Para>
1200 where <Literal>cType[[]]</Literal> is the Haskell to C type mapping presented
1201 in Section <XRef LinkEnd="sec-mapping">.
1202 </Para>
1203
1204 <Para>
1205 To make it all a bit more concrete, here's an example:
1206 </Para>
1207
1208 <Para>
1209
1210 <ProgramListing>
1211 foreign export dynamic mkCallback :: (Int -&#62; IO Int) -&#62; IO Addr
1212
1213 foreign import registerCallback :: Addr -&#62; IO ()
1214
1215 exportCallback :: (Int -&#62; IO Int) -&#62; IO ()
1216 exportCallback f = do
1217   fx &#60;- mkCallback f
1218   registerCallback fx
1219 </ProgramListing>
1220
1221 </Para>
1222
1223 <Para>
1224 The <Literal>exportCallback</Literal> lets you register a Haskell function value as
1225 a callback function to some external library. The C type of the
1226 callback that the external library expects in <Literal>registerCallback()</Literal>,
1227 is:
1228 <Footnote>
1229 <Para>
1230 An FFI implementation is encouraged to generate the C typedef corresponding
1231 to a <Literal>foreign export dynamic</Literal> declaration, but isn't required
1232 to do so.
1233 </Para>
1234 </Footnote>
1235
1236 </Para>
1237
1238 <Para>
1239
1240 <ProgramListing>
1241 typedef HsInt (*mkCallback_FunPtr) (HsInt arg1);
1242 </ProgramListing>
1243
1244 </Para>
1245
1246 <Para>
1247 Creating the view of a Haskell closure as a C function pointer entails
1248 registering the Haskell closure as a 'root' with the underlying
1249 Haskell storage system, so that it won't be garbage collected. The FFI
1250 implementation takes care of this, but when the outside world is
1251 through with using a C function pointer generated by a <Literal>foreign
1252 export dynamic</Literal> declaration, it needs to be explicitly freed. This is
1253 done by calling:
1254 </Para>
1255
1256 <Para>
1257
1258 <ProgramListing>
1259 void freeHaskellFunctionPtr(void *ptr);
1260 </ProgramListing>
1261
1262 </Para>
1263
1264 <Para>
1265 In the event you need to free these function pointers from within
1266 Haskell, a standard 'foreign import'ed binding of the above C entry
1267 point is also provided,
1268 </Para>
1269
1270 <Para>
1271
1272 <ProgramListing>
1273 Foreign.freeHaskellFunctionPtr :: Addr -&#62; IO ()
1274 </ProgramListing>
1275
1276 </Para>
1277
1278 </Sect2>
1279
1280 <Sect2 id="sec-foreign-label">
1281 <Title>Code addresses
1282 </Title>
1283
1284 <Para>
1285 The <Literal>foreign import</Literal> declaration allows us to invoke an external
1286 function by name from within the comforts of the Haskell world, while
1287 <Literal>foreign import dynamic</Literal> lets us invoke an external function by
1288 address. However, there's no way of getting at the code address of
1289 some particular external label though, which is at times useful,
1290 e.g. for the construction of method tables for, say, Haskell COM
1291 components. To support this, the FFI has got <Literal>foreign label</Literal>s:
1292 </Para>
1293
1294 <Para>
1295
1296 <ProgramListing>
1297 foreign label "freeAtLast" addrOf_freeAtLast :: Addr
1298 </ProgramListing>
1299
1300 </Para>
1301
1302 <Para>
1303 The meaning of this declaration is that <Literal>addrOf&lowbar;freeAtLast</Literal> will now
1304 contain the address of the label <Literal>freeAtLast</Literal>.
1305 </Para>
1306
1307 </Sect2>
1308
1309 </Sect1>
1310
1311 <Sect1 id="sec-changelog">
1312 <Title>Change history
1313 </Title>
1314
1315 <Para>
1316
1317 <ItemizedList>
1318 <ListItem>
1319
1320 <Para>
1321 0.95 --&gt; 0.96:
1322
1323 <ItemizedList>
1324 <ListItem>
1325
1326 <Para>
1327 changed the C representation of <Literal>Haskell&lowbar;ForeignObj</Literal> from
1328 <Literal>(long*)</Literal> to <Literal>(void*)</Literal> -- ANSI C guarantees that <Literal>(void*)</Literal>
1329 is the widest possible data pointer.
1330 </Para>
1331 </ListItem>
1332 <ListItem>
1333
1334 <Para>
1335 Updated defnition of <Literal>varid</Literal> in Section
1336 <XRef LinkEnd="sec-prim-name"> to reflect Haskell98's.
1337 </Para>
1338 </ListItem>
1339 <ListItem>
1340
1341 <Para>
1342 Replaced confusing uses of <Literal>stdcall</Literal> with <Literal>ccall</Literal>.
1343 </Para>
1344 </ListItem>
1345
1346 </ItemizedList>
1347
1348 </Para>
1349 </ListItem>
1350 <ListItem>
1351
1352 <Para>
1353 0.96 --&gt; 0.97:
1354
1355 <ItemizedList>
1356 <ListItem>
1357
1358 <Para>
1359 Simplified the calling convention section, support for Pascal (and
1360 fastcall) calling conventions dropped. 
1361 </Para>
1362 </ListItem>
1363 <ListItem>
1364
1365 <Para>
1366 Clarified that the arguments to a safe <Literal>foreign import</Literal> must have
1367 lifetimes that equal that of a C function application.
1368 </Para>
1369 </ListItem>
1370 <ListItem>
1371
1372 <Para>
1373 Outlawed the use of the (GHC specific) types <Literal>ByteArray</Literal>
1374 and <Literal>MutableByteArray</Literal> in safe <Literal>foreign import</Literal>s.
1375 </Para>
1376 </ListItem>
1377 <ListItem>
1378
1379 <Para>
1380 Added a note that support for the use of unboxed types in
1381 <Literal>foreign import</Literal> may be withdrawn/deprecated sometime in the future.
1382 </Para>
1383 </ListItem>
1384 <ListItem>
1385
1386 <Para>
1387 Simplified section which sketches a possible implementation.
1388 </Para>
1389 </ListItem>
1390 <ListItem>
1391
1392 <Para>
1393 Use <Literal>Hs</Literal> as prefix for the typedefs for the primitive Haskell
1394 FFI types rather than the longer <Literal>Haskell&lowbar;</Literal>.
1395 </Para>
1396 </ListItem>
1397
1398 </ItemizedList>
1399
1400 </Para>
1401 </ListItem>
1402 <ListItem>
1403
1404 <Para>
1405 0.97 --&gt; 0.98:
1406
1407 <ItemizedList>
1408 <ListItem>
1409
1410 <Para>
1411 Leave out implementation section; of limited interest.
1412 </Para>
1413 </ListItem>
1414 <ListItem>
1415
1416 <Para>
1417 Outlined the criteria used to decide on what calling
1418 conventions to support.
1419 </Para>
1420 </ListItem>
1421 <ListItem>
1422
1423 <Para>
1424 Include <Literal>newtype</Literal>s that wrap primitive types in the list
1425 of types that can be both passed to and returned from external
1426 functions.
1427 </Para>
1428 </ListItem>
1429
1430 </ItemizedList>
1431
1432 </Para>
1433 </ListItem>
1434 <ListItem>
1435
1436 <Para>
1437 0.98 --&gt; 0.99:
1438
1439 <ItemizedList>
1440 <ListItem>
1441
1442 <Para>
1443 Updated the section on type mapping to integrate some comments
1444 from people on &lt;ffi@haskell.org&gt; (a fair chunk of the text
1445 in that section was contributed by Sven Panne.)
1446 </Para>
1447 </ListItem>
1448 <ListItem>
1449
1450 <Para>
1451 <Function>freeHaskellFunctionPtr</Function> should belong to module <Literal>Foreign</Literal>, not <Literal>IOExts</Literal>.
1452 </Para>
1453 </ListItem>
1454
1455 </ItemizedList>
1456
1457
1458 </Para>
1459 </ListItem>
1460 <ListItem>
1461
1462 <Para>
1463 0.99 --&gt; 0.99.1:
1464
1465 <ItemizedList>
1466 <ListItem>
1467
1468 <Para>
1469 <Literal>Bool</Literal> is now an FFI-supported type (i.e., added it to
1470 <Literal>ext&lowbar;ty</Literal>.)
1471 </Para>
1472 </ListItem>
1473
1474 </ItemizedList>
1475
1476
1477 </Para>
1478 </ListItem>
1479
1480 </ItemizedList>
1481
1482 </Para>
1483
1484 </Sect1>