File: manual032.html

package info (click to toggle)
ocaml-doc 3.09-1
  • links: PTS
  • area: non-free
  • in suites: etch, etch-m68k
  • size: 10,428 kB
  • ctags: 4,963
  • sloc: ml: 9,244; makefile: 2,413; ansic: 122; sh: 49; asm: 17
file content (1935 lines) | stat: -rw-r--r-- 97,164 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
            "http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML>
<HEAD>



<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="hevea 1.08">
<LINK rel="stylesheet" type="text/css" href="manual.css">
<TITLE>
Interfacing C with Objective Caml
</TITLE>
</HEAD>
<BODY >
<A HREF="manual031.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A>
<A HREF="index.html"><IMG SRC ="contents_motif.gif" ALT="Up"></A>
<A HREF="manual033.html"><IMG SRC ="next_motif.gif" ALT="Next"></A>
<HR>

<H1 CLASS="chapter"><A NAME="htoc204">Chapter&nbsp;18</A>&nbsp;&nbsp;Interfacing C with Objective Caml</H1> <A NAME="c:intf-c"></A>

This chapter describes how user-defined primitives, written in C, can
be linked with Caml code and called from Caml functions.<BR>
<BR>
<div style="background-color:yellow; color:red; border-style:none; border-width:0.5pt">
Since 3.08.0 all global C identifiers have been prefixed with
"<KBD>caml_</KBD>" to avoid name clashes with other libraries (i.e.,
<KBD>caml_alloc_small</KBD> instead of <KBD>alloc_small</KBD>).
This change has been announced but has not been documented
before. These new "<KBD>caml_</KBD>" prefixes are not marked in
this page.
</div>

<H2 CLASS="section"><A NAME="htoc205">18.1</A>&nbsp;&nbsp;Overview and compilation information</H2>


<H3 CLASS="subsection"><A NAME="htoc206">18.1.1</A>&nbsp;&nbsp;Declaring primitives</H3>
User primitives are declared in an implementation file or
<TT>struct</TT>...<TT>end</TT> module expression using the <TT>external</TT> keyword:
<PRE>
        external <I>name</I> : <I>type</I> = <I>C-function-name</I>
</PRE>
This defines the value name <I>name</I> as a function with type
<I>type</I> that executes by calling the given C function.
For instance, here is how the <TT>input</TT> primitive is declared in the
standard library module <TT>Pervasives</TT>:
<PRE CLASS="verbatim">
        external input : in_channel -&gt; string -&gt; int -&gt; int -&gt; int
                       = "input"
</PRE>Primitives with several arguments are always curried. The C function
does not necessarily have the same name as the ML function.<BR>
<BR>
External functions thus defined can be specified in interface files or
<TT>sig</TT>...<TT>end</TT> signatures either as regular values
<PRE>
        val <I>name</I> : <I>type</I>
</PRE>
thus hiding their implementation as a C function, or explicitly as
&#8220;manifest&#8221; external functions
<PRE>
        external <I>name</I> : <I>type</I> = <I>C-function-name</I>
</PRE>
The latter is slightly more efficient, as it allows clients of the
module to call directly the C function instead of going through the
corresponding Caml function. <BR>
<BR>
The arity (number of arguments) of a primitive is automatically
determined from its Caml type in the <TT>external</TT> declaration, by
counting the number of function arrows in the type. For instance,
<TT>input</TT> above has arity 4, and the <TT>input</TT> C function is called with
four arguments. Similarly,
<PRE CLASS="verbatim">
    external input2 : in_channel * string * int * int -&gt; int = "input2"
</PRE>has arity 1, and the <TT>input2</TT> C function receives one argument (which
is a quadruple of Caml values).<BR>
<BR>
Type abbreviations are not expanded when determining the arity of a
primitive. For instance,
<PRE CLASS="verbatim">
        type int_endo = int -&gt; int
        external f : int_endo -&gt; int_endo = "f"
        external g : (int -&gt; int) -&gt; (int -&gt; int) = "f"
</PRE><TT>f</TT> has arity 1, but <TT>g</TT> has arity 2. This allows a primitive to
return a functional value (as in the <TT>f</TT> example above): just remember
to name the functional return type in a type abbreviation.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc207">18.1.2</A>&nbsp;&nbsp;Implementing primitives</H3>
User primitives with arity <I>n</I> &#8804; 5 are implemented by C functions
that take <I>n</I> arguments of type <TT>value</TT>, and return a result of type
<TT>value</TT>. The type <TT>value</TT> is the type of the representations for Caml
values. It encodes objects of several base types (integers,
floating-point numbers, strings, ...), as well as Caml data
structures. The type <TT>value</TT> and the associated conversion
functions and macros are described in details below. For instance,
here is the declaration for the C function implementing the <TT>input</TT>
primitive:
<PRE CLASS="verbatim">
CAMLprim value input(value channel, value buffer, value offset, value length)
{
  ...
}
</PRE>When the primitive function is applied in a Caml program, the C
function is called with the values of the expressions to which the
primitive is applied as arguments. The value returned by the function is
passed back to the Caml program as the result of the function
application.<BR>
<BR>
User primitives with arity greater than 5 should be implemented by two
C functions. The first function, to be used in conjunction with the
bytecode compiler <TT>ocamlc</TT>, receives two arguments: a pointer to an
array of Caml values (the values for the arguments), and an
integer which is the number of arguments provided. The other function,
to be used in conjunction with the native-code compiler <TT>ocamlopt</TT>,
takes its arguments directly. For instance, here are the two C
functions for the 7-argument primitive <TT>Nat.add_nat</TT>:
<PRE CLASS="verbatim">
CAMLprim value add_nat_native(value nat1, value ofs1, value len1,
                              value nat2, value ofs2, value len2,
                              value carry_in)
{
  ...
}
CAMLprim value add_nat_bytecode(value * argv, int argn)
{
  return add_nat_native(argv[0], argv[1], argv[2], argv[3],
                        argv[4], argv[5], argv[6]);
}
</PRE>The names of the two C functions must be given in the primitive
declaration, as follows:
<PRE>
        external <I>name</I> : <I>type</I> =
                 <I>bytecode-C-function-name native-code-C-function-name</I>
</PRE>
For instance, in the case of <TT>add_nat</TT>, the declaration is:
<PRE CLASS="verbatim">
        external add_nat: nat -&gt; int -&gt; int -&gt; nat -&gt; int -&gt; int -&gt; int -&gt; int
                        = "add_nat_bytecode" "add_nat_native"
</PRE>
Implementing a user primitive is actually two separate tasks: on the
one hand, decoding the arguments to extract C values from the given
Caml values, and encoding the return value as a Caml 
value; on the other hand, actually computing the result from the arguments.
Except for very simple primitives, it is often preferable to have two
distinct C functions to implement these two tasks. The first function
actually implements the primitive, taking native C values as
arguments and returning a native C value. The second function,
often called the &#8220;stub code&#8221;, is a simple wrapper around the first
function that converts its arguments from Caml values to C values,
call the first function, and convert the returned C value to Caml
value. For instance, here is the stub code for the <TT>input</TT>
primitive:
<PRE CLASS="verbatim">
CAMLprim value input(value channel, value buffer, value offset, value length)
{
  return Val_long(getblock((struct channel *) channel,
                           &amp;Byte(buffer, Long_val(offset)),
                           Long_val(length)));
}
</PRE>(Here, <TT>Val_long</TT>, <TT>Long_val</TT> and so on are conversion macros for the
type <TT>value</TT>, that will be described later. The <TT>CAMLprim</TT> macro
expands to the required compiler directives to ensure that the
function following it is exported and accessible from Caml.)
The hard work is performed by the function <TT>getblock</TT>, which is
declared as:
<PRE CLASS="verbatim">
long getblock(struct channel * channel, char * p, long n)
{
  ...
}
</PRE>
To write C code that operates on Objective Caml values, the following
include files are provided:
<BR>
<BR>
<DIV CLASS="center"><TABLE BORDER=1 CELLSPACING=0 CELLPADDING=1 WIDTH="80%">
<TR><TD ALIGN=center NOWRAP><B>Include file</B></TD>
<TD ALIGN=center NOWRAP><B>Provides</B></TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP>
<TT>caml/mlvalues.h</TT></TD>
<TD VALIGN=top ALIGN=left>definition of the <TT>value</TT> type, and conversion macros</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml/alloc.h</TT></TD>
<TD VALIGN=top ALIGN=left>allocation functions (to create structured Caml
objects)</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml/memory.h</TT></TD>
<TD VALIGN=top ALIGN=left>miscellaneous memory-related functions
and macros (for GC interface, in-place modification of structures, etc).</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml/fail.h</TT></TD>
<TD VALIGN=top ALIGN=left>functions for raising exceptions
(see section&nbsp;<A HREF="#s:c-exceptions">18.4.5</A>)</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml/callback.h</TT></TD>
<TD VALIGN=top ALIGN=left>callback from C to Caml (see
section&nbsp;<A HREF="#s:callback">18.7</A>).</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml/custom.h</TT></TD>
<TD VALIGN=top ALIGN=left>operations on custom blocks (see
section&nbsp;<A HREF="#s:custom">18.9</A>).</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml/intext.h</TT></TD>
<TD VALIGN=top ALIGN=left>operations for writing user-defined
serialization and deserialization functions for custom blocks
(see section&nbsp;<A HREF="#s:custom">18.9</A>).</TD>
</TR></TABLE></DIV><BR>
<BR>

These files reside in the <TT>caml/</TT> subdirectory of the Objective Caml
standard library directory (usually <TT>/usr/local/lib/ocaml</TT>).<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc208">18.1.3</A>&nbsp;&nbsp;Statically linking C code with Caml code</H3>
<A NAME="staticlink-c-code"></A>
The Objective Caml runtime system comprises three main parts: the bytecode
interpreter, the memory manager, and a set of C functions that
implement the primitive operations. Some bytecode instructions are
provided to call these C functions, designated by their offset in a
table of functions (the table of primitives).<BR>
<BR>
In the default mode, the Caml linker produces bytecode for the
standard runtime system, with a standard set of primitives. References
to primitives that are not in this standard set result in the
&#8220;unavailable C primitive&#8221; error. (Unless dynamic loading of C
libraries is supported &ndash; see section&nbsp;<A HREF="#dynlink-c-code">18.1.4</A> below.)<BR>
<BR>
In the &#8220;custom runtime&#8221; mode, the Caml linker scans the
object files and determines the set of required primitives. Then, it
builds a suitable runtime system, by calling the native code linker with:
<UL CLASS="itemize"><LI CLASS="li-itemize">
the table of the required primitives;
<LI CLASS="li-itemize">a library that provides the bytecode interpreter, the
memory manager, and the standard primitives;
<LI CLASS="li-itemize">libraries and object code files (<TT>.o</TT> files) mentioned on the
command line for the Caml linker, that provide implementations
for the user's primitives.
</UL>
This builds a runtime system with the required primitives. The Caml
linker generates bytecode for this custom runtime system. The
bytecode is appended to the end of the custom runtime system, so that
it will be automatically executed when the output file (custom
runtime + bytecode) is launched.<BR>
<BR>
To link in &#8220;custom runtime&#8221; mode, execute the <TT>ocamlc</TT> command with:
<UL CLASS="itemize"><LI CLASS="li-itemize">
the <TT>-custom</TT> option;
<LI CLASS="li-itemize">the names of the desired Caml object files (<TT>.cmo</TT> and <TT>.cma</TT> files) ;
<LI CLASS="li-itemize">the names of the C object files and libraries (<TT>.o</TT> and <TT>.a</TT>
files) that implement the required primitives. Under Unix and Windows,
a library named <TT>lib</TT><I>name</I><TT>.a</TT> residing in one of the standard
library directories can also be specified as <TT>-cclib -l</TT><I>name</I>.
</UL>
If you are using the native-code compiler <TT>ocamlopt</TT>, the <TT>-custom</TT>
flag is not needed, as the final linking phase of <TT>ocamlopt</TT> always
builds a standalone executable. To build a mixed Caml/C executable,
execute the <TT>ocamlopt</TT> command with:
<UL CLASS="itemize"><LI CLASS="li-itemize">
the names of the desired Caml native object files (<TT>.cmx</TT> and
<TT>.cmxa</TT> files);
<LI CLASS="li-itemize">the names of the C object files and libraries (<TT>.o</TT>, <TT>.a</TT>,
<TT>.so</TT> or <TT>.dll</TT> files) that implement the required primitives.
</UL>
Starting with OCaml 3.00, it is possible to record the
<TT>-custom</TT> option as well as the names of C libraries in a Caml
library file <TT>.cma</TT> or <TT>.cmxa</TT>. For instance, consider a Caml library
<TT>mylib.cma</TT>, built from the Caml object files <TT>a.cmo</TT> and <TT>b.cmo</TT>,
which reference C code in <TT>libmylib.a</TT>. If the library is
built as follows:
<PRE>
        ocamlc -a -o mylib.cma -custom a.cmo b.cmo -cclib -lmylib
</PRE>
users of the library can simply link with <TT>mylib.cma</TT>:
<PRE>
        ocamlc -o myprog mylib.cma ...
</PRE>
and the system will automatically add the <TT>-custom</TT> and <TT>-cclib -lmylib</TT> options, achieving the same effect as
<PRE>
        ocamlc -o myprog -custom a.cmo b.cmo ... -cclib -lmylib
</PRE>
The alternative, of course, is to build the library without extra
options:
<PRE>
        ocamlc -a -o mylib.cma a.cmo b.cmo
</PRE>
and then ask users to provide the <TT>-custom</TT> and <TT>-cclib -lmylib</TT>
options themselves at link-time:
<PRE>
        ocamlc -o myprog -custom mylib.cma ... -cclib -lmylib
</PRE>
The former alternative is more convenient for the final users of the
library, however.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc209">18.1.4</A>&nbsp;&nbsp;Dynamically linking C code with Caml code</H3>
<A NAME="dynlink-c-code"></A>
Starting with OCaml 3.03, an alternative to static linking of C code
using the <TT>-custom</TT> code is provided. In this mode, the Caml linker
generates a pure bytecode executable (no embedded custom runtime
system) that simply records the names of dynamically-loaded libraries
containing the C code. The standard Caml runtime system <TT>ocamlrun</TT>
then loads dynamically these libraries, and resolves references to the
required primitives, before executing the bytecode.<BR>
<BR>
This facility is currently supported and known to work well under
Linux and Windows (the native Windows port). It is supported, but not
fully tested yet, under FreeBSD, Tru64, Solaris and Irix. It is not
supported yet under other Unixes, Cygwin for Windows, and MacOS.<BR>
<BR>
To dynamically link C code with Caml code, the C code must first be
compiled into a shared library (under Unix) or DLL (under Windows).
This involves 1- compiling the C files with appropriate C compiler
flags for producing position-independent code, and 2- building a
shared library from the resulting object files. The resulting shared
library or DLL file must be installed in a place where <TT>ocamlrun</TT> can
find it later at program start-up time (see
section&nbsp;<A HREF="manual024.html#s-ocamlrun-dllpath">10.3</A>).
Finally (step 3), execute the <TT>ocamlc</TT> command with
<UL CLASS="itemize"><LI CLASS="li-itemize">
the names of the desired Caml object files (<TT>.cmo</TT> and <TT>.cma</TT> files) ;
<LI CLASS="li-itemize">the names of the C shared libraries (<TT>.so</TT> or <TT>.dll</TT> files) that
implement the required primitives. Under Unix and Windows, 
a library named <TT>dll</TT><I>name</I><TT>.so</TT> (respectively, <TT>.dll</TT>) residing
in one of the standard library directories can also be specified as
<TT>-dllib -l</TT><I>name</I>.
</UL>
Do <EM>not</EM> set the <TT>-custom</TT> flag, otherwise you're back to static linking
as described in section&nbsp;<A HREF="#staticlink-c-code">18.1.3</A>.
Under Unix, the <TT>ocamlmklib</TT> tool (see section&nbsp;<A HREF="#s-ocamlmklib">18.10</A>)
automates steps 2 and 3.<BR>
<BR>
As in the case of static linking, it is possible (and recommended) to
record the names of C libraries in a Caml <TT>.cmo</TT> library archive. 
Consider again a Caml library
<TT>mylib.cma</TT>, built from the Caml object files <TT>a.cmo</TT> and <TT>b.cmo</TT>,
which reference C code in <TT>dllmylib.so</TT>. If the library is
built as follows:
<PRE>
        ocamlc -a -o mylib.cma a.cmo b.cmo -dllib -lmylib
</PRE>
users of the library can simply link with <TT>mylib.cma</TT>:
<PRE>
        ocamlc -o myprog mylib.cma ...
</PRE>
and the system will automatically add the <TT>-dllib -lmylib</TT> option,
achieving the same effect as
<PRE>
        ocamlc -o myprog a.cmo b.cmo ... -dllib -lmylib
</PRE>
Using this mechanism, users of the library <TT>mylib.cma</TT> do not need to
known that it references C code, nor whether this C code must be
statically linked (using <TT>-custom</TT>) or dynamically linked.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc210">18.1.5</A>&nbsp;&nbsp;Choosing between static linking and dynamic linking</H3>
After having described two different ways of linking C code with Caml
code, we now review the pros and cons of each, to help developers of
mixed Caml/C libraries decide.<BR>
<BR>
The main advantage of dynamic linking is that it preserves the
platform-independence of bytecode executables. That is, the bytecode
executable contains no machine code, and can therefore be compiled on
platform <I>A</I> and executed on other platforms <I>B</I>, <I>C</I>, ..., as long
as the required shared libraries are available on all these
platforms. In contrast, executables generated by <TT>ocamlc -custom</TT> run
only on the platform on which they were created, because they embark a
custom-tailored runtime system specific to that platform. In
addition, dynamic linking results in smaller executables.<BR>
<BR>
Another advantage of dynamic linking is that the final users of the
library do not need to have a C compiler, C linker, and C runtime
libraries installed on their machines. This is no big deal under 
Unix and Cygwin, but many Windows users are reluctant to install
Microsoft Visual C just to be able to do <TT>ocamlc -custom</TT>.<BR>
<BR>
There are two drawbacks to dynamic linking. The first is that the
resulting executable is not stand-alone: it requires the shared
libraries, as well as <TT>ocamlrun</TT>, to be installed on the machine
executing the code. If you wish to distribute a stand-alone
executable, it is better to link it statically, using <TT>ocamlc -custom -ccopt -static</TT> or <TT>ocamlopt -ccopt -static</TT>. Dynamic linking also
raises the &#8220;DLL hell&#8221; problem: some care must be taken to ensure
that the right versions of the shared libraries are found at start-up
time.<BR>
<BR>
The second drawback of dynamic linking is that it complicates the
construction of the library. The C compiler and linker flags to
compile to position-independent code and build a shared library vary
wildly between different Unix systems. Also, dynamic linking is not
supported on all Unix systems, requiring a fall-back case to static
linking in the Makefile for the library. The <TT>ocamlmklib</TT> command
(see section&nbsp;<A HREF="#s-ocamlmklib">18.10</A>) tries to hide some of these system
dependencies.<BR>
<BR>
In conclusion: dynamic linking is highly recommended under the native
Windows port, because there are no portability problems and it is much
more convenient for the end users. Under Unix, dynamic linking should
be considered for mature, frequently used libraries because it
enhances platform-independence of bytecode executables. For new or
rarely-used libraries, static linking is much simpler to set up in a
portable way.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc211">18.1.6</A>&nbsp;&nbsp;Building standalone custom runtime systems</H3>
<A NAME="s:custom-runtime"></A>
It is sometimes inconvenient to build a custom runtime system each
time Caml code is linked with C libraries, like <TT>ocamlc -custom</TT> does.
For one thing, the building of the runtime system is slow on some
systems (that have bad linkers or slow remote file systems); for
another thing, the platform-independence of bytecode files is lost,
forcing to perform one <TT>ocamlc -custom</TT> link per platform of interest.<BR>
<BR>
An alternative to <TT>ocamlc -custom</TT> is to build separately a custom
runtime system integrating the desired C libraries, then generate
&#8220;pure&#8221; bytecode executables (not containing their own runtime
system) that can run on this custom runtime. This is achieved by the
<TT>-make_runtime</TT> and <TT>-use_runtime</TT> flags to <TT>ocamlc</TT>. For example,
to build a custom runtime system integrating the C parts of the
&#8220;Unix&#8221; and &#8220;Threads&#8221; libraries, do:
<PRE CLASS="verbatim">
        ocamlc -make-runtime -o /home/me/ocamlunixrun unix.cma threads.cma
</PRE>To generate a bytecode executable that runs on this runtime system,
do:
<PRE>
        ocamlc -use-runtime /home/me/ocamlunixrun -o myprog \
                unix.cma threads.cma <I>your .cmo and .cma files</I>
</PRE>
The bytecode executable <TT>myprog</TT> can then be launched as usual:
<TT>myprog</TT> <I>args</I> or <TT>/home/me/ocamlunixrun myprog</TT> <I>args</I>.<BR>
<BR>
Notice that the bytecode libraries <TT>unix.cma</TT> and <TT>threads.cma</TT> must
be given twice: when building the runtime system (so that <TT>ocamlc</TT>
knows which C primitives are required) and also when building the
bytecode executable (so that the bytecode from <TT>unix.cma</TT> and
<TT>threads.cma</TT> is actually linked in).<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc212">18.2</A>&nbsp;&nbsp;The <TT>value</TT> type</H2>

All Caml objects are represented by the C type <TT>value</TT>,
defined in the include file <TT>caml/mlvalues.h</TT>, along with macros to
manipulate values of that type. An object of type <TT>value</TT> is either:
<UL CLASS="itemize"><LI CLASS="li-itemize">
an unboxed integer;
<LI CLASS="li-itemize">a pointer to a block inside the heap (such as the blocks
allocated through one of the <CODE>caml_alloc_*</CODE> functions below);
<LI CLASS="li-itemize">a pointer to an object outside the heap (e.g., a pointer to a block
allocated by <TT>malloc</TT>, or to a C variable).
</UL>

<H3 CLASS="subsection"><A NAME="htoc213">18.2.1</A>&nbsp;&nbsp;Integer values</H3>
Integer values encode 31-bit signed integers (63-bit on 64-bit
architectures). They are unboxed (unallocated).<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc214">18.2.2</A>&nbsp;&nbsp;Blocks</H3>
Blocks in the heap are garbage-collected, and therefore have strict
structure constraints. Each block includes a header containing the
size of the block (in words), and the tag of the block.
The tag governs how the contents of the blocks are structured. A tag
lower than <TT>No_scan_tag</TT> indicates a structured block, containing
well-formed values, which is recursively traversed by the garbage
collector. A tag greater than or equal to <TT>No_scan_tag</TT> indicates a
raw block, whose contents are not scanned by the garbage collector.
For the benefits of ad-hoc polymorphic primitives such as equality and
structured input-output, structured and raw blocks are further
classified according to their tags as follows:
<BR>
<BR>
<DIV CLASS="center"><TABLE BORDER=1 CELLSPACING=0 CELLPADDING=1 WIDTH="80%">
<TR><TD ALIGN=center NOWRAP><B>Tag</B></TD>
<TD ALIGN=center NOWRAP><B>Contents of the block</B></TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP>
0 to <TT>No_scan_tag</TT>&minus;1</TD>
<TD VALIGN=top ALIGN=left>A structured block (an array of
Caml objects). Each field is a <TT>value</TT>.</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>Closure_tag</TT></TD>
<TD VALIGN=top ALIGN=left>A closure representing a functional value. The first
word is a pointer to a piece of code, the remaining words are
<TT>value</TT> containing the environment.</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>String_tag</TT></TD>
<TD VALIGN=top ALIGN=left>A character string.</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>Double_tag</TT></TD>
<TD VALIGN=top ALIGN=left>A double-precision floating-point number.</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>Double_array_tag</TT></TD>
<TD VALIGN=top ALIGN=left>An array or record of double-precision
floating-point numbers.</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>Abstract_tag</TT></TD>
<TD VALIGN=top ALIGN=left>A block representing an abstract datatype.</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>Custom_tag</TT></TD>
<TD VALIGN=top ALIGN=left>A block representing an abstract datatype
 with user-defined finalization, comparison, hashing,
 serialization and deserialization functions atttached.</TD>
</TR></TABLE></DIV><BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc215">18.2.3</A>&nbsp;&nbsp;Pointers outside the heap</H3>
Any word-aligned pointer to an address outside the heap can be safely
cast to and from the type <TT>value</TT>. This includes pointers returned by
<TT>malloc</TT>, and pointers to C variables (of size at least one word)
obtained with the <CODE>&amp;</CODE> operator.<BR>
<BR>
Caution: if a pointer returned by <TT>malloc</TT> is cast to the type <TT>value</TT>
and returned to Caml, explicit deallocation of the pointer using
<TT>free</TT> is potentially dangerous, because the pointer may still be
accessible from the Caml world. Worse, the memory space deallocated
by <TT>free</TT> can later be reallocated as part of the Caml heap; the
pointer, formerly pointing outside the Caml heap, now points inside
the Caml heap, and this can confuse the garbage collector. To avoid
these problems, it is preferable to wrap the pointer in a Caml block
with tag <TT>Abstract_tag</TT> or <TT>Custom_tag</TT>.<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc216">18.3</A>&nbsp;&nbsp;Representation of Caml data types</H2>

This section describes how Caml data types are encoded in the
<TT>value</TT> type.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc217">18.3.1</A>&nbsp;&nbsp;Atomic types</H3><BR>
<BR>
<DIV CLASS="center"><TABLE BORDER=1 CELLSPACING=0 CELLPADDING=1 WIDTH="80%">
<TR><TD ALIGN=center NOWRAP><B>Caml type</B></TD>
<TD ALIGN=center NOWRAP><B>Encoding</B></TD>
</TR>
<TR><TD ALIGN=left NOWRAP>
<TT>int</TT></TD>
<TD ALIGN=left NOWRAP>Unboxed integer values.</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>char</TT></TD>
<TD ALIGN=left NOWRAP>Unboxed integer values (ASCII code).</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>float</TT></TD>
<TD ALIGN=left NOWRAP>Blocks with tag <TT>Double_tag</TT>.</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>string</TT></TD>
<TD ALIGN=left NOWRAP>Blocks with tag <TT>String_tag</TT>.</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>int32</TT></TD>
<TD ALIGN=left NOWRAP>Blocks with tag <TT>Custom_tag</TT>.</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>int64</TT></TD>
<TD ALIGN=left NOWRAP>Blocks with tag <TT>Custom_tag</TT>.</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>nativeint</TT></TD>
<TD ALIGN=left NOWRAP>Blocks with tag <TT>Custom_tag</TT>.</TD>
</TR></TABLE></DIV><BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc218">18.3.2</A>&nbsp;&nbsp;Tuples and records</H3>
Tuples are represented by pointers to blocks, with tag&nbsp;0.<BR>
<BR>
Records are also represented by zero-tagged blocks. The ordering of
labels in the record type declaration determines the layout of
the record fields: the value associated to the label
declared first is stored in field&nbsp;0 of the block, the value associated
to the label declared next goes in field&nbsp;1, and so on.<BR>
<BR>
As an optimization, records whose fields all have static type <TT>float</TT>
are represented as arrays of floating-point numbers, with tag
<TT>Double_array_tag</TT>. (See the section below on arrays.)<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc219">18.3.3</A>&nbsp;&nbsp;Arrays</H3>
Arrays of integers and pointers are represented like tuples, 
that is, as pointers to blocks tagged&nbsp;0. They are accessed with the
<TT>Field</TT> macro for reading and the <TT>modify</TT> function for writing.<BR>
<BR>
Arrays of floating-point numbers (type <TT>float array</TT>)
have a special, unboxed, more efficient representation.
These arrays are represented by pointers to blocks with tag
<TT>Double_array_tag</TT>. They should be accessed with the <TT>Double_field</TT>
and <TT>Store_double_field</TT> macros.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc220">18.3.4</A>&nbsp;&nbsp;Concrete types</H3>
Constructed terms are represented either by unboxed integers (for
constant constructors) or by blocks whose tag encode the constructor
(for non-constant constructors). The constant constructors and the
non-constant constructors for a given concrete type are numbered
separately, starting from 0, in the order in which they appear in the
concrete type declaration. Constant constructors are represented by
unboxed integers equal to the constructor number. Non-constant
constructors declared with a <I>n</I>-tuple as argument are represented by
a block of size <I>n</I>, tagged with the constructor number; the <I>n</I>
fields contain the components of its tuple argument. Other
non-constant constructors are represented by a block of size&nbsp;1, tagged
with the constructor number; the field&nbsp;0 contains the value of the
constructor argument. Example:<BR>
<BR>
<DIV CLASS="center"><TABLE BORDER=1 CELLSPACING=0 CELLPADDING=1 WIDTH="80%">
<TR><TD ALIGN=center NOWRAP><B>Constructed term</B></TD>
<TD ALIGN=center NOWRAP><B>Representation</B></TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP>
<TT>()</TT></TD>
<TD VALIGN=top ALIGN=left><TT>Val_int(0)</TT></TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>false</TT></TD>
<TD VALIGN=top ALIGN=left><TT>Val_int(0)</TT></TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>true</TT></TD>
<TD VALIGN=top ALIGN=left><TT>Val_int(1)</TT></TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>[]</TT></TD>
<TD VALIGN=top ALIGN=left><TT>Val_int(0)</TT></TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>h::t</TT></TD>
<TD VALIGN=top ALIGN=left>Block with size = 2 and tag = 0; first field
contains <TT>h</TT>, second field <TT>t</TT></TD>
</TR></TABLE></DIV><BR>
<BR>
As a convenience, <TT>caml/mlvalues.h</TT> defines the macros <TT>Val_unit</TT>,
<TT>Val_false</TT> and <TT>Val_true</TT> to refer to <TT>()</TT>, <TT>false</TT> and <TT>true</TT>.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc221">18.3.5</A>&nbsp;&nbsp;Objects</H3>
Objects are represented as blocks
<div style="background-color:yellow; color:red; border-style:none; border-width:0.5pt">
with tag <TT>Object_tag</TT>.
</div>
The first
field of the block refers to the object class and associated method
suite, in a format that cannot easily be exploited from C.
<div style="background-color:yellow; color:red; border-style:none; border-width:0.5pt">
The second
field contains a unique object ID, used for comparisons.
</div>
The remaining
fields of the object contain the values of the instance variables of
the object. Instance variables are stored in the order in which they
appear in the class definition (taking inherited classes into
account).<BR>
<BR>
One may extract a public method from an object using the C function
<TT>caml_get_public_method</TT> (declared in <TT>&lt;caml/mlvalues.h&gt;</TT>.)
Since public method tags are hashed in the same way as variant tags,
and methods are functions taking self as first argument, if you want
to do the method call <TT>foo#bar</TT> from the C side, you should call:
<PRE CLASS="verbatim">
  callback(caml_get_public_method(foo, hash_variant("bar")), foo);
</PRE>

<H3 CLASS="subsection"><A NAME="htoc222">18.3.6</A>&nbsp;&nbsp;Variants</H3>
Like constructed terms, values of variant types are represented either
as integers (for variants without arguments), or as blocks (for
variants with an argument). Unlike constructed terms, variant
constructors are not numbered starting from 0, but identified by a
hash value (a Caml integer), as computed by the C function
<TT>hash_variant</TT> (declared in <TT>&lt;caml/mlvalues.h&gt;</TT>):
the hash value for a variant constructor named, say, <TT>VConstr</TT>
is <TT>hash_variant("VConstr")</TT>.<BR>
<BR>
The variant value <TT>`VConstr</TT> is represented by
<TT>hash_variant("VConstr")</TT>. The variant value <TT>`VConstr(</TT><I>v</I><TT>)</TT> is
represented by a block of size 2 and tag 0, with field number 0
containing <TT>hash_variant("VConstr")</TT> and field number 1 containing
<I>v</I>.<BR>
<BR>
Unlike constructed values, variant values taking several arguments are
not flattened. That is, <TT>`VConstr(</TT><I>v</I><TT>, </TT><I>v'</I><TT>)</TT> is
represented by a block of size 2, whose field number 1 contains
the representation of the pair <TT>(</TT><I>v</I><TT>, </TT><I>v'</I><TT>)</TT>, rather than a
block of size 3 containing <I>v</I> and <I>v'</I> in fields 1 and 2.<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc223">18.4</A>&nbsp;&nbsp;Operations on values</H2>


<H3 CLASS="subsection"><A NAME="htoc224">18.4.1</A>&nbsp;&nbsp;Kind tests</H3>
<UL CLASS="itemize"><LI CLASS="li-itemize">
<TT>Is_long(</TT><I>v</I><TT>)</TT> is true if value <I>v</I> is an immediate integer,
false otherwise
<LI CLASS="li-itemize"><TT>Is_block(</TT><I>v</I><TT>)</TT> is true if value <I>v</I> is a pointer to a block,
and false if it is an immediate integer.
</UL>

<H3 CLASS="subsection"><A NAME="htoc225">18.4.2</A>&nbsp;&nbsp;Operations on integers</H3>
<UL CLASS="itemize"><LI CLASS="li-itemize">
<TT>Val_long(</TT><I>l</I><TT>)</TT> returns the value encoding the <TT>long int</TT> <I>l</I>.
<LI CLASS="li-itemize"><TT>Long_val(</TT><I>v</I><TT>)</TT> returns the <TT>long int</TT> encoded in value <I>v</I>.
<LI CLASS="li-itemize"><TT>Val_int(</TT><I>i</I><TT>)</TT> returns the value encoding the <TT>int</TT> <I>i</I>.
<LI CLASS="li-itemize"><TT>Int_val(</TT><I>v</I><TT>)</TT> returns the <TT>int</TT> encoded in value <I>v</I>.
<LI CLASS="li-itemize"><TT>Val_bool(</TT><I>x</I><TT>)</TT> returns the Caml boolean representing the
truth value of the C integer <I>x</I>.
<LI CLASS="li-itemize"><TT>Bool_val(</TT><I>v</I><TT>)</TT> returns 0 if <I>v</I> is the Caml boolean
<TT>false</TT>, 1 if <I>v</I> is <TT>true</TT>.
<LI CLASS="li-itemize"><TT>Val_true</TT>, <TT>Val_false</TT> represent the Caml booleans <TT>true</TT> and <TT>false</TT>.
</UL>

<H3 CLASS="subsection"><A NAME="htoc226">18.4.3</A>&nbsp;&nbsp;Accessing blocks</H3>
<UL CLASS="itemize"><LI CLASS="li-itemize">
<TT>Wosize_val(</TT><I>v</I><TT>)</TT> returns the size of the block <I>v</I>, in words,
excluding the header.
<LI CLASS="li-itemize"><TT>Tag_val(</TT><I>v</I><TT>)</TT> returns the tag of the block <I>v</I>.
<LI CLASS="li-itemize"><TT>Field(</TT><I>v</I><TT>, </TT><I>n</I><TT>)</TT> returns the value contained in the
<I>n</I><FONT SIZE=2><SUP>th</SUP></FONT> field of the structured block <I>v</I>. Fields are numbered from 0 to
<TT>Wosize_val</TT>(<I>v</I>)&minus;1.
<LI CLASS="li-itemize"><TT>Store_field(</TT><I>b</I><TT>, </TT><I>n</I><TT>, </TT><I>v</I><TT>)</TT> stores the value
<I>v</I> in the field number <I>n</I> of value <I>b</I>, which must be a
structured block.
<LI CLASS="li-itemize"><TT>Code_val(</TT><I>v</I><TT>)</TT> returns the code part of the closure <I>v</I>.
<LI CLASS="li-itemize"><TT>string_length(</TT><I>v</I><TT>)</TT> returns the length (number of characters)
of the string <I>v</I>.
<LI CLASS="li-itemize"><TT>Byte(</TT><I>v</I><TT>, </TT><I>n</I><TT>)</TT> returns the <I>n</I><FONT SIZE=2><SUP>th</SUP></FONT> character of the string
<I>v</I>, with type <TT>char</TT>. Characters are numbered from 0 to
<TT>string_length</TT>(<I>v</I>)&minus;1.
<LI CLASS="li-itemize"><TT>Byte_u(</TT><I>v</I><TT>, </TT><I>n</I><TT>)</TT> returns the <I>n</I><FONT SIZE=2><SUP>th</SUP></FONT> character of the string
<I>v</I>, with type <TT>unsigned char</TT>. Characters are numbered from 0 to
<TT>string_length</TT>(<I>v</I>)&minus;1.
<LI CLASS="li-itemize"><TT>String_val(</TT><I>v</I><TT>)</TT> returns a pointer to the first byte of the string
<I>v</I>, with type <TT>char *</TT>. This pointer is a valid C string: there is a
null character after the last character in the string. However, Caml
strings can contain embedded null characters, that will confuse
the usual C functions over strings. 
<LI CLASS="li-itemize"><TT>Double_val(</TT><I>v</I><TT>)</TT> returns the floating-point number contained in
value <I>v</I>, with type <TT>double</TT>.
<LI CLASS="li-itemize"><TT>Double_field(</TT><I>v</I><TT>, </TT><I>n</I><TT>)</TT> returns
the <I>n</I><FONT SIZE=2><SUP>th</SUP></FONT> element of the array of floating-point numbers <I>v</I> (a
block tagged <TT>Double_array_tag</TT>).
<LI CLASS="li-itemize"><TT>Store_double_field(</TT><I>v</I><TT>, </TT><I>n</I><TT>, </TT><I>d</I><TT>)</TT> stores the double precision floating-point number <I>d</I>
in the <I>n</I><FONT SIZE=2><SUP>th</SUP></FONT> element of the array of floating-point numbers <I>v</I>.
<LI CLASS="li-itemize"><TT>Data_custom_val(</TT><I>v</I><TT>)</TT> returns a pointer to the data part
of the custom block <I>v</I>. This pointer has type <TT>void *</TT> and must
be cast to the type of the data contained in the custom block.
<LI CLASS="li-itemize"><TT>Int32_val(</TT><I>v</I><TT>)</TT> returns the 32-bit integer contained
in the <TT>int32</TT> <I>v</I>.
<LI CLASS="li-itemize"><TT>Int64_val(</TT><I>v</I><TT>)</TT> returns the 64-bit integer contained
in the <TT>int64</TT> <I>v</I>.
<LI CLASS="li-itemize"><TT>Nativeint_val(</TT><I>v</I><TT>)</TT> returns the long integer contained
in the <TT>nativeint</TT> <I>v</I>.
</UL>
The expressions <TT>Field(</TT><I>v</I><TT>, </TT><I>n</I><TT>)</TT>,
<TT>Byte(</TT><I>v</I><TT>, </TT><I>n</I><TT>)</TT> and
<TT>Byte_u(</TT><I>v</I><TT>, </TT><I>n</I><TT>)</TT>
are valid l-values. Hence, they can be assigned to, resulting in an
in-place modification of value <I>v</I>.
Assigning directly to <TT>Field(</TT><I>v</I><TT>, </TT><I>n</I><TT>)</TT> must
be done with care to avoid confusing the garbage collector (see
below).<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc227">18.4.4</A>&nbsp;&nbsp;Allocating blocks</H3>

<H4 CLASS="subsubsection">Simple interface</H4>
<UL CLASS="itemize"><LI CLASS="li-itemize">
<TT>Atom(</TT><I>t</I><TT>)</TT> returns an &#8220;atom&#8221; (zero-sized block) with tag <I>t</I>.
Zero-sized blocks are preallocated outside of the heap. It is
incorrect to try and allocate a zero-sized block using the functions below.
For instance, <TT>Atom(0)</TT> represents the empty array.
<LI CLASS="li-itemize"><TT>caml_alloc(</TT><I>n</I><TT>, </TT><I>t</I><TT>)</TT> returns a fresh block of size <I>n</I>
with tag <I>t</I>. If <I>t</I> is less than <TT>No_scan_tag</TT>, then the
fields of the block are initialized with a valid value in order to
satisfy the GC constraints.
<LI CLASS="li-itemize"><TT>caml_alloc_tuple(</TT><I>n</I><TT>)</TT> returns a fresh block of size
<I>n</I> words, with tag 0.
<LI CLASS="li-itemize"><TT>caml_alloc_string(</TT><I>n</I><TT>)</TT> returns a string value of length <I>n</I> characters.
The string initially contains garbage.
<LI CLASS="li-itemize"><TT>caml_copy_string(</TT><I>s</I><TT>)</TT> returns a string value containing a copy of
the null-terminated C string <I>s</I> (a <TT>char *</TT>).
<LI CLASS="li-itemize"><TT>caml_copy_double(</TT><I>d</I><TT>)</TT> returns a floating-point value initialized
with the <TT>double</TT> <I>d</I>.
<LI CLASS="li-itemize"><TT>caml_copy_int32(</TT><I>i</I><TT>)</TT>, <TT>copy_int64(</TT><I>i</I><TT>)</TT> and
<TT>caml_copy_nativeint(</TT><I>i</I><TT>)</TT> return a value of Caml type <TT>int32</TT>,
<TT>int64</TT> and <TT>nativeint</TT>, respectively, initialized with the integer
<I>i</I>.
<LI CLASS="li-itemize"><TT>caml_alloc_array(</TT><I>f</I><TT>, </TT><I>a</I><TT>)</TT> allocates an array of values, calling
function <I>f</I> over each element of the input array <I>a</I> to transform it
into a value. The array <I>a</I> is an array of pointers terminated by the
null pointer. The function <I>f</I> receives each pointer as argument, and
returns a value. The zero-tagged block returned by
<TT>alloc_array(</TT><I>f</I><TT>, </TT><I>a</I><TT>)</TT> is filled with the values returned by the
successive calls to <I>f</I>. (This function must not be used to build
an array of floating-point numbers.)
<LI CLASS="li-itemize"><TT>caml_copy_string_array(</TT><I>p</I><TT>)</TT> allocates an array of strings, copied from
the pointer to a string array <I>p</I> (a <CODE>char **</CODE>). <I>p</I> must
be NULL-terminated.
</UL>

<H4 CLASS="subsubsection">Low-level interface</H4>
The following functions are slightly more efficient than <TT>caml_alloc</TT>, but
also much more difficult to use.<BR>
<BR>
From the standpoint of the allocation functions, blocks are divided
according to their size as zero-sized blocks, small blocks (with size
less than or equal to <CODE>Max_young_wosize</CODE>), and large blocks (with
size greater than <CODE>Max_young_wosize</CODE>). The constant
<CODE>Max_young_wosize</CODE> is declared in the include file <TT>mlvalues.h</TT>. It
is guaranteed to be at least 64 (words), so that any block with
constant size less than or equal to 64 can be assumed to be small. For
blocks whose size is computed at run-time, the size must be compared
against <CODE>Max_young_wosize</CODE> to determine the correct allocation procedure.
<UL CLASS="itemize"><LI CLASS="li-itemize">
<TT>caml_alloc_small(</TT><I>n</I><TT>, </TT><I>t</I><TT>)</TT> returns a fresh small block of size
<I>n</I> &#8804; <TT>Max_young_wosize</TT> words, with tag <I>t</I>. 
If this block is a structured block (i.e. if <I>t</I> &lt; <TT>No_scan_tag</TT>), then 
the fields of the block (initially containing garbage) must be initialized
with legal values (using direct assignment to the fields of the block)
before the next allocation.
<LI CLASS="li-itemize"><TT>caml_alloc_shr(</TT><I>n</I><TT>, </TT><I>t</I><TT>)</TT> returns a fresh block of size
<I>n</I>, with tag <I>t</I>. 
The size of the block can be greater than <CODE>Max_young_wosize</CODE>. (It
can also be smaller, but in this case it is more efficient to call
<TT>caml_alloc_small</TT> instead of <TT>caml_alloc_shr</TT>.) 
If this block is a structured block (i.e. if <I>t</I> &lt; <TT>No_scan_tag</TT>), then 
the fields of the block (initially containing garbage) must be initialized
with legal values (using the <TT>initialize</TT> function described below)
before the next allocation.
</UL>

<H3 CLASS="subsection"><A NAME="htoc228">18.4.5</A>&nbsp;&nbsp;Raising exceptions</H3> <A NAME="s:c-exceptions"></A>
Two functions are provided to raise two standard exceptions:
<UL CLASS="itemize"><LI CLASS="li-itemize">
<TT>caml_failwith(</TT><I>s</I><TT>)</TT>, where <I>s</I> is a null-terminated C string (with
type <CODE>char *</CODE>), raises exception <TT>Failure</TT> with argument <I>s</I>.
<LI CLASS="li-itemize"><TT>caml_invalid_argument(</TT><I>s</I><TT>)</TT>, where <I>s</I> is a null-terminated C
string (with type <CODE>char *</CODE>), raises exception <TT>Invalid_argument</TT>
with argument <I>s</I>.
</UL>
Raising arbitrary exceptions from C is more delicate: the
exception identifier is dynamically allocated by the Caml program, and
therefore must be communicated to the C function using the
registration facility described below in section&nbsp;<A HREF="#s:register-exn">18.7.3</A>.
Once the exception identifier is recovered in C, the following
functions actually raise the exception:
<UL CLASS="itemize"><LI CLASS="li-itemize">
<TT>caml_raise_constant(</TT><I>id</I><TT>)</TT> raises the exception <I>id</I> with
no argument;
<LI CLASS="li-itemize"><TT>caml_raise_with_arg(</TT><I>id</I><TT>, </TT><I>v</I><TT>)</TT> raises the exception
<I>id</I> with the Caml value <I>v</I> as argument;
<LI CLASS="li-itemize"><TT>caml_raise_with_string(</TT><I>id</I><TT>, </TT><I>s</I><TT>)</TT>, where <I>s</I> is a
null-terminated C string, raises the exception <I>id</I> with a copy of
the C string <I>s</I> as argument.
</UL>

<H2 CLASS="section"><A NAME="htoc229">18.5</A>&nbsp;&nbsp;Living in harmony with the garbage collector</H2>

Unused blocks in the heap are automatically reclaimed by the garbage
collector. This requires some cooperation from C code that
manipulates heap-allocated blocks.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc230">18.5.1</A>&nbsp;&nbsp;Simple interface</H3>
All the macros described in this section are declared in the
<TT>memory.h</TT> header file.<BR>
<BR>
<DIV CLASS="flushleft"><B>Rule&nbsp;1</B>&nbsp;&nbsp;<EM>
A function that has parameters or local variables of type <TT>value</TT> must
begin with a call to one of the <TT>CAMLparam</TT> macros and return with
<TT>CAMLreturn</TT> or <TT>CAMLreturn0</TT>.
</EM></DIV><BR>
<BR>
There are six <TT>CAMLparam</TT> macros: <TT>CAMLparam0</TT> to <TT>CAMLparam5</TT>, which
take zero to five arguments respectively. If your function has fewer
than 5 parameters of type <TT>value</TT>, use the corresponding macros
with these parameters as arguments. If your function has more than 5
parameters of type <TT>value</TT>, use <TT>CAMLparam5</TT> with five of these
parameters, and use one or more calls to the <TT>CAMLxparam</TT> macros for
the remaining parameters (<TT>CAMLxparam1</TT> to <TT>CAMLxparam5</TT>).<BR>
<BR>
The macros <TT>CAMLreturn</TT> and <TT>CAMLreturn0</TT> are used to replace the C
keyword <TT>return</TT>. Every occurence of <TT>return x</TT> must be replaced by
<TT>CAMLreturn (x)</TT>, every occurence of <TT>return</TT> without argument must be
replaced by <TT>CAMLreturn0</TT>. If your C function is a procedure (i.e. if
it returns void), you must insert <TT>CAMLreturn0</TT> at the end (to replace
C's implicit <TT>return</TT>).<BR>
<BR>

<H5 CLASS="paragraph">Note:</H5> some C compilers give bogus warnings about unused
variables <TT>caml__dummy_xxx</TT> at each use of <TT>CAMLparam</TT> and
<TT>CAMLlocal</TT>. You should ignore them.<BR>
<BR>
 <BR>
<BR>
<BR>
Example:
<PRE CLASS="verbatim">
void foo (value v1, value v2, value v3)
{
  CAMLparam3 (v1, v2, v3);
  ...
  CAMLreturn0;
}
</PRE>

<H5 CLASS="paragraph">Note:</H5> if your function is a primitive with more than 5 arguments
for use with the byte-code runtime, its arguments are not <TT>value</TT>s and
must not be declared (they have types <TT>value *</TT> and <TT>int</TT>).<BR>
<BR>
<DIV CLASS="flushleft"><B>Rule&nbsp;2</B>&nbsp;&nbsp;<EM>
Local variables of type <TT>value</TT> must be declared with one of the
<TT>CAMLlocal</TT> macros. Arrays of <TT>value</TT>s are declared with
<TT>CAMLlocalN</TT>.
<div style="background-color:yellow; color:red; border-style:none; border-width:0.5pt">
These macros must be used at the beginning of the
function, not in a nested block.
</div>
</EM></DIV><BR>
<BR>
The macros <TT>CAMLlocal1</TT> to <TT>CAMLlocal5</TT> declare and initialize one to
five local variables of type <TT>value</TT>. The variable names are given as
arguments to the macros. <TT>CAMLlocalN(</TT><I>x</I><TT>, </TT><I>n</I><TT>)</TT> declares
and initializes a local variable of type <TT>value [</TT><I>n</I><TT>]</TT>. You can
use several calls to these macros if you have more than 5 local
variables.
<div style="background-color:yellow; color:red; border-style:none; border-width:0.5pt">
<STRIKE>You can also use them in nested C blocks within the
function.</STRIKE> (deleted)
</div>
<BR>
<BR>
Example:
<PRE CLASS="verbatim">
value bar (value v1, value v2, value v3)
{
  CAMLparam3 (v1, v2, v3);
  CAMLlocal1 (result);
  result = caml_alloc (3, 0);
  ...
  CAMLreturn (result);
}
</PRE><BR>
<BR>
<DIV CLASS="flushleft"><B>Rule&nbsp;3</B>&nbsp;&nbsp;<EM>
Assignments to the fields of structured blocks must be done with the
<TT>Store_field</TT> macro (for normal blocks) or <TT>Store_double_field</TT> macro
(for arrays and records of floating-point numbers). Other assignments
must not use <TT>Store_field</TT> nor <TT>Store_double_field</TT>.
</EM></DIV><BR>
<BR>
<TT>Store_field (</TT><I>b</I><TT>, </TT><I>n</I><TT>, </TT><I>v</I><TT>)</TT> stores the value
<I>v</I> in the field number <I>n</I> of value <I>b</I>, which must be a
block (i.e. <TT>Is_block(</TT><I>b</I><TT>)</TT> must be true).<BR>
<BR>
Example:
<PRE CLASS="verbatim">
value bar (value v1, value v2, value v3)
{
  CAMLparam3 (v1, v2, v3);
  CAMLlocal1 (result);
  result = caml_alloc (3, 0);
  Store_field (result, 0, v1);
  Store_field (result, 1, v2);
  Store_field (result, 2, v3);
  CAMLreturn (result);
}
</PRE>

<H5 CLASS="paragraph">Warning:</H5> The first argument of <TT>Store_field</TT> and
<TT>Store_double_field</TT> must be a variable declared by <TT>CAMLparam*</TT> or
a parameter declared by <TT>CAMLlocal*</TT> to ensure that a garbage
collection triggered by the evaluation of the other arguments will not
invalidate the first argument after it is computed.<BR>
<BR>
<DIV CLASS="flushleft"><B>Rule&nbsp;4</B>&nbsp;&nbsp;<EM> Global variables containing values must be registered
with the garbage collector using the <TT>register_global_root</TT> function.
</EM></DIV><BR>
<BR>
Registration of a global variable <TT>v</TT> is achieved by calling
<TT>caml_register_global_root(&amp;v)</TT> just before a valid value is stored in <TT>v</TT>
for the first time. <BR>
<BR>
A registered global variable <TT>v</TT> can be un-registered by calling
<TT>caml_remove_global_root(&amp;v)</TT>.<BR>
<BR>
<B>Note:</B> The <TT>CAML</TT> macros use identifiers (local variables, type
identifiers, structure tags) that start with <TT>caml__</TT>. Do not use any
identifier starting with <TT>caml__</TT> in your programs.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc231">18.5.2</A>&nbsp;&nbsp;Low-level interface</H3>
We now give the GC rules corresponding to the low-level allocation
functions <TT>caml_alloc_small</TT> and <TT>caml_alloc_shr</TT>. You can ignore those rules
if you stick to the simplified allocation function <TT>caml_alloc</TT>.<BR>
<BR>
<DIV CLASS="flushleft"><B>Rule&nbsp;5</B>&nbsp;&nbsp;<EM> After a structured block (a block with tag less than
<TT>No_scan_tag</TT>) is allocated with the low-level functions, all fields
of this block must be filled with well-formed values before the next
allocation operation. If the block has been allocated with
<TT>caml_alloc_small</TT>, filling is performed by direct assignment to the fields
of the block:
</EM><PRE><EM>
        Field(<I>v</I>, <I>n</I>) = <I>v<SUB>n</SUB></I>;
</EM></PRE><EM>
If the block has been allocated with <TT>caml_alloc_shr</TT>, filling is performed
through the <TT>caml_initialize</TT> function:
</EM><PRE><EM>
        caml_initialize(&amp;Field(<I>v</I>, <I>n</I>), <I>v<SUB>n</SUB></I>);
</EM></PRE>
</DIV><BR>
<BR>
The next allocation can trigger a garbage collection. The garbage
collector assumes that all structured blocks contain well-formed
values. Newly created blocks contain random data, which generally do
not represent well-formed values.<BR>
<BR>
If you really need to allocate before the fields can receive their
final value, first initialize with a constant value (e.g.
<TT>Val_unit</TT>), then allocate, then modify the fields with the correct
value (see rule&nbsp;6).<BR>
<BR>
<DIV CLASS="flushleft"><B>Rule&nbsp;6</B>&nbsp;&nbsp;<EM> Direct assignment to a field of a block, as in
</EM><PRE><EM>
        Field(<I>v</I>, <I>n</I>) = <I>w</I>;
</EM></PRE><EM>
is safe only if <I>v</I> is a block newly allocated by <TT>caml_alloc_small</TT>;
that is, if no allocation took place between the 
allocation of <I>v</I> and the assignment to the field. In all other cases,
never assign directly. If the block has just been allocated by <TT>caml_alloc_shr</TT>,
use <TT>caml_initialize</TT> to assign a value to a field for the first time:
</EM><PRE><EM>
        caml_initialize(&amp;Field(<I>v</I>, <I>n</I>), <I>w</I>);
</EM></PRE><EM>
Otherwise, you are updating a field that previously contained a
well-formed value; then, call the <TT>caml_modify</TT> function:
</EM><PRE><EM>
        caml_modify(&amp;Field(<I>v</I>, <I>n</I>), <I>w</I>);
</EM></PRE>
</DIV><BR>
<BR>
To illustrate the rules above, here is a C function that builds and
returns a list containing the two integers given as parameters.
First, we write it using the simplified allocation functions:
<PRE CLASS="verbatim">
value alloc_list_int(int i1, int i2)
{
  CAMLparam0 ();
  CAMLlocal2 (result, r);

  r = caml_alloc(2, 0);                   /* Allocate a cons cell */
  Store_field(r, 0, Val_int(i2));         /* car = the integer i2 */
  Store_field(r, 1, Val_int(0));          /* cdr = the empty list [] */
  result = caml_alloc(2, 0);              /* Allocate the other cons cell */
  Store_field(result, 0, Val_int(i1));    /* car = the integer i1 */
  Store_field(result, 1, r);              /* cdr = the first cons cell */
  CAMLreturn (result);
}
</PRE>Here, the registering of <TT>result</TT> is not strictly needed, because no
allocation takes place after it gets its value, but it's easier and
safer to simply register all the local variables that have type <TT>value</TT>.<BR>
<BR>
Here is the same function written using the low-level allocation
functions. We notice that the cons cells are small blocks and can be
allocated with <TT>caml_alloc_small</TT>, and filled by direct assignments on
their fields.
<PRE CLASS="verbatim">
value alloc_list_int(int i1, int i2)
{
  CAMLparam0 ();
  CAMLlocal2 (result, r);

  r = caml_alloc_small(2, 0);                  /* Allocate a cons cell */
  Field(r, 0) = Val_int(i2);              /* car = the integer i2 */
  Field(r, 1) = Val_int(0);               /* cdr = the empty list [] */
  result = caml_alloc_small(2, 0);        /* Allocate the other cons cell */
  Field(result, 0) = Val_int(i1);         /* car = the integer i1 */
  Field(result, 1) = r;                   /* cdr = the first cons cell */
  CAMLreturn (result);
}
</PRE>In the two examples above, the list is built bottom-up. Here is an
alternate way, that proceeds top-down. It is less efficient, but
illustrates the use of <TT>modify</TT>.
<PRE CLASS="verbatim">
value alloc_list_int(int i1, int i2)
{
  CAMLparam0 ();
  CAMLlocal2 (tail, r);

  r = caml_alloc_small(2, 0);             /* Allocate a cons cell */
  Field(r, 0) = Val_int(i1);              /* car = the integer i1 */
  Field(r, 1) = Val_int(0);               /* A dummy value
  tail = caml_alloc_small(2, 0);          /* Allocate the other cons cell */
  Field(tail, 0) = Val_int(i2);           /* car = the integer i2 */
  Field(tail, 1) = Val_int(0);            /* cdr = the empty list [] */
  caml_modify(&amp;Field(r, 1), tail);        /* cdr of the result = tail */
  CAMLreturn (r);
}
</PRE>It would be incorrect to perform
<TT>Field(r, 1) = tail</TT> directly, because the allocation of <TT>tail</TT>
has taken place since <TT>r</TT> was allocated.<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc232">18.6</A>&nbsp;&nbsp;A complete example</H2>

This section outlines how the functions from the Unix <TT>curses</TT> library
can be made available to Objective Caml programs. First of all, here is
the interface <TT>curses.mli</TT> that declares the <TT>curses</TT> primitives and
data types:
<PRE CLASS="verbatim">
type window                   (* The type "window" remains abstract *)
external initscr: unit -&gt; window = "curses_initscr"
external endwin: unit -&gt; unit = "curses_endwin"
external refresh: unit -&gt; unit = "curses_refresh"
external wrefresh : window -&gt; unit = "curses_wrefresh"
external newwin: int -&gt; int -&gt; int -&gt; int -&gt; window = "curses_newwin"
external addch: char -&gt; unit = "curses_addch"
external mvwaddch: window -&gt; int -&gt; int -&gt; char -&gt; unit = "curses_mvwaddch"
external addstr: string -&gt; unit = "curses_addstr"
external mvwaddstr: window -&gt; int -&gt; int -&gt; string -&gt; unit = "curses_mvwaddstr"
(* lots more omitted *)
</PRE>To compile this interface:
<PRE CLASS="verbatim">
        ocamlc -c curses.mli
</PRE>
To implement these functions, we just have to provide the stub code;
the core functions are already implemented in the <TT>curses</TT> library.
The stub code file, <TT>curses_stubs.c</TT>, looks like this:
<PRE CLASS="verbatim">
#include &lt;curses.h&gt;
<span style="background-color:yellow; color:red">#include &lt;caml/mlvalues.h&gt;
#include &lt;caml/memory.h&gt;
#include &lt;caml/alloc.h&gt;
#include &lt;caml/custom.h&gt;

/* Encapsulation of opaque window handles (of type WINDOW *)
   as Caml custom blocks. */

static struct custom_operations curses_window_ops = {
  "fr.inria.caml.curses_windows",
  custom_finalize_default,
  custom_compare_default,
  custom_hash_default,
  custom_serialize_default,
  custom_deserialize_default
};

/* Accessing the WINDOW * part of a Caml custom block */
#define Window_val(v) (*((WINDOW **) Data_custom_val(v)))

/* Allocating a Caml custom block to hold the given WINDOW * */
static value alloc_window(WINDOW * w)
{
  value v = alloc_custom(&amp;curses_window_ops, sizeof(WINDOW *), 0, 1);
  Window_val(v) = w;
  return v;
}</span>

value caml_curses_initscr(value unit)
{
  CAMLparam1 (unit);
  CAMLreturn (<span style="background-color:yellow; color:red">alloc_window</span>(initscr()));
}

<span style="background-color:yellow; color:red">value caml_curses_endwin(value unit)
{
  CAMLparam1 (unit);
  endwin();
  CAMLreturn (Val_unit);
}

value caml_curses_refresh(value unit)
{
  CAMLparam1 (unit);
  refresh();
  CAMLreturn (Val_unit);
}</span>

value caml_curses_wrefresh(value win)
{
  CAMLparam1 (win);
  wrefresh(<span style="background-color:yellow; color:red">Window_val</span>(win));
  CAMLreturn (Val_unit);
}

value caml_curses_newwin(value nlines, value ncols, value x0, value y0)
{
  CAMLparam4 (nlines, ncols, x0, y0);
  CAMLreturn (<span style="background-color:yellow; color:red">alloc_window</span>(newwin(Int_val(nlines), Int_val(ncols),
                                  Int_val(x0), Int_val(y0))));
}

value caml_curses_addch(value c)
{
  CAMLparam1 (c);
  addch(Int_val(c));            /* Characters are encoded like integers */
  CAMLreturn (Val_unit);
}

<span style="background-color:yellow; color:red">value caml_curses_mvwaddch(value win, value x, value y, value c)
{
  CAMLparam4 (win, x, y, c);
  mvwaddch(Window_val(win), Int_val(x), Int_val(y), Int_val(c));
  CAMLreturn (Val_unit);
}</span>

value caml_curses_addstr(value s)
{
  CAMLparam1 (s);
  addstr(String_val(s));
  CAMLreturn (Val_unit);
}

<span style="background-color:yellow; color:red">value caml_curses_mvwaddstr(value win, value x, value y, value s)
{
  CAMLparam4 (win, x, y, s);
  mvwaddstr(Window_val(win), Int_val(x), Int_val(y), String_val(s));
  CAMLreturn (Val_unit);
}</span>

/* This goes on for pages. */
</PRE>
The file <TT>curses_stubs.c</TT> can be compiled with:
<PRE CLASS="verbatim">
        cc -c -I/usr/local/lib/ocaml curses.c
</PRE>or, even simpler,
<PRE CLASS="verbatim">
        ocamlc -c curses.c
</PRE>(When passed a <TT>.c</TT> file, the <TT>ocamlc</TT> command simply calls the C
compiler on that file, with the right <TT>-I</TT> option.)<BR>
<BR>
Now, here is a sample Caml program <TT>test.ml</TT> that uses the <TT>curses</TT>
module:
<PRE CLASS="verbatim">
open Curses
let main_window = initscr () in
let small_window = newwin 10 5 20 10 in
  mvwaddstr main_window 10 2 "Hello";
  mvwaddstr small_window 4 3 "world";
  refresh();
  Unix.sleep 5;
  endwin()
</PRE>To compile and link this program, run:
<PRE CLASS="verbatim">
        ocamlc -custom -o test <span style="background-color:yellow; color:red">unix.cma</span> test.ml curses_stubs.o -cclib -lcurses
</PRE>(On some machines, you may need to put <TT>-cclib -ltermcap</TT> or
<TT>-cclib -lcurses -cclib -ltermcap</TT> instead of <TT>-cclib -lcurses</TT>.)<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc233">18.7</A>&nbsp;&nbsp;Advanced topic: callbacks from C to Caml</H2> <A NAME="s:callback"></A>

So far, we have described how to call C functions from Caml. In this
section, we show how C functions can call Caml functions, either as
callbacks (Caml calls C which calls Caml), or because the main program
is written in C.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc234">18.7.1</A>&nbsp;&nbsp;Applying Caml closures from C</H3> <A NAME="s:callbacks"></A>
C functions can apply Caml functional values (closures) to Caml values.
The following functions are provided to perform the applications:
<UL CLASS="itemize"><LI CLASS="li-itemize">
<TT>caml_callback(</TT><I>f, a</I><TT>)</TT> applies the functional value <I>f</I> to
the value <I>a</I> and return the value returned by&nbsp;<I>f</I>.
<LI CLASS="li-itemize"><TT>caml_callback2(</TT><I>f, a, b</I><TT>)</TT> applies the functional value <I>f</I>
(which is assumed to be a curried Caml function with two arguments) to
<I>a</I> and <I>b</I>.
<LI CLASS="li-itemize"><TT>caml_callback3(</TT><I>f, a, b, c</I><TT>)</TT> applies the functional value <I>f</I>
(a curried Caml function with three arguments) to <I>a</I>, <I>b</I> and <I>c</I>.
<LI CLASS="li-itemize"><TT>caml_callbackN(</TT><I>f, n, args</I><TT>)</TT> applies the functional value <I>f</I>
to the <I>n</I> arguments contained in the array of values <I>args</I>.
</UL>
If the function <I>f</I> does not return, but raises an exception that
escapes the scope of the application, then this exception is
propagated to the next enclosing Caml code, skipping over the C
code. That is, if a Caml function <I>f</I> calls a C function <I>g</I> that
calls back a Caml function <I>h</I> that raises a stray exception, then the
execution of <I>g</I> is interrupted and the exception is propagated back
into <I>f</I>.<BR>
<BR>
If the C code wishes to catch exceptions escaping the Caml function,
it can use the functions <TT>caml_callback_exn</TT>, <TT>caml_callback2_exn</TT>,
<TT>caml_callback3_exn</TT>, <TT>caml_callbackN_exn</TT>. These functions take the same
arguments as their non-<TT>_exn</TT> counterparts, but catch escaping
exceptions and return them to the C code. The return value <I>v</I> of the
<TT>caml_callback*_exn</TT> functions must be tested with the macro
<TT>Is_exception_result(</TT><I>v</I><TT>)</TT>. If the macro returns &#8220;false&#8221;, no
exception occured, and <I>v</I> is the value returned by the Caml
function. If <TT>Is_exception_result(</TT><I>v</I><TT>)</TT> returns &#8220;true&#8221;,
an exception escaped, and its value (the exception descriptor) can be
recovered using <TT>Extract_exception(</TT><I>v</I><TT>)</TT>.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc235">18.7.2</A>&nbsp;&nbsp;Registering Caml closures for use in C functions</H3>
The main difficulty with the <TT>callback</TT> functions described above is
obtaining a closure to the Caml function to be called. For this
purpose, Objective Caml provides a simple registration mechanism, by
which Caml code can register Caml functions under some global name,
and then C code can retrieve the corresponding closure by this global
name.<BR>
<BR>
On the Caml side, registration is performed by evaluating
<TT>Callback.register</TT> <I>n v</I>. Here, <I>n</I> is the global name
(an arbitrary string) and <I>v</I> the Caml value. For instance:
<PRE CLASS="verbatim">
    let f x = print_string "f is applied to "; print_int n; print_newline()
    let _ = Callback.register "test function" f
</PRE>
On the C side, a pointer to the value registered under name <I>n</I> is
obtained by calling <TT>caml_named_value(</TT><I>n</I><TT>)</TT>. The returned
pointer must then be dereferenced to recover the actual Caml value.
If no value is registered under the name <I>n</I>, the null pointer is
returned. For example, here is a C wrapper that calls the Caml function <TT>f</TT>
above:
<PRE CLASS="verbatim">
    void call_caml_f(int arg)
    {
        caml_callback(*caml_named_value("test function"), Val_int(arg));
    }
</PRE>
The pointer returned by <TT>caml_named_value</TT> is constant and can safely
be cached in a C variable to avoid repeated name lookups. On the other
hand, the value pointed to can change during garbage collection and
must always be recomputed at the point of use. Here is a more
efficient variant of <TT>call_caml_f</TT> above that calls <TT>caml_named_value</TT>
only once:
<PRE CLASS="verbatim">
    void call_caml_f(int arg)
    {
        static value * closure_f = NULL;
        if (closure_f == NULL) {
            /* First time around, look up by name */
            closure_f = caml_named_value("test function");
        }
        caml_callback(*closure_f, Val_int(arg));
    }
</PRE>

<H3 CLASS="subsection"><A NAME="htoc236">18.7.3</A>&nbsp;&nbsp;Registering Caml exceptions for use in C functions</H3> <A NAME="s:register-exn"></A>
The registration mechanism described above can also be used to
communicate exception identifiers from Caml to C. The Caml code
registers the exception by evaluating
<TT>Callback.register_exception</TT> <I>n exn</I>, where <I>n</I> is an
arbitrary name and <I>exn</I> is an exception value of the
exception to register. For example:
<PRE CLASS="verbatim">
    exception Error of string
    let _ = Callback.register_exception "test exception" (Error "any string")
</PRE>The C code can then recover the exception identifier using
<TT>caml_named_value</TT> and pass it as first argument to the functions
<TT>raise_constant</TT>, <TT>raise_with_arg</TT>, and <TT>raise_with_string</TT> (described
in section&nbsp;<A HREF="#s:c-exceptions">18.4.5</A>) to actually raise the exception. For
example, here is a C function that raises the <TT>Error</TT> exception with
the given argument:
<PRE CLASS="verbatim">
    void raise_error(char * msg)
    {
        caml_raise_with_string(*caml_named_value("test exception"), msg);
    }
</PRE>

<H3 CLASS="subsection"><A NAME="htoc237">18.7.4</A>&nbsp;&nbsp;Main program in C</H3> <A NAME="s:main-c"></A>
In normal operation, a mixed Caml/C program starts by executing the
Caml initialization code, which then may proceed to call C
functions. We say that the main program is the Caml code. In some
applications, it is desirable that the C code plays the role of the
main program, calling Caml functions when needed. This can be achieved as
follows:
<UL CLASS="itemize"><LI CLASS="li-itemize">
The C part of the program must provide a <TT>main</TT> function,
which will override the default <TT>main</TT> function provided by the Caml
runtime system. Execution will start in the user-defined <TT>main</TT> function
just like for a regular C program.<BR>
<BR>
<LI CLASS="li-itemize">At some point, the C code must call <TT>caml_main(argv)</TT> to
initialize the Caml code. The <TT>argv</TT> argument is a C array of strings
(type <TT>char **</TT>), terminated with a <TT>NULL</TT> pointer,
which represents the command-line arguments, as
passed as second argument to <TT>main</TT>. The Caml array <TT>Sys.argv</TT> will
be initialized from this parameter. For the bytecode compiler,
<TT>argv[0]</TT> and <TT>argv[1]</TT> are also consulted to find the file containing
the bytecode.<BR>
<BR>
<LI CLASS="li-itemize">The call to <TT>caml_main</TT> initializes the Caml runtime system,
loads the bytecode (in the case of the bytecode compiler), and
executes the initialization code of the Caml program. Typically, this
initialization code registers callback functions using <TT>Callback.register</TT>.
Once the Caml initialization code is complete, control returns to the
C code that called <TT>caml_main</TT>.<BR>
<BR>
<LI CLASS="li-itemize">The C code can then invoke Caml functions using the callback
mechanism (see section&nbsp;<A HREF="#s:callbacks">18.7.1</A>).
</UL>

<H3 CLASS="subsection"><A NAME="htoc238">18.7.5</A>&nbsp;&nbsp;Embedding the Caml code in the C code</H3> <A NAME="s:embedded-code"></A>
The bytecode compiler in custom runtime mode (<TT>ocamlc -custom</TT>)
normally appends the bytecode to the executable file containing the
custom runtime. This has two consequences. First, the final linking
step must be performed by <TT>ocamlc</TT>. Second, the Caml runtime library
must be able to find the name of the executable file from the
command-line arguments. When using <TT>caml_main(argv)</TT> as in
section&nbsp;<A HREF="#s:main-c">18.7.4</A>, this means that <TT>argv[0]</TT> or <TT>argv[1]</TT> must
contain the executable file name.<BR>
<BR>
An alternative is to embed the bytecode in the C code. The
<TT>-output-obj</TT> option to <TT>ocamlc</TT> is provided for this purpose.
It causes the <TT>ocamlc</TT> compiler to output a C object file (<TT>.o</TT> file)
containing the bytecode for the Caml part of the program, as well as a
<TT>caml_startup</TT> function. The C object file produced by <TT>ocamlc -output-obj</TT> can then be linked with C code using the standard C
compiler, or stored in a C library.<BR>
<BR>
The <TT>caml_startup</TT> function must be called from the main C program in
order to initialize the Caml runtime and execute the Caml
initialization code. Just like <TT>caml_main</TT>, it takes one <TT>argv</TT>
parameter containing the command-line parameters. Unlike <TT>caml_main</TT>,
this <TT>argv</TT> parameter is used only to initialize <TT>Sys.argv</TT>, but not
for finding the name of the executable file.<BR>
<BR>
The native-code compiler <TT>ocamlopt</TT> also supports the <TT>-output-obj</TT>
option, causing it to output a C object file containing the native
code for all Caml modules on the command-line, as well as the Caml
startup code. Initialization is performed by calling <TT>caml_startup</TT> as
in the case of the bytecode compiler.<BR>
<BR>
For the final linking phase, in addition to the object file produced
by <TT>-output-obj</TT>, you will have to provide the Objective Caml runtime
library (<TT>libcamlrun.a</TT> for bytecode, <TT>libasmrun.a</TT> for native-code),
as well as all C libraries that are required by the Caml libraries
used. For instance, assume the Caml part of your program uses the
Unix library. With <TT>ocamlc</TT>, you should do:
<PRE>
        ocamlc -output-obj -o camlcode.o unix.cma <I>other</I> .cmo <I>and</I> .cma <I>files</I>
        cc -o myprog <I>C objects and libraries</I> \
           camlcode.o -L/usr/local/lib/ocaml -lunix -lcamlrun
</PRE>
With <TT>ocamlopt</TT>, you should do:
<PRE>
        ocamlopt -output-obj -o camlcode.o unix.cmxa <I>other</I> .cmx <I>and</I> .cmxa <I>files</I>
        cc -o myprog <I>C objects and libraries</I> \
           camlcode.o -L/usr/local/lib/ocaml -lunix -lasmrun
</PRE>

<H5 CLASS="paragraph">Warning:</H5> On some ports, special options are required on the final
linking phase that links together the object file produced by the
<TT>-output-obj</TT> option and the remainder of the program. Those options
are shown in the configuration file <TT>config/Makefile</TT> generated during
compilation of Objective Caml, as the variables <TT>BYTECCLINKOPTS</TT>
(for object files produced by <TT>ocamlc -output-obj</TT>) and
<TT>NATIVECCLINKOPTS</TT> (for object files produced by <TT>ocamlopt -output-obj</TT>). Currently, the only ports that require special
attention are:
<UL CLASS="itemize"><LI CLASS="li-itemize">
Alpha under Digital Unix / Tru64 Unix with <TT>gcc</TT>:
object files produced by <TT>ocamlc -output-obj</TT> must be linked with the
<TT>gcc</TT> options <TT>-Wl,-T,12000000 -Wl,-D,14000000</TT>.
This is not necessary for object files produced by <TT>ocamlopt -output-obj</TT>.
<LI CLASS="li-itemize">Windows NT: the object file produced by Objective Caml have been
compiled with the <TT>/MT</TT> flag, and therefore all other object files
linked with it should also be compiled with <TT>/MT</TT>.
</UL>

<H2 CLASS="section"><A NAME="htoc239">18.8</A>&nbsp;&nbsp;Advanced example with callbacks</H2>

This section illustrates the callback facilities described in
section&nbsp;<A HREF="#s:callback">18.7</A>. We are going to package some Caml functions
in such a way that they can be linked with C code and called from C
just like any C functions. The Caml functions are defined in the
following <TT>mod.ml</TT> Caml source:
<PRE CLASS="verbatim">
(* File mod.ml -- some ``useful'' Caml functions *)

let rec fib n = if n &lt; 2 then 1 else fib(n-1) + fib(n-2)

let format_result n = Printf.sprintf "Result is: %d\n" n

(* Export those two functions to C *)

let _ = Callback.register "fib" fib
let _ = Callback.register "format_result" format_result
</PRE>
Here is the C stub code for calling these functions from C:
<PRE CLASS="verbatim">
/* File modwrap.c -- wrappers around the Caml functions */

#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;caml/mlvalues.h&gt;
#include &lt;caml/callback.h&gt;

int fib(int n)
{
  static value * fib_closure = NULL;
  if (fib_closure == NULL) fib_closure = caml_named_value("fib");
  return Int_val(caml_callback(*fib_closure, Val_int(n)));
}

char * format_result(int n)
{
  static value * format_result_closure = NULL;
  if (format_result_closure == NULL)
    format_result_closure = caml_named_value("format_result");
  return strdup(String_val(caml_callback(*format_result_closure, Val_int(n))));
  /* We copy the C string returned by String_val to the C heap
     so that it remains valid after garbage collection. */
}
</PRE>
We now compile the Caml code to a C object file and put it in a C
library along with the stub code in <TT>modwrap.c</TT> and the Caml runtime system:
<PRE CLASS="verbatim">
        ocamlc -custom -output-obj -o modcaml.o mod.ml
        ocamlc -c modwrap.c
        cp /usr/local/lib/ocaml/libcamlrun.a mod.a
        ar r mod.a modcaml.o modwrap.o
</PRE>(One can also use <TT>ocamlopt -output-obj</TT> instead of <TT>ocamlc -custom -output-obj</TT>. In this case, replace <TT>libcamlrun.a</TT> (the bytecode
runtime library) by <TT>libasmrun.a</TT> (the native-code runtime library).)<BR>
<BR>
Now, we can use the two functions <TT>fib</TT> and <TT>format_result</TT> in any C
program, just like regular C functions. Just remember to call
<TT>caml_startup</TT> once before.
<PRE CLASS="verbatim">
/* File main.c -- a sample client for the Caml functions */

#include &lt;stdio.h&gt;

int main(int argc, char ** argv)
{
  int result;

  /* Initialize Caml code */
  caml_startup(argv);
  /* Do some computation */
  result = fib(10);
  printf("fib(10) = %s\n", format_result(result));
  return 0;
}
</PRE>
To build the whole program, just invoke the C compiler as follows:
<PRE CLASS="verbatim">
        cc -o prog main.c mod.a -lcurses
</PRE>(On some machines, you may need to put <TT>-ltermcap</TT> or
<TT>-lcurses -ltermcap</TT> instead of <TT>-lcurses</TT>.)<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc240">18.9</A>&nbsp;&nbsp;Advanced topic: custom blocks</H2> <A NAME="s:custom"></A>

Blocks with tag <TT>Custom_tag</TT> contain both arbitrary user data and a
pointer to a C struct, with type <TT>struct custom_operations</TT>, that
associates user-provided finalization, comparison, hashing,
serialization and deserialization functions to this block.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc241">18.9.1</A>&nbsp;&nbsp;The <TT>struct custom_operations</TT></H3>
The <TT>struct custom_operations</TT> is defined in <TT>&lt;caml/custom.h&gt;</TT> and
contains the following fields:
<UL CLASS="itemize"><LI CLASS="li-itemize">
<TT>char *identifier</TT><BR>
A zero-terminated character string serving as an identifier for
serialization and deserialization operations.<BR>
<BR>
<LI CLASS="li-itemize"><TT>void  (*finalize)(value v)</TT><BR>
The <TT>finalize</TT> field contains a pointer to a C function that is called
when the block becomes unreachable and is about to be reclaimed.
The block is passed as first argument to the function.
The <TT>finalize</TT> field can also be
<div style="background-color:yellow; color:red; border-style:none; border-width:0.5pt">
<STRIKE>NULL</STRIKE>
<TT>custom_finalize_default</TT>
</div>
to indicate that no
finalization function is associated with the block.
Important note: the <TT>v</TT> parameter of this function is of type <TT>value</TT>, but
it must not be declared using the <TT>CAMLparam</TT> macros.<BR>
<BR>
<LI CLASS="li-itemize"><TT>int (*compare)(value v1, value v2)</TT><BR>
The <TT>compare</TT> field contains a pointer to a C function that is
called whenever two custom blocks are compared using Caml's generic
comparison operators (<TT>=</TT>, <TT>&lt;&gt;</TT>, <TT>&lt;=</TT>, <TT>&gt;=</TT>, <TT>&lt;</TT>, <TT>&gt;</TT> and
<TT>compare</TT>). The C function should return 0 if the data contained in
the two blocks are structurally equal, a negative integer if the data
from the first block is less than the data from the second block, and
a positive integer if the data from the first block is greater than
the data from the second block.
Note: You must use <TT>CAMLparam</TT> to declare <TT>v1</TT> and <TT>v2</TT> and <TT>CAMLreturn</TT>
to return the result.<BR>
<BR>
The <TT>compare</TT> field can be set to <TT>custom_compare_default</TT>; this
default comparison function simply raises <TT>Failure</TT>.<BR>
<BR>
<LI CLASS="li-itemize"><TT>long (*hash)(value v)</TT><BR>
The <TT>hash</TT> field contains a pointer to a C function that is called
whenever Caml's generic hash operator (see module <TT>Hashtbl</TT>) is
applied to a custom block. The C function can return an arbitrary
long integer representing the hash value of the data contained in the
given custom block. The hash value must be compatible with the
<TT>compare</TT> function, in the sense that two structurally equal data
(that is, two custom blocks for which <TT>compare</TT> returns 0) must have
the same hash value.
Note: You must use <TT>CAMLparam</TT> to declare <TT>v</TT> and <TT>CAMLreturn</TT>
to return the result.<BR>
<BR>
The <TT>hash</TT> field can be set to <TT>custom_hash_default</TT>, in which case
the custom block is ignored during hash computation.<BR>
<BR>
<LI CLASS="li-itemize"><TT>void (*serialize)(value v, unsigned long * wsize_32, unsigned long * wsize_64)</TT><BR>
The <TT>serialize</TT> field contains a pointer to a C function that is
called whenever the custom block needs to be serialized (marshaled)
using the Caml functions <TT>output_value</TT> or <TT>Marshal.to_...</TT>.
For a custom block, those functions first write the identifier of the
block (as given by the <TT>identifier</TT> field) to the output stream,
then call the user-provided <TT>serialize</TT> function. That function is
responsible for writing the data contained in the custom block, using
the <TT>serialize_...</TT> functions defined in <TT>&lt;caml/intext.h&gt;</TT> and listed
below. The user-provided <TT>serialize</TT> function must then store in its
<TT>wsize_32</TT> and <TT>wsize_64</TT> parameters the sizes in bytes of the data
part of the custom block on a 32-bit architecture and on a 64-bit
architecture, respectively.
Note: You must use <TT>CAMLparam</TT> to declare <TT>v</TT> and <TT>CAMLreturn</TT>
to return the result.<BR>
<BR>
The <TT>serialize</TT> field can be set to <TT>custom_serialize_default</TT>,
in which case the <TT>Failure</TT> exception is raised when attempting to
serialize the custom block.<BR>
<BR>
<LI CLASS="li-itemize"><TT>unsigned long (*deserialize)(void * dst)</TT><BR>
The <TT>deserialize</TT> field contains a pointer to a C function that is
called whenever a custom block with identifier <TT>identifier</TT> needs to
be deserialized (un-marshaled) using the Caml functions <TT>input_value</TT>
or <TT>Marshal.from_...</TT>. This user-provided function is responsible for
reading back the data written by the <TT>serialize</TT> operation, using the
<TT>deserialize_...</TT> functions defined in <TT>&lt;caml/intext.h&gt;</TT> and listed
below. It must then rebuild the data part of the custom block
and store it at the pointer given as the <TT>dst</TT> argument. Finally, it
returns the size in bytes of the data part of the custom block.
This size must be identical to the <TT>wsize_32</TT> result of
the <TT>serialize</TT> operation if the architecture is 32 bits, or
<TT>wsize_64</TT> if the architecture is 64 bits.<BR>
<BR>
The <TT>deserialize</TT> field can be set to <TT>custom_deserialize_default</TT>
to indicate that deserialization is not supported. In this case,
do not register the <TT>struct custom_operations</TT> with the deserializer
using <TT>register_custom_operations</TT> (see below).
</UL>

<H3 CLASS="subsection"><A NAME="htoc242">18.9.2</A>&nbsp;&nbsp;Allocating custom blocks</H3>
Custom blocks must be allocated via the <TT>caml_alloc_custom</TT> function.
<TT>caml_alloc_custom(</TT><I>ops</I><TT>, </TT><I>size</I><TT>, </TT><I>used</I><TT>, </TT><I>max</I><TT>)</TT>
returns a fresh custom block, with room for <I>size</I> bytes of user
data, and whose associated operations are given by <I>ops</I> (a
pointer to a <TT>struct custom_operations</TT>, usually statically allocated
as a C global variable). <BR>
<BR>
The two parameters <I>used</I> and <I>max</I> are used to control the
speed of garbage collection when the finalized object contains
pointers to out-of-heap resources. Generally speaking, the
Caml incremental major collector adjusts its speed relative to the
allocation rate of the program. The faster the program allocates, the
harder the GC works in order to reclaim quickly unreachable blocks
and avoid having large amount of &#8220;floating garbage&#8221; (unreferenced
objects that the GC has not yet collected).<BR>
<BR>
Normally, the allocation rate is measured by counting the in-heap size
of allocated blocks. However, it often happens that finalized
objects contain pointers to out-of-heap memory blocks and other resources
(such as file descriptors, X Windows bitmaps, etc.). For those
blocks, the in-heap size of blocks is not a good measure of the
quantity of resources allocated by the program.<BR>
<BR>
The two arguments <I>used</I> and <I>max</I> give the GC an idea of how
much out-of-heap resources are consumed by the finalized block
being allocated: you give the amount of resources allocated to this
object as parameter <I>used</I>, and the maximum amount that you want
to see in floating garbage as parameter <I>max</I>. The units are
arbitrary: the GC cares only about the ratio <I>used</I> / <I>max</I>.<BR>
<BR>
For instance, if you are allocating a finalized block holding an X
Windows bitmap of <I>w</I> by <I>h</I> pixels, and you'd rather not
have more than 1 mega-pixels of unreclaimed bitmaps, specify
<I>used</I> = <I>w</I> * <I>h</I> and <I>max</I> = 1000000.<BR>
<BR>
Another way to describe the effect of the <I>used</I> and <I>max</I>
parameters is in terms of full GC cycles. If you allocate many custom
blocks with <I>used</I> / <I>max</I> = 1 / <I>N</I>, the GC will then do one
full cycle (examining every object in the heap and calling
finalization functions on those that are unreachable) every <I>N</I>
allocations. For instance, if <I>used</I> = 1 and <I>max</I> = 1000,
the GC will do one full cycle at least every 1000 allocations of
custom blocks.<BR>
<BR>
If your finalized blocks contain no pointers to out-of-heap resources,
or if the previous discussion made little sense to you, just take
<I>used</I> = 0 and <I>max</I> = 1. But if you later find that the
finalization functions are not called &#8220;often enough&#8221;, consider
increasing the <I>used</I> / <I>max</I> ratio.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc243">18.9.3</A>&nbsp;&nbsp;Accessing custom blocks</H3>
The data part of a custom block <I>v</I> can be
accessed via the pointer <TT>Data_custom_val(</TT><I>v</I><TT>)</TT>. This pointer
has type <TT>void *</TT> and should be cast to the actual type of the data
stored in the custom block.<BR>
<BR>
The contents of custom blocks are not scanned by the garbage
collector, and must therefore not contain any pointer inside the Caml
heap. In other terms, never store a Caml <TT>value</TT> in a custom block,
and do not use <TT>Field</TT>, <TT>Store_field</TT> nor <TT>modify</TT> to access the data
part of a custom block. Conversely, any C data structure (not
containing heap pointers) can be stored in a custom block.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc244">18.9.4</A>&nbsp;&nbsp;Writing custom serialization and deserialization functions</H3>
The following functions, defined in <TT>&lt;caml/intext.h&gt;</TT>, are provided to
write and read back the contents of custom blocks in a portable way.
Those functions handle endianness conversions when e.g. data is
written on a little-endian machine and read back on a big-endian machine.<BR>
<BR>
<DIV CLASS="center"><TABLE BORDER=1 CELLSPACING=0 CELLPADDING=1 WIDTH="80%">
<TR><TD ALIGN=center NOWRAP><B>Function</B></TD>
<TD ALIGN=center NOWRAP><B>Action</B></TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP>
<TT>caml_serialize_int_1</TT></TD>
<TD VALIGN=top ALIGN=left>Write a 1-byte integer</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_serialize_int_2</TT></TD>
<TD VALIGN=top ALIGN=left>Write a 2-byte integer</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_serialize_int_4</TT></TD>
<TD VALIGN=top ALIGN=left>Write a 4-byte integer</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_serialize_int_8</TT></TD>
<TD VALIGN=top ALIGN=left>Write a 8-byte integer</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_serialize_float_4</TT></TD>
<TD VALIGN=top ALIGN=left>Write a 4-byte float</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_serialize_float_8</TT></TD>
<TD VALIGN=top ALIGN=left>Write a 8-byte float</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_serialize_block_1</TT></TD>
<TD VALIGN=top ALIGN=left>Write an array of 1-byte quantities</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_serialize_block_2</TT></TD>
<TD VALIGN=top ALIGN=left>Write an array of 2-byte quantities</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_serialize_block_4</TT></TD>
<TD VALIGN=top ALIGN=left>Write an array of 4-byte quantities</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_serialize_block_8</TT></TD>
<TD VALIGN=top ALIGN=left>Write an array of 8-byte quantities</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_uint_1</TT></TD>
<TD VALIGN=top ALIGN=left>Read an unsigned 1-byte integer</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_sint_1</TT></TD>
<TD VALIGN=top ALIGN=left>Read a signed 1-byte integer</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_uint_2</TT></TD>
<TD VALIGN=top ALIGN=left>Read an unsigned 2-byte integer</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_sint_2</TT></TD>
<TD VALIGN=top ALIGN=left>Read a signed 2-byte integer</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_uint_4</TT></TD>
<TD VALIGN=top ALIGN=left>Read an unsigned 4-byte integer</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_sint_4</TT></TD>
<TD VALIGN=top ALIGN=left>Read a signed 4-byte integer</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_uint_8</TT></TD>
<TD VALIGN=top ALIGN=left>Read an unsigned 8-byte integer</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_sint_8</TT></TD>
<TD VALIGN=top ALIGN=left>Read a signed 8-byte integer</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_float_4</TT></TD>
<TD VALIGN=top ALIGN=left>Read a 4-byte float</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_float_8</TT></TD>
<TD VALIGN=top ALIGN=left>Read an 8-byte float</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_block_1</TT></TD>
<TD VALIGN=top ALIGN=left>Read an array of 1-byte quantities</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_block_2</TT></TD>
<TD VALIGN=top ALIGN=left>Read an array of 2-byte quantities</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_block_4</TT></TD>
<TD VALIGN=top ALIGN=left>Read an array of 4-byte quantities</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_block_8</TT></TD>
<TD VALIGN=top ALIGN=left>Read an array of 8-byte quantities</TD>
</TR>
<TR><TD VALIGN=top ALIGN=left NOWRAP><TT>caml_deserialize_error</TT></TD>
<TD VALIGN=top ALIGN=left>Signal an error during deserialization;
<TT>input_value</TT> or <TT>Marshal.from_...</TT> raise a <TT>Failure</TT> exception after
cleaning up their internal data structures</TD>
</TR></TABLE></DIV><BR>
<BR>
Serialization functions are attached to the custom blocks to which
they apply. Obviously, deserialization functions cannot be attached
this way, since the custom block does not exist yet when
deserialization begins! Thus, the <TT>struct custom_operations</TT> that
contain deserialization functions must be registered with the
deserializer in advance, using the <TT>register_custom_operations</TT>
function declared in <TT>&lt;caml/custom.h&gt;</TT>. Deserialization proceeds by
reading the identifier off the input stream, allocating a custom block
of the size specified in the input stream, searching the registered
<TT>struct custom_operation</TT> blocks for one with the same identifier, and
calling its <TT>deserialize</TT> function to fill the data part of the custom block.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc245">18.9.5</A>&nbsp;&nbsp;Choosing identifiers</H3>
Identifiers in <TT>struct custom_operations</TT> must be chosen carefully,
since they must identify uniquely the data structure for serialization
and deserialization operations. In particular, consider including a
version number in the identifier; this way, the format of the data can
be changed later, yet backward-compatible deserialisation functions
can be provided.<BR>
<BR>
Identifiers starting with <TT>_</TT> (an underscore character) are reserved
for the Objective Caml runtime system; do not use them for your custom
data. We recommend to use a URL
(<TT>http://mymachine.mydomain.com/mylibrary/version-number</TT>)
or a Java-style package name
(<TT>com.mydomain.mymachine.mylibrary.version-number</TT>)
as identifiers, to minimize the risk of identifier collision.<BR>
<BR>

<H3 CLASS="subsection"><A NAME="htoc246">18.9.6</A>&nbsp;&nbsp;Finalized blocks</H3>
Custom blocks generalize the finalized blocks that were present in
Objective Caml prior to version 3.00. For backward compatibility, the
format of custom blocks is compatible with that of finalized blocks,
and the <TT>alloc_final</TT> function is still available to allocate a custom
block with a given finalization function, but default comparison,
hashing and serialization functions. <TT>caml_alloc_final(</TT><I>n</I><TT>, </TT><I>f</I><TT>, </TT><I>used</I><TT>, </TT><I>max</I><TT>)</TT> returns a fresh custom block of
size <I>n</I> words, with finalization function <I>f</I>. The first
word is reserved for storing the custom operations; the other
<I>n</I>-1 words are available for your data. The two parameters
<I>used</I> and <I>max</I> are used to control the speed of garbage
collection, as described for <TT>caml_alloc_custom</TT>.<BR>
<BR>

<H2 CLASS="section"><A NAME="htoc247">18.10</A>&nbsp;&nbsp;Building mixed C/Caml libraries: <TT>ocamlmklib</TT></H2> <A NAME="s-ocamlmklib"></A>
The <TT>ocamlmklib</TT> command facilitates the construction of libraries
containing both Caml code and C code, and usable both in static
linking and dynamic linking modes.<BR>
<BR>

&nbsp;&nbsp;<FONT COLOR=purple>Windows:</FONT>
<BLOCKQUOTE CLASS="quote"> This command is available only under Cygwin, but not for the
native Win32 port.
</BLOCKQUOTE>
The <TT>ocamlmklib</TT> command takes three kinds of arguments:
<UL CLASS="itemize"><LI CLASS="li-itemize">
Caml source files and object files (<TT>.cmo</TT>, <TT>.cmx</TT>, <TT>.ml</TT>)
comprising the Caml part of the library;
<LI CLASS="li-itemize">C object files (<TT>.o</TT>, <TT>.a</TT>) comprising the C part of the
library;
<LI CLASS="li-itemize">Support libraries for the C part (<TT>-l</TT><I>lib</I>).
</UL>
It generates the following outputs:
<UL CLASS="itemize"><LI CLASS="li-itemize">
A Caml bytecode library <TT>.cma</TT> incorporating the <TT>.cmo</TT> and
<TT>.ml</TT> Caml files given as arguments, and automatically referencing the
C library generated with the C object files.
<LI CLASS="li-itemize">A Caml native-code library <TT>.cmxa</TT> incorporating the <TT>.cmx</TT> and
<TT>.ml</TT> Caml files given as arguments, and automatically referencing the
C library generated with the C object files.
<LI CLASS="li-itemize">If dynamic linking is supported on the target platform, a
<TT>.so</TT> shared library built from the C object files given as arguments,
and automatically referencing the support libraries.
<LI CLASS="li-itemize">A C static library <TT>.a</TT> built from the C object files.
</UL>
In addition, the following options are recognized:
<DL CLASS="description" COMPACT=compact><DT CLASS="dt-description">
<B><TT>-cclib</TT>, <TT>-ccopt</TT>, <TT>-I</TT>, <TT>-linkall</TT></B><DD CLASS="dd-description">
These options are passed as is to <TT>ocamlc</TT> or <TT>ocamlopt</TT>.
See the documentation of these commands.
<DT CLASS="dt-description"><B><TT>-pthread</TT>, <TT>-rpath</TT>, <TT>-R</TT>, <TT>-Wl,-rpath</TT>, <TT>-Wl,-R</TT></B><DD CLASS="dd-description">
These options are passed as is to the C compiler. Refer to the
documentation of the C compiler.
<DT CLASS="dt-description"><TT><B>-custom</B></TT><DD CLASS="dd-description"> Force the construction of a statically linked library
only, even if dynamic linking is supported.
<DT CLASS="dt-description"><TT><B>-failsafe</B></TT><DD CLASS="dd-description"> Fall back to building a statically linked library
if a problem occurs while building the shared library (e.g. some of
the support libraries are not available as shared libraries).
<DT CLASS="dt-description"><B><TT>-L</TT><I>dir</I></B><DD CLASS="dd-description"> Add <I>dir</I> to the search path for support
libraries (<TT>-l</TT><I>lib</I>).
<DT CLASS="dt-description"><B><TT>-ocamlc</TT> <I>cmd</I></B><DD CLASS="dd-description"> Use <I>cmd</I> instead of <TT>ocamlc</TT> to call
the bytecode compiler.
<DT CLASS="dt-description"><B><TT>-ocamlopt</TT> <I>cmd</I></B><DD CLASS="dd-description"> Use <I>cmd</I> instead of <TT>ocamlopt</TT> to call
the native-code compiler.
<DT CLASS="dt-description"><B><TT>-o</TT> <I>output</I></B><DD CLASS="dd-description"> Set the name of the generated Caml library.
<TT>ocamlmklib</TT> will generate <I>output</I><TT>.cma</TT> and/or <I>output</I><TT>.cmxa</TT>.
If not specified, defaults to <TT>a</TT>.
<DT CLASS="dt-description"><B><TT>-oc</TT> <I>outputc</I></B><DD CLASS="dd-description"> Set the name of the generated C library.
<TT>ocamlmklib</TT> will generate <TT>lib</TT><I>outputc</I><TT>.so</TT> (if shared
libraries are supported) and <TT>lib</TT><I>outputc</I><TT>.a</TT>.
If not specified, defaults to the output name given with <TT>-o</TT>.
</DL>

<H5 CLASS="paragraph">Example</H5> Consider a Caml interface to the standard <TT>libz</TT>
C library for reading and writing compressed files. Assume this
library resides in <TT>/usr/local/zlib</TT>. This interface is
composed of a Caml part <TT>zip.cmo</TT>/<TT>zip.cmx</TT> and a C part <TT>zipstubs.o</TT>
containing the stub code around the <TT>libz</TT> entry points. The
following command builds the Caml libraries <TT>zip.cma</TT> and <TT>zip.cmxa</TT>,
as well as the companion C libraries <TT>dllzip.so</TT> and <TT>libzip.a</TT>:
<PRE CLASS="verbatim">
ocamlmklib -o zip zip.cmo zip.cmx zipstubs.o -lz -L/usr/local/zlib
</PRE>If shared libraries are supported, this performs the following
commands:
<PRE CLASS="verbatim">
ocamlc -a -o zip.cma zip.cmo -dllib -lzip \
        -cclib -lzip -cclib -lz -ccopt -L/usr/local/zlib
ocamlopt -a -o zip.cmxa zip.cmx -cclib -lzip \
        -cclib -lzip -cclib -lz -ccopt -L/usr/local/zlib
gcc -shared -o dllzip.so zipstubs.o -lz -L/usr/local/zlib
ar rc libzip.a zipstubs.o
</PRE>If shared libraries are not supported, the following commands are
performed instead:
<PRE CLASS="verbatim">
ocamlc -a -custom -o zip.cma zip.cmo -cclib -lzip \
        -cclib -lz -ccopt -L/usr/local/zlib
ocamlopt -a -o zip.cmxa zip.cmx -lzip \
        -cclib -lz -ccopt -L/usr/local/zlib
ar rc libzip.a zipstubs.o
</PRE>Instead of building simultaneously the bytecode library, the
native-code library and the C libraries, <TT>ocamlmklib</TT> can be called
three times to build each separately. Thus,
<PRE CLASS="verbatim">
ocamlmklib -o zip zip.cmo -lz -L/usr/local/zlib
</PRE>builds the bytecode library <TT>zip.cma</TT>, and
<PRE CLASS="verbatim">
ocamlmklib -o zip zip.cmx -lz -L/usr/local/zlib
</PRE>builds the native-code library <TT>zip.cmxa</TT>, and
<PRE CLASS="verbatim">
ocamlmklib -o zip zipstubs.o -lz -L/usr/local/zlib
</PRE>builds the C libraries <TT>dllzip.so</TT> and <TT>libzip.a</TT>. Notice that the
support libraries (<TT>-lz</TT>) and the corresponding options
(<TT>-L/usr/local/zlib</TT>) must be given on all three invocations of <TT>ocamlmklib</TT>,
because they are needed at different times depending on whether shared
libraries are supported.<BR>
<BR>
<HR>
<A HREF="manual031.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A>
<A HREF="index.html"><IMG SRC ="contents_motif.gif" ALT="Up"></A>
<A HREF="manual033.html"><IMG SRC ="next_motif.gif" ALT="Next"></A>
</BODY>
</HTML>