Newer
Older
<Sect1 id="sec-intro">
<Title>Introduction
</Title>
<Para>
The motivation behind this foreign function interface (FFI) specification is
to make it possible to describe in Haskell <Emphasis>source code</Emphasis>
the interface to foreign functionality in a Haskell system independent
manner. It builds on experiences made with the previous foreign function
interfaces provided by GHC and Hugs. However, the FFI specified in this
document is not in the market of trying to completely bridge the gap between
the actual type of an external function, and what is a
<Emphasis>convenient</Emphasis> type for that function to the Haskell
programmer. That is the domain of tools like HaskellDirect or Green Card, both
of which are capable of generating Haskell code that uses this FFI.
Generally, the FFI consists of three parts:
<OrderedList>
<ListItem>
<Para>
extensions to the base language Haskell 98 (most notably <Literal>foreign
import</Literal> and <Literal>foreign export</Literal> declarations), which
are specified in the present document,
</Para>
</ListItem>
<ListItem>
<Para>
a low-level marshalling library, which is part of the
<Emphasis>Language</Emphasis> part of the <Emphasis>Haskell Extension
Library</Emphasis> (see <xref linkend="sec-Storable">), and a
</Para>
</ListItem>
<ListItem>
<Para>
a high-level marshalling library, which is still under development.
</Para>
</ListItem>
</OrderedList>
Before diving into the details of the language extension coming with the FFI,
let us briefly outline the two other components of the interface.
</Para>
<Para>
The low-level marshalling library consists of a portion that is independent of
the targeted foreign language and dedicated support for Haskell bindings to C
libraries (special support for other languages may be added in the future).
The language independent part is given by the module
<literal>Foreign</literal> module (see <xref linkend="sec-Foreign">). It
provides support for handling references to foreign structures, for passing
references to Haskell structures out to foreign routines, and for storing
primitive data types in raw memory blocks in a portable manner. The support
for C libraries essentially provides Haskell representations for all basic
types of C (see <xref linkend="sec-CTypes"> and <xref
linkend="sec-CTypesISO">).
</Para>
<Para>
The high-level library, of which the interface definition is not yet
finalised, provides routines for marshalling complex Haskell structures as
well as handling out and in-out parameters in a convenient, yet protable way.
In the following, we will discuss the language extensions of the FFI (ie, the
first point above). They can be split up into two complementary halves; one
half that provides Haskell constructs for importing foreign functionality into
Haskell, the other which lets you expose Haskell functions to the outside
world. We start with the former, how to import external functionality into
Haskell.
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
</Para>
</Sect1>
<Sect1 id="sec-primitive">
<Title>Calling foreign functions
</Title>
<Para>
To bind a Haskell variable name and type to an external function, we
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:
</Para>
<Para>
<ProgramListing>
topdecl
: ...
..
| 'foreign' 'import' [callconv] [ext_fun] ['unsafe'] varid '::' prim_type
</ProgramListing>
</Para>
<Para>
A <Literal>foreign import</Literal> declaration is only allowed as a toplevel
declaration. It consists of two parts, one giving the Haskell type
(<Literal>prim_type</Literal>), Haskell name (<Literal>varid</Literal>) and a flag indicating whether the
primitive is unsafe, the other giving details of the name of the
external function (<Literal>ext_fun</Literal>) and its calling interface
(<Literal>callconv</Literal>.)
</Para>
<Para>
Giving a Haskell name and type to an external entry point is clearly
an unsafe thing to do, as the external name will in most cases be
untyped. The onus is on the programmer using <Literal>foreign import</Literal> to
ensure that the Haskell type given correctly maps on to the
type of the external function. Section
<XRef LinkEnd="sec-mapping"> specifies the mapping from
Haskell types to external types.
</Para>
<Sect2 id="sec-prim-name">
<Title>Giving the external function a Haskell name
</Title>
<Para>
The external function has to be given a Haskell name. The name
must be a Haskell <Literal>varid</Literal>, so the language rules regarding
variable names must be followed, i.e., it must start with a
lower case letter followed by a sequence of alphanumeric
(`in the Unicode sense') characters or '.
<Footnote>
<Para>
Notice that with Haskell 98, underscore ('_') is included in
the character class <Literal>small</Literal>.
</Para>
</Footnote>
</Para>
<Para>
<ProgramListing>
varid : small ( small | large | udigit | ' )*
</ProgramListing>
</Para>
</Sect2>
<Sect2 id="sec-prim-ext-name">
<Title>Naming the external function
</Title>
<Para>
The name of the external function consists of two parts,
one specifying its location, the other its name:
</Para>
<Para>
<ProgramListing>
ext_fun : ext_loc ext_name
| ext_name
ext_name : string
ext_loc : string
</ProgramListing>
</Para>
<Para>
For example,
</Para>
<Para>
<ProgramListing>
foreign import stdcall "Advapi32" "RegCloseKey" regCloseKey :: Addr -> IO ()
</ProgramListing>
</Para>
<Para>
states that the external function named <Function>RegCloseKey</Function> at location
<Function>Advapi32</Function> should be bound to the Haskell name <Function>regCloseKey</Function>.
For a Win32 Haskell implementation that supports the loading of DLLs
on-the-fly, this declaration will most likely cause the run-time
system to load the <Filename>Advapi32.dll</Filename> DLL before looking up the
function <Function>RegCloseKey()</Function> therein to get at the function pointer
to use when invoking <Function>regCloseKey</Function>.
</Para>
<Para>
Compiled implementations may do something completely different, i.e.,
mangle "RegCloseKey" to convert it into an archive/import library
symbol, that's assumed to be in scope when linking. The details of
which are platform (and compiler command-line) dependent.
</Para>
<Para>
If the location part is left out, the name of the external function
specifies a symbol that is assumed to be in scope when linking.
</Para>
<Para>
The location part can either contain an absolute `address' (i.e.,
path) of the archive/DLL, or just its name, leaving it up to the
underlying system (system meaning both RTS/compiler and OS) to resolve
the name to its real location.
</Para>
<Para>
An implementation is <Emphasis>expected</Emphasis> to be able to intelligently
transform the <Literal>ext_loc</Literal> location to fit platform-specific
practices for naming dynamic libraries. For instance, given the
declaration
</Para>
<Para>
<ProgramListing>
foreign import "Foo" "foo" foo :: Int -> Int -> IO ()
</ProgramListing>
</Para>
<Para>
an implementation should map <Filename>Foo</Filename> to <Filename>"Foo.dll"</Filename> on a Win32
platform, and <Filename>libFoo.so</Filename> on ELF platforms. If the lookup of the
dynamic library with this transformed location name should fail, the
implementation should then attempt to use the original name before
eventually giving up. As part of their documentation, implementations
of <Literal>foreign import</Literal> should specify the exact details of how
<Literal>ext_loc</Literal>s are transformed and resolved, including the list of
directories searched (and the order in which they are.)
</Para>
<Para>
In the case the Haskell name of the imported function is identical to
the external name, the <Literal>ext_fun</Literal> can be omitted. i.e.,
</Para>
<Para>
<ProgramListing>
foreign import sin :: Double -> IO Double
</ProgramListing>
</Para>
<Para>
is identical to
</Para>
<Para>
<ProgramListing>
foreign import "sin" sin :: Double -> IO Double
</ProgramListing>
</Para>
</Sect2>
<Sect2 id="sec-cconv">
<Title>Calling conventions
</Title>
<Para>
The number of calling conventions supported is fixed:
</Para>
<Para>
<ProgramListing>
callconv : ccall | stdcall
</ProgramListing>
</Para>
<Para>
<VariableList>
<VarListEntry>
<Term><Literal>ccall</Literal></Term>
<ListItem>
<Para>
The 'default' calling convention on a platform, i.e., the one
used to do (C) function calls.
</Para>
<Para>
In the case of x86 platforms, the caller pushes function arguments
from right to left on the C stack before calling. The caller is
responsible for popping the arguments off of the C stack on return.
</Para>
</ListItem>
</VarListEntry>
<VarListEntry>
<Term><Literal>stdcall</Literal></Term>
<ListItem>
<Para>
A Win32 specific calling convention. The same as <Literal>ccall</Literal>, except
that the callee cleans up the C stack before returning.
<Footnote>
<Para>
The <Literal>stdcall</Literal> is a Microsoft Win32 specific wrinkle; it used
throughout the Win32 API, for instance. On platforms where
<Literal>stdcall</Literal> isn't meaningful, it should be treated as being equal
to <Literal>ccall</Literal>.
</Para>
</Footnote>
</Para>
</ListItem>
</VarListEntry>
</VariableList>
</Para>
<Para>
<Emphasis remap="bf">Some remarks:</Emphasis>
<ItemizedList>
<ListItem>
<Para>
Interoperating well with external code is the name of the game here,
so the guiding principle when deciding on what calling conventions
to include in <Literal>callconv</Literal> is that there's a demonstrated need for
a particular calling convention. Should it emerge that the inclusion
of other calling conventions will generally improve the quality of
this Haskell FFI, they will be considered for future inclusion in
<Literal>callconv</Literal>.
</Para>
</ListItem>
<ListItem>
<Para>
Supporting <Literal>stdcall</Literal> (and perhaps other platform-specific calling
conventions) raises the issue of whether a Haskell FFI should allow
the user to write platform-specific Haskell code. The calling
convention is clearly an integral part of an external function's
interface, so if the one used differs from the standard one specified
by the platform's ABI <Emphasis>and</Emphasis> that convention is used by a
non-trivial amount of external functions, the view of the FFI authors
is that a Haskell FFI should support it.
</Para>
</ListItem>
<ListItem>
<Para>
For <Literal>foreign import</Literal> (and other <Literal>foreign</Literal> declarations),
supplying the calling convention is optional. If it isn't supplied,
it is treated as if <Literal>ccall</Literal> was specified. Users are encouraged
to leave out the specification of the calling convention, if possible.
</Para>
</ListItem>
</ItemizedList>
</Para>
</Sect2>
<Sect2 id="sec-prim-types">
<Title>External function types
</Title>
<Para>
The range of types that can be passed as arguments to an external
function is restricted (as are the range of results coming back):
</Para>
<Para>
<ProgramListing>
prim_type : IO prim_result
| prim_result
| prim_arg '->' prim_type
</ProgramListing>
</Para>
<Para>
<ItemizedList>
<ListItem>
<Para>
If you associate a non-IO type with an external function, you
have the same 'proof obligations' as when you make use of
<Function>IOExts.unsafePerformIO</Function> in your Haskell programs.
</Para>
</ListItem>
<ListItem>
<Para>
The external function is strict in all its arguments.
</Para>
</ListItem>
<ListItem>
<Para>
<Emphasis>GHC only:</Emphasis> The GHC FFI implementation provides one extension
to <Literal>prim_type</Literal>:
<ProgramListing>
prim_type : ...
| unsafe_arr_ty '->' prim_type
unsafe_arr_ty : ByteArray a
| MutableByteArray i s a
</ProgramListing>
GHC permits the passing of its byte array primitive types
to external functions. There's some restrictions on when
they can be used; see Section <XRef LinkEnd="sec-arguments">
for more details.
</Para>
</ListItem>
</ItemizedList>
</Para>
<Para>
Section <XRef LinkEnd="sec-results"> defines
<Literal>prim_result</Literal>; Section <XRef LinkEnd="sec-arguments">
defines <Literal>prim_arg</Literal>.
</Para>
<Sect3 id="sec-arguments">
<Title>Argument types
</Title>
<Para>
The external function expects zero or more arguments. The set of legal
argument types is restricted to the following set:
</Para>
<Para>
<ProgramListing>
prim_arg : ext_ty | new_ty | ForeignObj
new_ty : a Haskell newtype of a prim_arg.
ext_ty : int_ty | word_ty | float_ty
| Addr | Char | StablePtr a
| Bool
int_ty : Int | Int8 | Int16 | Int32 | Int64
word_ty : Word8 | Word16 | Word32 | Word64
float_ty : Float | Double
</ProgramListing>
</Para>
<Para>
<ItemizedList>
<ListItem>
<Para>
<Literal>ext_ty</Literal> represent the set of basic types supported by
C-like languages, although the numeric types are explicitly sized.
The <Emphasis>stable pointer</Emphasis> <Literal>StablePtr</Literal> type looks out of place in
this list of C-like types, but it has a well-defined and simple
C mapping, see Section <XRef LinkEnd="sec-mapping">
for details.
</Para>
</ListItem>
<ListItem>
<Para>
<Literal>prim_arg</Literal> represent the set of permissible argument types. In
addition to <Literal>ext_ty</Literal>, <Literal>ForeignObj</Literal> is also included.
The <Literal>ForeignObj</Literal> type represent values that are pointers to some
external entity/object. It differs from the <Literal>Addr</Literal> type in that
<Literal>ForeignObj</Literal>s are <Emphasis>finalized</Emphasis>, i.e., once the garbage collector
determines that a <Literal>ForeignObj</Literal> is unreachable, it will invoke a
finalising procedure attached to the <Literal>ForeignObj</Literal> to notify the
outside world that we're through with using it.
</Para>
</ListItem>
<ListItem>
<Para>
Haskell <Literal>newtype</Literal>s that wrap up a <Literal>prim_arg</Literal> type can also
be passed to external functions.
</Para>
</ListItem>
<ListItem>
<Para>
Haskell type synonyms for any of the above can also be used
in <Literal>foreign import</Literal> declarations. Qualified names likewise,
i.e. <Literal>Word.Word32</Literal> is legal.
</Para>
</ListItem>
<ListItem>
<Para>
<Literal>foreign import</Literal> does not support the binding to external
constants/variables. A <Literal>foreign import</Literal> declaration that takes no
arguments represent a binding to a function with no arguments.
</Para>
</ListItem>
<ListItem>
<Para>
<Emphasis>GHC only:</Emphasis> GHC's implementation of the FFI provides
two extensions:
<ItemizedList>
<ListItem>
<Para>
Support for passing heap allocated byte arrays to an external
function
<ProgramListing>
prim_type : ...
| prim_arg '->' prim_type
| unsafe_arr_ty '->' prim_type
unsafe_arr_ty : ByteArray a
| MutableByteArray i s a
</ProgramListing>
GHC's <Literal>ByteArray</Literal> and <Literal>MutableByteArray</Literal> primitive types are
(im)mutable chunks of memory allocated on the Haskell heap, and
pointers to these can be passed to <Literal>foreign import</Literal>ed external
functions provided they are marked as <Literal>unsafe</Literal>. Since it is
inherently unsafe to hand out references to objects in the Haskell
heap if the external call may cause a garbage collection to happen,
you have to annotate the <Literal>foreign import</Literal> declaration with
the attribute <Literal>unsafe</Literal>. By doing so, the user explicitly states
that the external function won't provoke a garbage collection,
so passing out heap references to the external function is allright.
</Para>
</ListItem>
<ListItem>
<Para>
Another GHC extension is the support for unboxed types:
<ProgramListing>
prim_arg : ... | unboxed_h_ty
ext_ty : .... | unboxed_ext_ty
unboxed_ext_ty : Int# | Word# | Char#
| Float# | Double# | Addr#
| StablePtr# a
unboxed_h_ty : MutableByteArray# | ForeignObj#
| ByteArray#
</ProgramListing>
Clearly, if you want to be portable across Haskell systems, using
system-specific extensions such as this is not advisable; avoid
using them if you can. (Support for using unboxed types might
be withdrawn sometime in the future.)
</Para>
</ListItem>
</ItemizedList>
</Para>
</ListItem>
</ItemizedList>
</Para>
</Sect3>
<Sect3 id="sec-results">
<Title>Result type
</Title>
<Para>
An external function is permitted to return the following
range of types:
</Para>
<Para>
<ProgramListing>
prim_result : ext_ty | new_ext_ty | ()
new_ext_ty : a Haskell newtype of an ext_ty.
</ProgramListing>
</Para>
<Para>
where <Literal>()</Literal> represents <Literal>void</Literal> / no result.
</Para>
<Para>
<ItemizedList>
<ListItem>
<Para>
External functions cannot raise exceptions (IO exceptions or non-IO ones.)
It is the responsibility of the <Literal>foreign import</Literal> user to layer
any error handling on top of an external function.
</Para>
</ListItem>
<ListItem>
<Para>
Only external types (<Literal>ext_ty</Literal>) can be passed back, i.e., returning
<Literal>ForeignObj</Literal>s is not supported/allowed.
</Para>
</ListItem>
<ListItem>
<Para>
Haskell newtypes that wrap up <Literal>ext_ty</Literal> are also permitted.
</Para>
</ListItem>
</ItemizedList>
</Para>
</Sect3>
</Sect2>
<Sect2 id="sec-mapping">
<Title>Type mapping
</Title>
<Para>
For the FFI to be of any practical use, the properties and sizes of
the various types that can be communicated between the Haskell world
and the outside, needs to be precisely defined. We do this by
presenting a mapping to C, as it is commonly used and most other
languages define a mapping to it. Table
<XRef LinkEnd="sec-mapping-table">
defines the mapping between Haskell and C types.
</Para>
<Para>
<Table id="sec-mapping-table">
<Title>Mapping of Haskell types to C types</Title>
<ColSpec Align="Left" Colsep="0">
<ColSpec Align="Left" Colsep="0">
<ColSpec Align="Left" Colsep="0">
<ColSpec Align="Left" Colsep="0">
<TBody>
<Row RowSep="1">
<Entry>Haskell type </Entry>
<Entry> C type </Entry>
<Entry> requirement </Entry>
<Entry> range (9) </Entry>
<Entry> </Entry>
<Entry> </Entry>
</Row>
<Row>
<Entry>
<Literal>Char</Literal> </Entry>
<Entry> <Literal>HsChar</Literal> </Entry>
<Entry> unspec. integral type </Entry>
<Entry> <Literal>HS_CHAR_MIN</Literal> .. <Literal>HS_CHAR_MAX</Literal></Entry>
</Row>
<Row>
<Entry>
<Literal>Int</Literal> </Entry>
<Entry> <Literal>HsInt</Literal> </Entry>
<Entry> signed integral of unspec. size(4) </Entry>
<Entry> <Literal>HS_INT_MIN</Literal> ..
<Literal>HS_INT_MAX</Literal></Entry>
</Row>
<Row>
<Entry>
<Literal>Int8</Literal> (2) </Entry>
<Entry> <Literal>HsInt8</Literal> </Entry>
<Entry> 8 bit signed integral </Entry>
<Entry> <Literal>HS_INT8_MIN</Literal>
..
<Literal>HS_INT8_MAX</Literal></Entry>
</Row>
<Row>
<Entry>
<Literal>Int16</Literal> (2) </Entry>
<Entry> <Literal>HsInt16</Literal> </Entry>
<Entry> 16 bit signed integral </Entry>
<Entry> <Literal>HS_INT16_MIN</Literal>
.. <Literal>HS_INT16_MAX</Literal></Entry>
</Row>
<Row>
<Entry>
<Literal>Int32</Literal> (2) </Entry>
<Entry> <Literal>HsInt32</Literal> </Entry>
<Entry> 32 bit signed integral </Entry>
<Entry> <Literal>HS_INT32_MIN</Literal> ..
<Literal>HS_INT32_MAX</Literal></Entry>
</Row>
<Row>
<Entry>
<Literal>Int64</Literal> (2,3) </Entry>
<Entry> <Literal>HsInt64</Literal> </Entry>
<Entry> 64 bit signed integral (3) </Entry>
<Entry> <Literal>HS_INT64_MIN</Literal> ..
<Literal>HS_INT64_MAX</Literal></Entry>
</Row>
<Row>
<Entry>
<Literal>Word8</Literal> (2) </Entry>
<Entry> <Literal>HsWord8</Literal> </Entry>
<Entry> 8 bit unsigned integral </Entry>
<Literal>HS_WORD8_MAX</Literal></Entry>
</Row>
<Row>
<Entry>
<Literal>Word16</Literal> (2) </Entry>
<Entry> <Literal>HsWord16</Literal> </Entry>
<Entry> 16 bit unsigned integral </Entry>
<Literal>HS_WORD16_MAX</Literal></Entry>
</Row>
<Row>
<Entry>
<Literal>Word32</Literal> (2) </Entry>
<Entry> <Literal>HsWord32</Literal> </Entry>
<Entry> 32 bit unsigned integral </Entry>
<Entry> <Literal>0</Literal> ..
<Literal>HS_WORD32_MAX</Literal></Entry>
</Row>
<Row>
<Entry>
<Literal>Word64</Literal> (2,3) </Entry>
<Entry> <Literal>HsWord64</Literal> </Entry>
<Entry> 64 bit unsigned integral (3) </Entry>
<Entry> <Literal>0</Literal> ..
<Literal>HS_WORD64_MAX</Literal></Entry>
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
</Row>
<Row>
<Entry>
<Literal>Float</Literal> </Entry>
<Entry> <Literal>HsFloat</Literal> </Entry>
<Entry> floating point of unspec. size (5) </Entry>
<Entry> (10) </Entry>
</Row>
<Row>
<Entry>
<Literal>Double</Literal> </Entry>
<Entry> <Literal>HsDouble</Literal> </Entry>
<Entry> floating point of unspec. size (5) </Entry>
<Entry> (10) </Entry>
</Row>
<Row>
<Entry>
<Literal>Bool</Literal> </Entry>
<Entry> <Literal>HsBool</Literal> </Entry>
<Entry> unspec. integral type </Entry>
<Entry> (11) </Entry>
</Row>
<Row>
<Entry>
<Literal>Addr</Literal> </Entry>
<Entry> <Literal>HsAddr</Literal> </Entry>
<Entry> void* (6) </Entry>
<Entry> </Entry>
</Row>
<Row>
<Entry>
<Literal>ForeignObj</Literal> </Entry>
<Entry> <Literal>HsForeignObj</Literal> </Entry>
<Entry> void* (7) </Entry>
<Entry> </Entry>
</Row>
<Row>
<Entry>
<Literal>StablePtr</Literal> </Entry>
<Entry> <Literal>HsStablePtr</Literal> </Entry>
<Entry> void* (8) </Entry>
<Entry> </Entry>
</Row>
</TBody>
</TGroup>
</Table>
</Para>
<Para>
<Emphasis remap="bf">Some remarks:</Emphasis>
<OrderedList>
<ListItem>
<Para>
A Haskell system that implements the FFI will supply a header file
<Filename>HsFFI.h</Filename> that includes target platform specific definitions
for the above types and values.
</Para>
</ListItem>
<ListItem>
<Para>
The sized numeric types <Literal>Hs{Int,Word}{8,16,32,64}</Literal> have
a 1-1 mapping to ISO C 99's <Literal>{,u}int{8,16,32,64}_t</Literal>. For systems
that doesn't support this revision of ISO C, a best-fit mapping
onto the supported C types is provided.
</Para>
</ListItem>
<ListItem>
<Para>
An implementation which does not support 64 bit integral types
on the C side should implement <Literal>Hs{Int,Word}64</Literal> as a struct. In
this case the bounds <Constant>HS_INT64_{MIN,MAX}</Constant> and <Constant>HS_WORD64_MAX</Constant>
are undefined.
</Para>
</ListItem>
<ListItem>
<Para>
A valid Haskell representation of <Literal>Int</Literal> has to be equal to or
wider than 30 bits. The <Literal>HsInt</Literal> synonym is guaranteed to map
onto a C type that satisifies Haskell's requirement for <Literal>Int</Literal>.
</Para>
</ListItem>
<ListItem>
<Para>
It is guaranteed that <Literal>Hs{Float,Double}</Literal> are one of C's
floating-point types <Literal>float</Literal>/<Literal>double</Literal>/<Literal>long double</Literal>.
</Para>
</ListItem>
<ListItem>
<Para>
It is guaranteed that <Literal>HsAddr</Literal> is of the same size as <Literal>void*</Literal>, so
any other pointer type can be converted to and from HsAddr without any
loss of information (K&R, Appendix A6.8).
</Para>
</ListItem>
<ListItem>
<Para>
Foreign objects are handled like <Literal>Addr</Literal> by the FFI, so there
is again the guarantee that <Literal>HsForeignObj</Literal> is the same as
<Literal>void*</Literal>. The separate name is meant as a reminder that there is
a finalizer attached to the object pointed to.
</Para>
</ListItem>
<ListItem>
<Para>
Stable pointers are passed as addresses by the FFI, but this is
only because a <Literal>void*</Literal> is used as a generic container in most
APIs, not because they are real addresses. To make this special
case clear, a separate C type is used here.
</Para>
</ListItem>
<ListItem>
<Para>
The bounds are preprocessor macros, so they can be used in
<Literal>#if</Literal> and for array bounds.
</Para>
</ListItem>
<ListItem>
<Para>
Floating-point limits are a little bit more complicated, so
preprocessor macros mirroring ISO C's <Filename>float.h</Filename> are provided:
<ProgramListing>
HS_{FLOAT,DOUBLE}_RADIX
HS_{FLOAT,DOUBLE}_ROUNDS
HS_{FLOAT,DOUBLE}_EPSILON
HS_{FLOAT,DOUBLE}_DIG
HS_{FLOAT,DOUBLE}_MANT_DIG
HS_{FLOAT,DOUBLE}_MIN
HS_{FLOAT,DOUBLE}_MIN_EXP
HS_{FLOAT,DOUBLE}_MIN_10_EXP
HS_{FLOAT,DOUBLE}_MAX
HS_{FLOAT,DOUBLE}_MAX_EXP
HS_{FLOAT,DOUBLE}_MAX_10_EXP
</ProgramListing>
</Para>
</ListItem>
<ListItem>
<Para>
It is guaranteed that Haskell's <Literal>False</Literal>/<Literal>True</Literal> map to
C's <Literal>0</Literal>/<Literal>1</Literal>, respectively, and vice versa. The mapping of
any other integral value to <Literal>Bool</Literal> is left unspecified.
</Para>
</ListItem>
<ListItem>
<Para>
To avoid name clashes, identifiers starting with <Literal>Hs</Literal> and
macros starting with <Literal>HS_</Literal> are reserved for the FFI.
</Para>
</ListItem>
<ListItem>
<Para>
<Emphasis>GHC only:</Emphasis> The GHC specific types <Literal>ByteArray</Literal> and
<Literal>MutableByteArray</Literal> both map to <Literal>char*</Literal>.
</Para>
</ListItem>
</OrderedList>
</Para>
</Sect2>
<Sect2 id="sec-prim-remarks">
<Title>Some <Literal>foreign import</Literal> wrinkles
</Title>
<Para>
<ItemizedList>
<ListItem>
<Para>
By default, a <Literal>foreign import</Literal> function is <Emphasis>safe</Emphasis>. A safe
external function may cause a Haskell garbage collection as a result
of being called. This will typically happen when the imported
function end up calling Haskell functions that reside in the same
'Haskell world' (i.e., shares the same storage manager heap) -- see
Section <XRef LinkEnd="sec-entry"> for
details of how the FFI let's you call Haskell functions from the outside.
If the programmer can guarantee that the imported function won't
call back into Haskell, the <Literal>foreign import</Literal> can be marked as
'unsafe' (see Section <XRef LinkEnd="sec-primitive"> for details of
how to do this.)
Unsafe calls are cheaper than safe ones, so distinguishing the two
classes of external calls may be worth your while if you're extra
conscious about performance.
</Para>
</ListItem>
<ListItem>
<Para>
A <Literal>foreign import</Literal>ed function should clearly not need to know that
it is being called from Haskell. One consequence of this is that the
lifetimes of the arguments that are passed from Haskell <Emphasis>must</Emphasis>
equal that of a normal C call. For instance, for the following decl,
<ProgramListing>
foreign import "mumble" mumble :: ForeignObj -> IO ()
f :: Addr -> IO ()
f ptr = do
fo <- newForeignObj ptr myFinalizer
mumble fo
</ProgramListing>
The <Literal>ForeignObj</Literal> must live across the call to <Function>mumble</Function> even if
it is not subsequently used/reachable. Why the insistence on this?
Consider what happens if <Function>mumble</Function> calls a function which calls back
into the Haskell world to execute a function, behind our back as it
were. This evaluation may possibly cause a garbage collection, with
the result that <Literal>fo</Literal> may end up being finalised.
By guaranteeing that <Literal>fo</Literal> will be considered live across the call
to <Function>mumble</Function>, the unfortunate situation where <Literal>fo</Literal> is finalised
(and hence the reference passed to <Function>mumble</Function> is suddenly no longer
valid) is avoided.
</Para>
</ListItem>
</ItemizedList>
</Para>