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
|
<!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">
<TITLE>
Interfacing C with Objective Caml
</TITLE>
</HEAD>
<BODY >
<A HREF="manual027.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A>
<A HREF="manual029.html"><IMG SRC ="next_motif.gif" ALT="Next"></A>
<A HREF="index.html"><IMG SRC ="contents_motif.gif" ALT="Contents"></A>
<HR>
<H1>Chapter 15: 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>
<H2>15.1 Overview and compilation information</H2>
<H3>15.1.1 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>
external input : in_channel -> string -> int -> int -> 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
``manifest'' 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>
external input2 : in_channel * string * int * int -> 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>
type int_endo = int -> int
external f : int_endo -> int_endo = "f"
external g : (int -> int) -> (int -> 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>15.1.2 Implementing primitives</H3>User primitives with arity <I>n</I> <FONT FACE=symbol></FONT> 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>
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</TT><TT>_</TT><TT>nat</TT>:
<PRE>
value add_nat_native(value nat1, value ofs1, value len1,
value nat2, value ofs2, value len2,
value carry_in)
{
...
}
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</I> <I>native-code-C-function-name</I>
</PRE>
For instance, in the case of <TT>add</TT><TT>_</TT><TT>nat</TT>, the declaration is:
<PRE>
external add_nat: nat -> int -> int -> nat -> int -> int -> int -> 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 ``stub code'', 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>
value input(value channel, value buffer, value offset, value length)
{
return Val_long(getblock((struct channel *) channel,
&Byte(buffer, Long_val(offset)),
Long_val(length)));
}
</PRE>
(Here, <TT>Val</TT><TT>_</TT><TT>long</TT>, <TT>Long</TT><TT>_</TT><TT>val</TT> and so on are conversion macros for the
type <TT>value</TT>, that will be described later.) The hard work is
performed by the function <TT>getblock</TT>, which is declared as:
<PRE>
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 ALIGN=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 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 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 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 ALIGN=left NOWRAP><TT>caml/fail.h</TT></TD>
<TD VALIGN=top ALIGN=left>functions for raising exceptions
(see section <A HREF="manual028.html#s:c-exceptions">15.4.6</A>)</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>caml/callback.h</TT></TD>
<TD VALIGN=top ALIGN=left>callback from C to Caml (see
section <A HREF="manual028.html#s:callback">15.6</A>).</TD>
</TR></TABLE></DIV><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>15.1.3 Linking C code with Caml code</H3>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
``unavailable C primitive'' error.<BR>
<BR>
In the ``custom runtime'' 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>
<LI>
the table of the required primitives
<LI>a library that provides the bytecode interpreter, the
memory manager, and the standard primitives
<LI>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 ``custom runtime'' mode, execute the <TT>ocamlc</TT> command with:
<UL>
<LI>
the <TT>-custom</TT> option
<LI>the names of the desired Caml object files (<TT>.cmo</TT> and <TT>.cma</TT> files)
<LI>the names of the C object files and libraries (<TT>.o</TT> and <TT>.a</TT>
files) that implement the required primitives. (Under Unix, 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>
<LI>
the names of the desired Caml native object files (<TT>.cmx</TT> and
<TT>.cmxa</TT> files)
<LI>the names of the C object files and libraries (<TT>.o</TT> and <TT>.a</TT>
files) that implement the required primitives.
</UL>
<H3>15.1.4 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
``pure'' bytecode executables (not containing their own runtime
system) that can run on this custom runtime. This is achieved by the
<TT>-make</TT><TT>_</TT><TT>runtime</TT> and <TT>-use</TT><TT>_</TT><TT>runtime</TT> flags to <TT>ocamlc</TT>. For example,
to build a custom runtime system integrating the C parts of the
``unix'' and ``threads'' libraries, do:
<PRE>
ocamlc -make-runtime -o /home/me/ocamlunixrun unix.cma threads.cma \
-cclib -lunix -cclib -lthreads
</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 from <TT>-lunix</TT> and <TT>-lthreads</TT> 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>15.2 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>
<LI>
an unboxed integer
<LI>a pointer to a block inside the heap (such as the blocks
allocated through one of the <CODE>alloc_*</CODE> functions below)
<LI>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>15.2.1 Integer values</H3>Integer values encode 31-bit signed integers (63-bit on 64-bit
architectures). They are unboxed (unallocated).<BR>
<BR>
<H3>15.2.2 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</TT><TT>_</TT><TT>scan</TT><TT>_</TT><TT>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</TT><TT>_</TT><TT>scan</TT><TT>_</TT><TT>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 ALIGN=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 ALIGN=left NOWRAP>
0 to <TT>No</TT><TT>_</TT><TT>scan</TT><TT>_</TT><TT>tag</TT>-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 ALIGN=left NOWRAP><TT>Closure</TT><TT>_</TT><TT>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 ALIGN=left NOWRAP><TT>String</TT><TT>_</TT><TT>tag</TT></TD>
<TD VALIGN=top ALIGN=left>A character string.</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>Double</TT><TT>_</TT><TT>tag</TT></TD>
<TD VALIGN=top ALIGN=left>A double-precision floating-point number.</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>Double</TT><TT>_</TT><TT>array</TT><TT>_</TT><TT>tag</TT></TD>
<TD VALIGN=top ALIGN=left>An array or record of double-precision
floating-point numbers.</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>Abstract</TT><TT>_</TT><TT>tag</TT></TD>
<TD VALIGN=top ALIGN=left>A block representing an abstract datatype.</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>Final</TT><TT>_</TT><TT>tag</TT></TD>
<TD VALIGN=top ALIGN=left>A block representing an abstract datatype
with a ``finalization'' function, to be called when
the block is deallocated.</TD>
</TR></TABLE></DIV><BR>
<H3>15.2.3 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>&</CODE> operator.<BR>
<BR>
<H2>15.3 Representation of Caml data types</H2>This section describes how Caml data types are encoded in the
<TT>value</TT> type.<BR>
<BR>
<H3>15.3.1 Atomic types</H3><BR>
<BR>
<DIV ALIGN=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</TT><TT>_</TT><TT>tag</TT>.</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>string</TT></TD>
<TD ALIGN=left NOWRAP>Blocks with tag <TT>String</TT><TT>_</TT><TT>tag</TT>.</TD>
</TR></TABLE></DIV><BR>
<H3>15.3.2 Tuples and records</H3>Tuples are represented by pointers to blocks, with tag 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 0 of the block, the value associated
to the label declared next goes in field 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</TT><TT>_</TT><TT>array</TT><TT>_</TT><TT>tag</TT>. (See the section below on arrays.)<BR>
<BR>
<H3>15.3.3 Arrays</H3>Arrays of integers and pointers are represented like tuples,
that is, as pointers to blocks tagged 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</TT><TT>_</TT><TT>array</TT><TT>_</TT><TT>tag</TT>. They should be accessed with the <TT>Double</TT><TT>_</TT><TT>field</TT>
and <TT>Store</TT><TT>_</TT><TT>double</TT><TT>_</TT><TT>field</TT> macros.<BR>
<BR>
<H3>15.3.4 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 1, tagged
with the constructor number; the field 0 contains the value of the
constructor argument. Example:<BR>
<BR>
<BR>
<BR>
<DIV ALIGN=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 ALIGN=left NOWRAP>
<TT>()</TT></TD>
<TD VALIGN=top ALIGN=left><TT>Val</TT><TT>_</TT><TT>int(0)</TT></TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>false</TT></TD>
<TD VALIGN=top ALIGN=left><TT>Val</TT><TT>_</TT><TT>int(0)</TT></TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>true</TT></TD>
<TD VALIGN=top ALIGN=left><TT>Val</TT><TT>_</TT><TT>int(1)</TT></TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>[]</TT></TD>
<TD VALIGN=top ALIGN=left><TT>Val</TT><TT>_</TT><TT>int(0)</TT></TD>
</TR>
<TR><TD 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>
As a convenience, <TT>caml/mlvalues.h</TT> defines the macros <TT>Val</TT><TT>_</TT><TT>unit</TT>,
<TT>Val</TT><TT>_</TT><TT>false</TT> and <TT>Val</TT><TT>_</TT><TT>true</TT> to refer to <TT>()</TT>, <TT>false</TT> and <TT>true</TT>.<BR>
<BR>
<H3>15.3.5 Objects</H3>Objects are represented as zero-tagged blocks. 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. 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>
<H2>15.4 Operations on values</H2>
<H3>15.4.1 Kind tests</H3><UL>
<LI>
<TT>Is</TT><TT>_</TT><TT>long(</TT><I>v</I><TT>)</TT> is true if value <I>v</I> is an immediate integer,
false otherwise
<LI><TT>Is</TT><TT>_</TT><TT>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>15.4.2 Operations on integers</H3><UL>
<LI>
<TT>Val</TT><TT>_</TT><TT>long(</TT><I>l</I><TT>)</TT> returns the value encoding the <TT>long int</TT> <I>l</I>.
<LI><TT>Long</TT><TT>_</TT><TT>val(</TT><I>v</I><TT>)</TT> returns the <TT>long int</TT> encoded in value <I>v</I>.
<LI><TT>Val</TT><TT>_</TT><TT>int(</TT><I>i</I><TT>)</TT> returns the value encoding the <TT>int</TT> <I>i</I>.
<LI><TT>Int</TT><TT>_</TT><TT>val(</TT><I>v</I><TT>)</TT> returns the <TT>int</TT> encoded in value <I>v</I>.
<LI><TT>Val</TT><TT>_</TT><TT>bool(</TT><I>x</I><TT>)</TT> returns the Caml boolean representing the
truth value of the C integer <I>x</I>.
<LI><TT>Bool</TT><TT>_</TT><TT>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><TT>Val</TT><TT>_</TT><TT>true</TT>, <TT>Val</TT><TT>_</TT><TT>false</TT> represent the Caml booleans <TT>true</TT> and <TT>false</TT>.
</UL>
<H3>15.4.3 Accessing blocks</H3><UL>
<LI>
<TT>Wosize</TT><TT>_</TT><TT>val(</TT><I>v</I><TT>)</TT> returns the size of the block <I>v</I>, in words,
excluding the header.
<LI><TT>Tag</TT><TT>_</TT><TT>val(</TT><I>v</I><TT>)</TT> returns the tag of the block <I>v</I>.
<LI><TT>Field(</TT><I>v</I><TT>, </TT><I>n</I><TT>)</TT> returns the value contained in the
<I>n</I><SUP><FONT SIZE=2>th</FONT></SUP> field
of the structured block <I>v</I>. Fields are numbered from 0 to
<TT>Wosize</TT><TT>_</TT><TT>val</TT>(<I>v</I>)-1.
<LI><TT>Store</TT><TT>_</TT><TT>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><TT>Code</TT><TT>_</TT><TT>val(</TT><I>v</I><TT>)</TT> returns the code part of the closure <I>v</I>.
<LI><TT>string</TT><TT>_</TT><TT>length(</TT><I>v</I><TT>)</TT> returns the length (number of characters)
of the string <I>v</I>.
<LI><TT>Byte(</TT><I>v</I><TT>, </TT><I>n</I><TT>)</TT> returns the <I>n</I><SUP><FONT SIZE=2>th</FONT></SUP> character of the string
<I>v</I>, with type <TT>char</TT>. Characters are numbered from 0 to
<TT>string</TT><TT>_</TT><TT>length</TT>(<I>v</I>)-1.
<LI><TT>Byte</TT><TT>_</TT><TT>u(</TT><I>v</I><TT>, </TT><I>n</I><TT>)</TT> returns the <I>n</I><SUP><FONT SIZE=2>th</FONT></SUP> character of the string
<I>v</I>, with type <TT>unsigned char</TT>. Characters are numbered from 0 to
<TT>string</TT><TT>_</TT><TT>length</TT>(<I>v</I>)-1.
<LI><TT>String</TT><TT>_</TT><TT>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><TT>Double</TT><TT>_</TT><TT>val(</TT><I>v</I><TT>)</TT> returns the floating-point number contained in
value <I>v</I>, with type <TT>double</TT>.
<LI><TT>Double</TT><TT>_</TT><TT>field(</TT><I>v</I><TT>, </TT><I>n</I><TT>)</TT> returns
the <I>n</I><SUP><FONT SIZE=2>th</FONT></SUP> element of the array of floating-point numbers <I>v</I> (a
block tagged <TT>Double</TT><TT>_</TT><TT>array</TT><TT>_</TT><TT>tag</TT>).
<LI><TT>Store</TT><TT>_</TT><TT>double</TT><TT>_</TT><TT>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><SUP><FONT SIZE=2>th</FONT></SUP> element of the array of floating-point numbers <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</TT><TT>_</TT><TT>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>15.4.4 Allocating blocks</H3>
<H4> Simple interface</H4><UL>
<LI>
<TT>Atom(</TT><I>t</I><TT>)</TT> returns an ``atom'' (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>
<TT>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</TT><TT>_</TT><TT>scan</TT><TT>_</TT><TT>tag</TT>, then the
fields of the block are initialized with a valid value in order to
satisfy the GC constraints.
<LI>
<TT>alloc</TT><TT>_</TT><TT>tuple(</TT><I>n</I><TT>)</TT> returns a fresh block of size
<I>n</I> words, with tag 0.
<LI>
<TT>alloc</TT><TT>_</TT><TT>string(</TT><I>n</I><TT>)</TT> returns a string value of length <I>n</I> characters.
The string initially contains garbage.
<LI>
<TT>copy</TT><TT>_</TT><TT>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>
<TT>copy</TT><TT>_</TT><TT>double(</TT><I>d</I><TT>)</TT> returns a floating-point value initialized
with the <TT>double</TT> <I>d</I>.
<LI>
<TT>alloc</TT><TT>_</TT><TT>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</TT><TT>_</TT><TT>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>
<TT>copy</TT><TT>_</TT><TT>string</TT><TT>_</TT><TT>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>).
</UL>
<H4> Low-level interface</H4>The following functions are slightly more efficient than <TT>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.<BR>
<BR>
<UL>
<LI>
<TT>alloc</TT><TT>_</TT><TT>small(</TT><I>n</I><TT>, </TT><I>t</I><TT>)</TT> returns a fresh small block of size
<I>n</I> <FONT FACE=symbol></FONT> <TT>Max</TT><TT>_</TT><TT>young</TT><TT>_</TT><TT>wosize</TT> words, with tag <I>t</I>.
If this block is a structured block (i.e. if <I>t</I> < <TT>No</TT><TT>_</TT><TT>scan</TT><TT>_</TT><TT>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>
<TT>alloc</TT><TT>_</TT><TT>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>alloc</TT><TT>_</TT><TT>small</TT> instead of <TT>alloc</TT><TT>_</TT><TT>shr</TT>.)
If this block is a structured block (i.e. if <I>t</I> < <TT>No</TT><TT>_</TT><TT>scan</TT><TT>_</TT><TT>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>15.4.5 Finalized blocks</H3>Blocks with tag <TT>Final</TT><TT>_</TT><TT>tag</TT> have an attached C finalization function
that is called when the block becomes unreachable and is about to be
reclaimed. A pointer to the finalization function occupies the first
word of the
allocated block; the remaining words can contain arbitrary raw data
(but not Caml pointers, since <TT>Final</TT><TT>_</TT><TT>tag</TT> is greater than
<TT>No</TT><TT>_</TT><TT>scan</TT><TT>_</TT><TT>tag</TT>).<BR>
<BR>
Finalized blocks must be allocated via the <TT>alloc</TT><TT>_</TT><TT>final</TT> function.
<TT>alloc</TT><TT>_</TT><TT>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 finalized block of size <I>n</I> words, with
finalization function <I>f</I>. The pointer to the finalization
function uses the first word, the other <I>n</I>-1 are available for
your data.<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 ``floating garbage'' (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>
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 ``often enough'', consider
increasing the <I>used</I> / <I>max</I> ratio.<BR>
<BR>
<H3>15.4.6 Raising exceptions</H3> <A NAME="s:c-exceptions"></A>Two functions are provided to raise two standard exceptions:
<UL>
<LI>
<TT>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><TT>invalid</TT><TT>_</TT><TT>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</TT><TT>_</TT><TT>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 <A HREF="manual028.html#s:register-exn">15.6.3</A>.
Once the exception identifier is recovered in C, the following
functions actually raise the exception:
<UL>
<LI>
<TT>raise</TT><TT>_</TT><TT>constant(</TT><I>id</I><TT>)</TT> raises the exception <I>id</I> with
no argument;
<LI><TT>raise</TT><TT>_</TT><TT>with</TT><TT>_</TT><TT>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><TT>raise</TT><TT>_</TT><TT>with</TT><TT>_</TT><TT>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>15.5 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>15.5.1 Simple interface</H3>All the macros described in this section are declared in the
<TT>memory.h</TT> header file.<BR>
<BR>
<BR><B>Rule </B><B>1</B> <I>
A function that has parameters or local variables of type </I><I><TT>value</TT></I><I> must
begin with a call to one of the </I><I><TT>CAMLparam</TT></I><I> macros and return with
</I><I><TT>CAMLreturn</TT></I><I>.<BR></I><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>CAMLxparam0</TT> to <TT>CAMLxparam5</TT>).<BR>
<BR>
The macro <TT>CAMLreturn</TT> is used as a direct replacement for the C
keyword <TT>return</TT>. All occurences of <TT>return</TT> must be replaced by
<TT>CAMLreturn</TT>, including the implicit <TT>return</TT> at the end of a
procedure (<TT>void</TT>-returning function).<BR>
<BR>
<BR>Example:
<PRE>
void foo (value v1, value v2, value v3)
{
CAMLparam3 (v1, v2, v3);
...
CAMLreturn;
}
</PRE><B>Note:</B> 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>
<BR><B>Rule </B><B>2</B> <I>
Local variables of type </I><I><TT>value</TT></I><I> must be declared with one of the
</I><I><TT>CAMLlocal</TT></I><I> macros. Arrays of </I><I><TT>value</TT></I><I>s are declared with
</I><I><TT>CAMLlocalN</TT></I><I>.<BR></I><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. You can also use them in nested C blocks within the
function.<BR>
<BR>
Example:
<PRE>
value bar (value v1, value v2, value v3)
{
CAMLparam3 (v1, v2, v3);
CAMLlocal1 (result);
result = alloc (3, 0);
...
CAMLreturn result;
}
</PRE><BR><B>Rule </B><B>3</B> <I>
Assignments to the fields of structured blocks must be done with the
</I><I><TT>Store</TT></I><I><TT>_</TT></I><I><TT>field</TT></I><I> macro.<BR></I><BR>
<BR>
<TT>Store</TT><TT>_</TT><TT>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</TT><TT>_</TT><TT>block(</TT><I>b</I><TT>)</TT> must be true).<BR>
<BR>
Example:
<PRE>
value bar (value v1, value v2, value v3)
{
CAMLparam3 (v1, v2, v3);
CAMLlocal1 (result);
result = alloc (3, 0);
Store_field (result, 0, v1);
Store_field (result, 1, v2);
Store_field (result, 2, v3);
CAMLreturn result;
}
</PRE><BR><B>Rule </B><B>4</B> <I>Global variables containing values must be registered
with the garbage collector using the </I><I><TT>register</TT></I><I><TT>_</TT></I><I><TT>global</TT></I><I><TT>_</TT></I><I><TT>root</TT></I><I> function.<BR></I><BR>
<BR>
Registration of a global variable <TT>v</TT> is achieved by calling
<TT>register</TT><TT>_</TT><TT>global</TT><TT>_</TT><TT>root(</TT><TT>&</TT><TT>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>remove</TT><TT>_</TT><TT>global</TT><TT>_</TT><TT>root(</TT><TT>&</TT><TT>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><TT>_</TT><TT>_</TT>. Do not use any
identifier starting with <TT>caml</TT><TT>_</TT><TT>_</TT> in your programs.<BR>
<BR>
<H3>15.5.2 Low-level interface</H3>We now give the GC rules corresponding to the low-level allocation
functions <TT>alloc</TT><TT>_</TT><TT>small</TT> and <TT>alloc</TT><TT>_</TT><TT>shr</TT>. You can ignore those rules
if you stick to the simplified allocation function <TT>alloc</TT>.<BR>
<BR>
<BR><B>Rule </B><B>5</B> <I>After a structured block (a block with tag less than
</I><I><TT>No</TT></I><I><TT>_</TT></I><I><TT>scan</TT></I><I><TT>_</TT></I><I><TT>tag</TT></I><I>) 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
</I><I><TT>alloc</TT></I><I><TT>_</TT></I><I><TT>small</TT></I><I>, filling is performed by direct assignment to the fields
of the block:
</I><PRE><I>
Field(</I><I>v</I><I>, </I><I>n</I><I>) = </I><I><I>v</I></I><SUB><I><FONT SIZE=2><I>n</I></FONT></I></SUB><I>;
</I></PRE><I>
If the block has been allocated with </I><I><TT>alloc</TT></I><I><TT>_</TT></I><I><TT>shr</TT></I><I>, filling is performed
through the </I><I><TT>initialize</TT></I><I> function:
</I><PRE><I>
initialize(&Field(</I><I>v</I><I>, </I><I>n</I><I>), </I><I><I>v</I></I><SUB><I><FONT SIZE=2><I>n</I></FONT></I></SUB><I>);
</I></PRE><I><BR></I><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</TT><TT>_</TT><TT>long(0)</TT>), then allocate, then modify the fields with the correct
value (see rule 6).<BR>
<BR>
<BR><B>Rule </B><B>6</B> <I>Direct assignment to a field of a block, as in
</I><PRE><I>
Field(</I><I>v</I><I>, </I><I>n</I><I>) = </I><I>w</I><I>;
</I></PRE><I>
is safe only if </I><I>v</I><I> is a block newly allocated by </I><I><TT>alloc</TT></I><I><TT>_</TT></I><I><TT>small</TT></I><I>;
that is, if no allocation took place between the
allocation of </I><I>v</I><I> and the assignment to the field. In all other cases,
never assign directly. If the block has just been allocated by </I><I><TT>alloc</TT></I><I><TT>_</TT></I><I><TT>shr</TT></I><I>,
use </I><I><TT>initialize</TT></I><I> to assign a value to a field for the first time:
</I><PRE><I>
initialize(&Field(</I><I>v</I><I>, </I><I>n</I><I>), </I><I>w</I><I>);
</I></PRE><I>
Otherwise, you are updating a field that previously contained a
well-formed value; then, call the </I><I><TT>modify</TT></I><I> function:
</I><PRE><I>
modify(&Field(</I><I>v</I><I>, </I><I>n</I><I>), </I><I>w</I><I>);
</I></PRE><I><BR></I><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>
value alloc_list_int(int i1, int i2)
{
CAMLparam0;
CAMLlocal2 (result, r);
r = 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 = 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>alloc</TT><TT>_</TT><TT>small</TT>, and filled by direct assignments on
their fields.
<PRE>
value alloc_list_int(int i1, int i2)
{
CAMLparam0;
CAMLlocal2 (result, r);
r = 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 = 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>
value alloc_list_int(int i1, int i2)
{
CAMLparam0;
CAMLlocal2 (tail, r);
r = 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 = 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 [] */
modify(&Field(r, 1), tail); /* cdr of the result = tail */
return 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. <TT>tail</TT> is not registered as
a root because there is no allocation between the assignment where it
takes its value and the <TT>modify</TT> statement that uses the value.<BR>
<BR>
<H2>15.6 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>15.6.1 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>
<LI>
<TT>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 <I>f</I>.
<LI><TT>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><TT>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><TT>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>callback</TT><TT>_</TT><TT>exn</TT>, <TT>callback2</TT><TT>_</TT><TT>exn</TT>,
<TT>callback3</TT><TT>_</TT><TT>exn</TT>, <TT>callbackN</TT><TT>_</TT><TT>exn</TT>. These functions take the same
arguments as their non-<TT>_</TT><TT>exn</TT> counterparts, but catch escaping
exceptions and return them to the C code. The return value <I>v</I> of the
<TT>callback*</TT><TT>_</TT><TT>exn</TT> functions must be tested with the macro
<TT>Is</TT><TT>_</TT><TT>exception</TT><TT>_</TT><TT>result(</TT><I>v</I><TT>)</TT>. If the macro returns ``false'', no
exception occured, and <I>v</I> is the value returned by the Caml
function. If <TT>Is</TT><TT>_</TT><TT>exception</TT><TT>_</TT><TT>result(</TT><I>v</I><TT>)</TT> returns ``true'',
an exception escaped, and its value (the exception descriptor) can be
recovered using <TT>Extract</TT><TT>_</TT><TT>exception(</TT><I>v</I><TT>)</TT>.<BR>
<BR>
<H3>15.6.2 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</I> <I>v</I>. Here, <I>n</I> is the global name
(an arbitrary string) and <I>v</I> the Caml value. For instance:
<PRE>
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</TT><TT>_</TT><TT>named</TT><TT>_</TT><TT>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>
void call_caml_f(int arg)
{
callback(*caml_named_value("test function"), Val_int(arg));
}
</PRE>The pointer returned by <TT>caml</TT><TT>_</TT><TT>named</TT><TT>_</TT><TT>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</TT><TT>_</TT><TT>caml</TT><TT>_</TT><TT>f</TT> above that calls <TT>caml</TT><TT>_</TT><TT>named</TT><TT>_</TT><TT>value</TT>
only once:
<PRE>
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");
}
callback(*closure_f, Val_int(arg));
}
</PRE>
<H3>15.6.3 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</TT><TT>_</TT><TT>exception</TT> <I>n</I> <I>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>
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</TT><TT>_</TT><TT>named</TT><TT>_</TT><TT>value</TT> and pass it as first argument to the functions
<TT>raise</TT><TT>_</TT><TT>constant</TT>, <TT>raise</TT><TT>_</TT><TT>with</TT><TT>_</TT><TT>arg</TT>, and <TT>raise</TT><TT>_</TT><TT>with</TT><TT>_</TT><TT>string</TT> (described
in section <A HREF="manual028.html#s:c-exceptions">15.4.6</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>
void raise_error(char * msg)
{
raise_with_string(*caml_named_value("test exception"), msg);
}
</PRE>
<H3>15.6.4 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>
<LI>
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>At some point, the C code must call <TT>caml</TT><TT>_</TT><TT>main(argv)</TT> to
initialize the Caml code. The <TT>argv</TT> argument is a C array of strings
(type <TT>char **</TT>) 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>The call to <TT>caml</TT><TT>_</TT><TT>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</TT><TT>_</TT><TT>main</TT>.<BR>
<BR>
<LI>The C code can then invoke Caml functions using the callback
mechanism (see section <A HREF="manual028.html#s:callbacks">15.6.1</A>).
</UL>
<H3>15.6.5 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</TT><TT>_</TT><TT>main(argv)</TT> as in
section <A HREF="manual028.html#s:main-c">15.6.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</TT><TT>_</TT><TT>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</TT><TT>_</TT><TT>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</TT><TT>_</TT><TT>main</TT>, it takes one <TT>argv</TT>
parameter containing the command-line parameters. Unlike <TT>caml</TT><TT>_</TT><TT>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</TT><TT>_</TT><TT>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> 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>
<LI>
Digital Unix on the Alpha: object files produced by <TT>ocamlc -output-obj</TT> must be linked with the <TT>-taso</TT> option. This is not
necessary for object files produced by <TT>ocamlopt -output-obj</TT>.
<LI>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>15.7 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>
type window (* The type "window" remains abstract *)
external initscr: unit -> window = "curses_initscr"
external endwin: unit -> unit = "curses_endwin"
external refresh: unit -> unit = "curses_refresh"
external wrefresh : window -> unit = "curses_wrefresh"
external newwin: int -> int -> int -> int -> window = "curses_newwin"
external mvwin: window -> int -> int -> unit = "curses_mvwin"
external addch: char -> unit = "curses_addch"
external mvwaddch: window -> int -> int -> char -> unit = "curses_mvwaddch"
external addstr: string -> unit = "curses_addstr"
external mvwaddstr: window -> int -> int -> string -> unit = "curses_mvwaddstr"
(* lots more omitted *)
</PRE>
To compile this interface:
<PRE>
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.o</TT>, looks like:
<PRE>
#include <curses.h>
#include <mlvalues.h>
value curses_initscr(value unit)
{
return (value) initscr(); /* OK to coerce directly from WINDOW * to value
since that's a block created by malloc() */
}
value curses_wrefresh(value win)
{
wrefresh((WINDOW *) win);
return Val_unit;
}
value curses_newwin(value nlines, value ncols, value x0, value y0)
{
return (value) newwin(Int_val(nlines), Int_val(ncols),
Int_val(x0), Int_val(y0));
}
value curses_addch(value c)
{
addch(Int_val(c)); /* Characters are encoded like integers */
return Val_unit;
}
value curses_addstr(value s)
{
addstr(String_val(s));
return Val_unit;
}
/* This goes on for pages. */
</PRE>The file <TT>curses.c</TT> can be compiled with:
<PRE>
cc -c -I/usr/local/lib/ocaml curses.c
</PRE>
or, even simpler,
<PRE>
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>
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();
for i = 1 to 100000 do () done;
endwin()
</PRE>
To compile this program, run:
<PRE>
ocamlc -c test.ml
</PRE>
Finally, to link everything together:
<PRE>
ocamlc -custom -o test test.cmo curses.o -cclib -lcurses
</PRE>
<H2>15.8 Advanced example with callbacks</H2>This section illustrates the callback facilities described in
section <A HREF="manual028.html#s:callback">15.6</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:<BR>
<BR>
<PRE>
(* File mod.ml -- some ``useful'' Caml functions *)
let rec fib n = if n < 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:<BR>
<BR>
<PRE>
/* File modwrap.c -- wrappers around the Caml functions */
#include <stdio.h>
#include <string.h>
#include <caml/mlvalues.h>
#include <caml/callback.h>
int fib(int n)
{
static value * fib_closure = NULL;
if (fib_closure == NULL) fib_closure = caml_named_value("fib");
return Int_val(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(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>
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 fonctions <TT>fib</TT> and <TT>format</TT><TT>_</TT><TT>result</TT> in any C
program, just like regular C functions. Just remember to call
<TT>caml</TT><TT>_</TT><TT>startup</TT> once before.<BR>
<BR>
<PRE>
/* File main.c -- a sample client for the Caml functions */
#include <stdio.h>
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>
cc -o prog main.c mod.a
</PRE>
<HR>
<A HREF="manual027.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A>
<A HREF="manual029.html"><IMG SRC ="next_motif.gif" ALT="Next"></A>
<A HREF="index.html"><IMG SRC ="contents_motif.gif" ALT="Contents"></A>
</BODY>
</HTML>
|