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 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
|
<ppdoc>
<copyright>
Copyright (c) 2001 by Addison Wesley Longman. This
material may be distributed only subject to the terms and
conditions set forth in the Open Publication License, v1.0 or
later (the latest version is presently available at
http://www.opencontent.org/openpub/).
</copyright>
<chapter name="Extending Ruby">
<p/>
It
is easy to extend Ruby with new features by writing code in Ruby.
Once you start adding in low-level code written in C, however, the
possibilities are endless.
<p/>
Extending Ruby with C is pretty easy. For instance, suppose we are
building a custom Internet-ready jukebox for the Sunset Diner and
Grill. It will play MP3 audio files from a hard disk or audio CDs
from a CD jukebox. We want to be able to control the jukebox hardware
from a Ruby program. The hardware vendor gave us a C header file and
a binary library to use; our job is to construct a Ruby object
that makes the appropriate C function calls.
<p/>
But before we can get Ruby and C to work together, we need to see what
the Ruby world looks like from the C side.<footnote>Much of the
information in this chapter is taken from the <tt>README.EXT</tt>
file that is included in the distribution. If you are planning on
writing a Ruby extension, you may want to refer to that file for
more details as well as the latest changes.</footnote>
<section>Ruby Objects in C</section>
<p/>
The first thing we need to look at is how to represent and access Ruby
datatypes from within C.
Everything in Ruby is an object, and all
variables are references to objects. In C, this means that the type
of all Ruby variables is <tt>VALUE</tt>,
which is either a pointer to a Ruby object or an immediate value (such
as <tt>Fixnum</tt>).
<p/>
This is how Ruby implements object-oriented code in C: a Ruby object
is an allocated structure in memory that contains a table of instance
variables and information about the class. The class itself is
another object (an allocated structure in memory) that contains a
table of the methods defined for that class. On this foundation hangs
all of Ruby.
<subsection><sansfont>VALUE</sansfont> as a Pointer</subsection>
When <tt>VALUE</tt> is a pointer, it is a pointer to one of the
defined Ruby object structures---you can't have a <tt>VALUE</tt> that points to an
arbitrary structure. The structures for each built-in
class are defined in ``<tt>ruby.h</tt>''
and are named <tt>R</tt><em>Classname</em>, as in <tt>RString</tt> and
<tt>RArray</tt>.
<p/>
You can check to see what type of structure is used for a particular
<tt>VALUE</tt> in a number of ways. The macro <tt>TYPE(</tt><em>obj</em><tt>)</tt>
will return a constant representing the C
type of the given object: <tt>T_OBJECT</tt>, <tt>T_STRING</tt>, and so on.
Constants for the built-in classes are defined in ``<tt>ruby.h</tt>''.
Note that the <em>type</em> we are referring to here is an
implementation detail---it is not the same as the class of an object.
<p/>
If you want to ensure that a value pointer points to a particular
structure, you can use the macro <tt>Check_Type</tt>, which will raise a
<exception>TypeError</exception> exception if <em>value</em> is not of the expected
<em>type</em> (which is one of the constants <tt>T_STRING</tt>,
<tt>T_FLOAT</tt>, and so on):
<p/>
<alltt>
Check_Type(VALUE <em>value</em>, int <em>type</em>)
</alltt>
<p/>
If speed is an issue, there are faster macros that check specifically
for the immediate values <tt>Fixnum</tt> and <tt>nil</tt>.
<p/>
<alltt>
FIXNUM_P(<em>value</em>) <returns>non-zero if value is a Fixnum</returns>
NIL_P(<em>value</em>) <returns>non-zero if value is nil</returns>
RTEST(<em>value</em>) <returns>non-zero if value is neither nil nor false</returns>
</alltt>
<p/>
Again, note that we are talking about ``type'' as the C structure that
represents a particular built-in type. The class of an object is a
different beast entirely. The class objects for the built-in classes
are stored in C global variables named <tt>rb_c</tt><em>Classname</em>
(for instance, <tt>rb_cObject</tt>); modules are named
<tt>rb_m</tt><em>Modulename</em>.
<p/>
It wouldn't be advisable to mess with the data in these
structures directly, however---you may look, but don't touch unless
you are fond of debuggers. You should normally use only the supplied
C functions to manipulate Ruby data (we'll talk more about this in just
a moment).
<p/>
However, in the interests of efficiency you may need to dig into these
structures to obtain data. In order to dereference members of these C
structures, you have to cast the generic <tt>VALUE</tt> to the proper
structure type. <tt>ruby.h</tt> contains a number of macros that perform
the proper casting for you, allowing you to dereference structure
members easily. These macros are named
<tt>R<em>CLASSNAME</em></tt>, as in <tt>RSTRING</tt> or <tt>RARRAY</tt>. For
example:
<p/>
<alltt>
VALUE str, arr;
RSTRING(str)->len <returns>length of the Ruby string</returns>
RSTRING(str)->ptr <returns>pointer to string storage</returns>
RARRAY(arr)->len <returns>length of the Ruby array</returns>
RARRAY(arr)->capa <returns>capacity of the Ruby array</returns>
RARRAY(arr)->ptr <returns>pointer to array storage</returns>
</alltt>
<subsection><sansfont>VALUE</sansfont> as an Immediate Object</subsection>
<p/>
As we said above, immediate values are not pointers: <tt>Fixnum</tt>,
<tt>Symbol</tt>, <tt>true</tt>, <tt>false</tt>, and <tt>nil</tt> are stored directly in
<tt>VALUE</tt>.
<p/>
<tt>Fixnum</tt> values are stored as 31-bit numbers<footnote>Or 63-bit on
wider CPU architectures.</footnote> that are formed by shifting the original
number left 1 bit and then setting the least significant bit (bit
0) to ``1.'' When <tt>VALUE</tt> is used as a pointer to a specific Ruby
structure, it is guaranteed always to have an LSB of zero; the
other immediate values also have LSBs of zero. Thus, a simple
bit test can tell you whether or not you have a <tt>Fixnum</tt>.
<p/>
There are several useful conversion macros for numbers as well as
other standard datatypes shown in Table 17.1 on page 176.
<p/>
The other immediate values (<kw>true</kw>, <kw>false</kw>, and <tt>nil</tt>) are
represented in C as the constants <kw>Qtrue</kw>, <kw>Qfalse</kw>, and
<kw>Qnil</kw>, respectively. You can test <tt>VALUE</tt> variables against
these constants directly, or use the conversion macros (which perform
the proper casting).
<section>Writing Ruby in C</section>
<p/>
One of the joys of Ruby is that you can write Ruby programs almost
directly in C. That is, you can use the same methods and the same
logic, but with slightly different syntax to accommodate C. For
instance, here is a small, fairly boring test class written in Ruby.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ class Test
def initialize
@arr = Array.new
end
def add(anObject)
@arr.push(anObject)
end
end
]]></fullcode>
class<nbsp/>Test
<nbsp/><nbsp/>def<nbsp/>initialize
<nbsp/><nbsp/><nbsp/><nbsp/>@arr<nbsp/>=<nbsp/>Array.new
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>add(anObject)
<nbsp/><nbsp/><nbsp/><nbsp/>@arr.push(anObject)
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
The equivalent code in C should look somewhat familiar.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[#include "ruby.h"
static VALUE t_init(VALUE self)
{
VALUE arr;
arr = rb_ary_new();
rb_iv_set(self, "@arr", arr);
return self;
}
static VALUE t_add(VALUE self, VALUE anObject)
{
VALUE arr;
arr = rb_iv_get(self, "@arr");
rb_ary_push(arr, anObject);
return arr;
}
VALUE cTest;
void Init_Test() {
cTest = rb_define_class("Test", rb_cObject);
rb_define_method(cTest, "initialize", t_init, 0);
rb_define_method(cTest, "add", t_add, 1);
}
]]></fullcode>
#include<nbsp/>"ruby.h"
<p/>
static<nbsp/>VALUE<nbsp/>t_init(VALUE<nbsp/>self)
{
<nbsp/><nbsp/>VALUE<nbsp/>arr;
<p/>
<nbsp/><nbsp/>arr<nbsp/>=<nbsp/>rb_ary_new();
<nbsp/><nbsp/>rb_iv_set(self,<nbsp/>"@arr",<nbsp/>arr);
<nbsp/><nbsp/>return<nbsp/>self;
}
<p/>
static<nbsp/>VALUE<nbsp/>t_add(VALUE<nbsp/>self,<nbsp/>VALUE<nbsp/>anObject)
{
<nbsp/><nbsp/>VALUE<nbsp/>arr;
<p/>
<nbsp/><nbsp/>arr<nbsp/>=<nbsp/>rb_iv_get(self,<nbsp/>"@arr");
<nbsp/><nbsp/>rb_ary_push(arr,<nbsp/>anObject);
<nbsp/><nbsp/>return<nbsp/>arr;
}
<p/>
VALUE<nbsp/>cTest;
<p/>
void<nbsp/>Init_Test()<nbsp/>{
<nbsp/><nbsp/>cTest<nbsp/>=<nbsp/>rb_define_class("Test",<nbsp/>rb_cObject);
<nbsp/><nbsp/>rb_define_method(cTest,<nbsp/>"initialize",<nbsp/>t_init,<nbsp/>0);
<nbsp/><nbsp/>rb_define_method(cTest,<nbsp/>"add",<nbsp/>t_add,<nbsp/>1);
}
</alltt>
</codefragment>
<p/>
Let's go through this example in detail, as it illustrates many of the
important concepts in this chapter. First off, we need to include the
header file ``<tt>ruby.h</tt>'' to obtain the necessary definitions.
<p/>
Now look at the last function, <tt>Init_Test</tt>.
Every class or module
defines a C global function named <tt>Init_</tt><em>Name</em>. This
function will be called when the interpreter first loads the extension
<em>Name</em> (or on startup for statically linked extensions). It is
used to initialize the extension and to insinuate it into the Ruby
environment. In this case, we define a new class named <tt>Test</tt>,
which is a subclass of <tt>Object</tt> (represented by the external symbol
<tt>rb_cObject</tt>; see ``<tt>ruby.h</tt>'' for others).
<p/>
Next we set up <tt>add</tt> and <tt>initialize</tt> as two instance methods
for class <tt>Test</tt>.
The calls to <tt>rb_define_method</tt> establish
a binding between the Ruby method name and the C function that will
implement it, so a call to the <tt>add</tt> method in Ruby will call the
C function <tt>t_add</tt> with one argument.
<p/>
Similarly, when <tt>new</tt> is called for this class, Ruby will construct
a basic object and then call <tt>initialize</tt>, which we have defined
here to call the C function <tt>t_init</tt> with no (Ruby) arguments.
<p/>
Now go back and look at the definition of <tt>initialize</tt>. Even
though we said it took no arguments, there's a parameter here! In
addition to any Ruby arguments, every method is passed an initial
<tt>VALUE</tt> argument that contains the receiver for this method (the
equivalent of <const>self</const> in Ruby code).
<p/>
The first thing we'll do in <tt>initialize</tt> is create a Ruby array
and set the instance variable <tt>@arr</tt> to point to it. Just as you
would expect if you were writing Ruby source, referencing an instance
variable that doesn't exist creates it.
<p/>
Finally, the function <tt>t_add</tt> gets the instance variable <tt>@arr</tt>
from the current object and calls <cim><file>array</file><front>Array</front><back>push</back><mref>push</mref></cim> to push the passed value
onto that array. When accessing instance variables in this way, the
<tt>@</tt>-prefix is mandatory---otherwise the variable is created, but
cannot be referenced from Ruby.
<p/>
Despite the extra, clunky syntax that C imposes, you're still writing
in Ruby---you can manipulate objects using all of the method calls
you've come to know and love, with the added advantage of being able
to craft tight, fast code when needed.
<p/>
<b>WARNING:</b> Every C function that is callable from Ruby
<em>must</em> return a <tt>VALUE</tt>, even if it's just <const>Qnil</const>.
Otherwise, a core dump (or GPF) will be the likely result.
<p/>
We can use the C version of the code in Ruby simply
by <kw>require</kw>-ing it dynamically at runtime (on
most platforms).
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ require "code/ext/Test"
t = Test.new
t.add("Bill Chase")
]]></fullcode>
require<nbsp/>"code/ext/Test"
t<nbsp/>=<nbsp/>Test.new
t.add("Bill<nbsp/>Chase")
</alltt>
</codefragment>
<figure type="table">
<caption>C/Ruby datatype conversion functions and
macros</caption>
<table>
<th>
<td colspan="3"><b>C Datatypes to Ruby Objects:</b></td>
</th>
<tr>
<td></td>
<td>INT2NUM(<em>int</em>)</td>
<td><returns><em>Fixnum</em> or <em>Bignum</em></returns></td>
</tr>
<tr>
<td></td>
<td>INT2FIX(<em>int</em>)</td>
<td><returns><em>Fixnum</em></returns> (faster)</td>
</tr>
<tr>
<td></td>
<td>INT2NUM(<em>long</em> or <em>int</em>)</td>
<td><returns><em>Fixnum</em> or <em>Bignum</em></returns></td>
</tr>
<tr>
<td></td>
<td>INT2FIX(<em>long</em> or <em>int</em>)</td>
<td><returns><em>Fixnum</em></returns> (faster)</td>
</tr>
<tr>
<td></td>
<td>CHR2FIX(<em>char</em>)</td>
<td><returns><em>Fixnum</em></returns></td>
</tr>
<tr>
<td></td>
<td>rb_str_new2(<em>char *</em>)</td>
<td><returns><em>String</em></returns></td>
</tr>
<tr>
<td></td>
<td>rb_float_new(<em>double</em>)</td>
<td><returns><em>Float</em></returns></td>
</tr>
<toprule/><tr>
<td colspan="3"><b>Ruby Objects to C Datatypes:</b></td>
</tr>
<th>
<td>int</td>
<td>NUM2INT(<em>Numeric</em>)</td>
<td>(Includes type check)</td>
</th>
<th>
<td>int</td>
<td>FIX2INT(<em>Fixnum</em>)</td>
<td>(Faster)</td>
</th>
<th>
<td>unsigned int</td>
<td>NUM2UINT(<em>Numeric</em>)</td>
<td>(Includes type check)</td>
</th>
<th>
<td>unsigned int</td>
<td>FIX2UINT(<em>Fixnum</em>)</td>
<td>(Includes type check)</td>
</th>
<th>
<td>long</td>
<td>NUM2LONG(<em>Numeric</em>)</td>
<td>(Includes type check)</td>
</th>
<th>
<td>long</td>
<td>FIX2LONG(<em>Fixnum</em>)</td>
<td>(Faster)</td>
</th>
<th>
<td>unsigned long</td>
<td>NUM2ULONG(<em>Numeric</em>)</td>
<td>(Includes type check)</td>
</th>
<th>
<td>char</td>
<td>NUM2CHR(<em>Numeric</em> or <em>String</em>)</td>
<td>(Includes type check)</td>
</th>
<th>
<td>char *</td>
<td>STR2CSTR(<em>String</em>)</td>
<td></td>
</th>
<th>
<td>char *</td>
<td>rb_str2cstr(<em>String</em>, int *length)</td>
<td>Returns length as well</td>
</th>
<th>
<td>double</td>
<td>NUM2DBL(<em>Numeric</em>)</td>
<td></td>
</th>
<bottomrule/></table>
<p/>
</figure>
<p/>
<subsection>Evaluating Ruby Expressions in C</subsection>
<p/>
If you are in the middle of some C code and you want to run an
arbitrary Ruby expression without writing a bunch of C, you can always
use the C version of <tt>eval</tt>. Suppose you have a collection of
objects that need to have a flag cleared.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ rb_eval_string("anObject.each{|x| x.clearFlag }");
]]></fullcode>
rb_eval_string("anObject.each{|x|<nbsp/>x.clearFlag<nbsp/>}");
</alltt>
</codefragment>
<p/>
If you just want to call a particular method (which is cheaper than
<tt>eval</tt>-ing an entire string) you can use
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ rb_funcall(receiver, method_id, argc, ...)
]]></fullcode>
rb_funcall(receiver,<nbsp/>method_id,<nbsp/>argc,<nbsp/>...)
</alltt>
</codefragment>
<p/>
Full descriptions of these and other commonly used C functions begin
on page 189.
<section>Sharing Data Between Ruby and C</section>
<p/>
We've covered enough of the basics now to return to our jukebox
example---interfacing C code with Ruby and sharing data and behavior
between the two worlds.
<subsection>Directly Sharing Variables</subsection>
<p/>
Although you could maintain a C version of some variable along with a
separate Ruby version of that variable, and struggle to keep the two
in sync,<footnote>A clear violation of the <em>DRY</em>--Don't
Repeat Yourself---principle described in our book <em>The Pragmatic
Programmer</em><nbsp/>.</footnote> it would be much better to
share a variable directly between Ruby and C.
You can share global
variables by creating a Ruby object on the C side and then binding
its address to a Ruby global variable. In this case, the $ prefix is
optional, but it helps clarify that this is a global variable.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ VALUE hardware_list;
hardware_list = rb_ary_new();
rb_define_variable("$hardware", &hardware_list);
...
rb_ary_push(hardware_list, rb_str_new2("DVD"));
rb_ary_push(hardware_list, rb_str_new2("CDPlayer1"));
rb_ary_push(hardware_list, rb_str_new2("CDPlayer2"));
]]></fullcode>
VALUE<nbsp/>hardware_list;
hardware_list<nbsp/>=<nbsp/>rb_ary_new();
rb_define_variable("$hardware",<nbsp/>&hardware_list);
...
rb_ary_push(hardware_list,<nbsp/>rb_str_new2("DVD"));
rb_ary_push(hardware_list,<nbsp/>rb_str_new2("CDPlayer1"));
rb_ary_push(hardware_list,<nbsp/>rb_str_new2("CDPlayer2"));
</alltt>
</codefragment>
<p/>
The Ruby side can then access the C variable <tt>hardware_list</tt> as
<tt>$hardware</tt>:
<p/>
<codefragment>
<fullcode><![CDATA[!- $hardware = [ "DVD", "CDPlayer1", "CDPlayer2" ]
$hardware
]]></fullcode><rubycode>
<tr>
<td><tt>$hardware</tt></td>
<td>»</td>
<td><tt>["DVD",<nbsp/>"CDPlayer1",<nbsp/>"CDPlayer2"]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
You can also create <em>hooked</em>
variables that will call a specified function when the variable is
accessed, and <em>virtual</em> variables that only call the hooks---no
actual variable is involved. See the API section that begins
on page 192 for details.
<p/>
If you create a Ruby object from C and store it in a C global
variable
<em>without</em> exporting it to Ruby, you must at least tell the
garbage collector about it, lest ye be reaped inadvertently:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ VALUE obj;
obj = rb_ary_new();
rb_global_variable(obj);
]]></fullcode>
VALUE<nbsp/>obj;
obj<nbsp/>=<nbsp/>rb_ary_new();
rb_global_variable(obj);
</alltt>
</codefragment>
<subsection>Wrapping C Structures</subsection>
Now on to the <em>really</em> fun stuff. We've got the vendor's
library that controls the audio CD jukebox units, and we're ready to
wire it into Ruby. The vendor's header file looks like this:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[typedef struct _cdjb {
int statusf;
int request;
void *data;
char pending;
int unit_id;
void *stats;
} CDJukebox;
// Allocate a new CDPlayer structure and bring it online
CDJukebox *CDPlayerNew(int unit_id);
// Deallocate when done (and take offline)
void CDPlayerDispose(CDJukebox *rec);
// Seek to a disc, track and notify progress
void CDPlayerSeek(CDJukebox *rec,
int disc,
int track,
void (*done)(CDJukebox *rec, int percent));
// ... others...
// Report a statistic
double CDPlayerAvgSeekTime(CDJukebox *rec);
]]></fullcode>
typedef<nbsp/>struct<nbsp/>_cdjb<nbsp/>{
<nbsp/><nbsp/>int<nbsp/>statusf;
<nbsp/><nbsp/>int<nbsp/>request;
<nbsp/><nbsp/>void<nbsp/>*data;
<nbsp/><nbsp/>char<nbsp/>pending;
<nbsp/><nbsp/>int<nbsp/>unit_id;
<nbsp/><nbsp/>void<nbsp/>*stats;
}<nbsp/>CDJukebox;
<p/>
//<nbsp/>Allocate<nbsp/>a<nbsp/>new<nbsp/>CDPlayer<nbsp/>structure<nbsp/>and<nbsp/>bring<nbsp/>it<nbsp/>online
CDJukebox<nbsp/>*CDPlayerNew(int<nbsp/>unit_id);
<p/>
//<nbsp/>Deallocate<nbsp/>when<nbsp/>done<nbsp/>(and<nbsp/>take<nbsp/>offline)
void<nbsp/>CDPlayerDispose(CDJukebox<nbsp/>*rec);
<p/>
//<nbsp/>Seek<nbsp/>to<nbsp/>a<nbsp/>disc,<nbsp/>track<nbsp/>and<nbsp/>notify<nbsp/>progress
void<nbsp/>CDPlayerSeek(CDJukebox<nbsp/>*rec,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>int<nbsp/>disc,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>int<nbsp/>track,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>void<nbsp/>(*done)(CDJukebox<nbsp/>*rec,<nbsp/>int<nbsp/>percent));
//<nbsp/>...<nbsp/>others...
//<nbsp/>Report<nbsp/>a<nbsp/>statistic
double<nbsp/>CDPlayerAvgSeekTime(CDJukebox<nbsp/>*rec);
</alltt>
</codefragment>
<p/>
This vendor has its act together; while the vendor might not admit it, the
code is written with an object-oriented flavor. We don't know what
all those fields mean within the <tt>CDJukeBox</tt> structure, but that's
okay---we can treat it as an opaque pile of bits. The vendor's code
knows what to do with it, we just have to carry it around.
<p/>
Anytime you have a C-only structure that you would like to handle as a
Ruby object, you should wrap it in a special, internal Ruby class
called <tt>DATA</tt> (type <tt>T_DATA</tt>).
There are two macros to do this wrapping, and one to retrieve your
structure back out again.
<p/>
<table>
<cdoctitle>C Datatype Wrapping</cdoctitle>
<cfunc name="Data_Wrap_Struct">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>class, void<nbsp/>(*mark)(),
void<nbsp/>(*free)(), void<nbsp/>*ptr"</cparams>
<cbody> Wraps the given C datatype <em>ptr</em>, registers the
two garbage collection routines (see below), and returns
a VALUE pointer to a genuine Ruby object. The C type of the
resulting object is <tt>T_DATA</tt> and its Ruby class is <em>class</em>.
</cbody>
</cfunc>
<cfunc name="Data_Make_Struct">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>class, <em>c-type</em>,
void<nbsp/>(*mark)(), void<nbsp/>(*free)(), <em>c-type *</em>"</cparams>
<cbody> Allocates a structure of the indicated
type first, then proceeds as <tt>Data_Wrap_Struct</tt>. <em>c-type</em>
is the name of the C datatype that you're wrapping, not a
variable of that type.
</cbody>
</cfunc>
<cfunc name="Data_Get_Struct">
<creturns></creturns>
<cparams>VALUE<nbsp/>obj,<em>c-type</em>,<em>c-type *</em>"</cparams>
<cbody> Returns the original pointer. This macro
is a type-safe wrapper around the macro
<tt>DATA_PTR(obj)</tt>, which evaluates the pointer.
</cbody>
</cfunc>
<p/>
</table>
<p/>
The object created by <tt>Data_Wrap_Struct</tt> is a normal Ruby object,
except that it has an additional C datatype that can't be accessed
from Ruby. As you can see in Figure 17.1 on page 179, this C
datatype is separate from any instance variables that the object
contains.
But since it's a separate thing, how do you get rid of it when the
garbage collector claims this object? What if you have to release
some resource (close some file, clean up some lock or IPC mechanism,
and so on)?
<figure type="figure">Figure not available...</figure>
<p/>
In order to participate in Ruby's mark-and-sweep garbage collection process,
you need to define a
routine to free your structure, and possibly a routine to mark any
references from your structure to other structures. Both routines take a <tt>void</tt>
pointer, a reference to your structure.
The <em>mark</em> routine will be called by the garbage collector
during its ``mark'' phase. If your structure references other Ruby
objects, then your mark function needs to identify these objects using
<tt>rb_gc_mark(<em>value</em>)</tt>. If the structure doesn't reference
other Ruby objects, you can simply pass <tt>0</tt> as a function pointer.
<p/>
When the object needs to be disposed of, the garbage collector will
call the <em>free</em> routine to free it. If you have allocated any
memory yourself (for instance, by using <tt>Data_Make_Struct</tt>),
you'll need to pass a free function---even if it's just the standard C
library's <tt>free</tt> routine. For complex structures that you have
allocated, your free function may need to traverse the structure to
free all the allocated memory.
<p/>
First a simple example, without any special handling. Given the
structure definition
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ typedef struct mp3info {
char *title;
char *artist;
int genre;
} MP3Info;
]]></fullcode>
typedef<nbsp/>struct<nbsp/>mp3info<nbsp/>{
<nbsp/><nbsp/>char<nbsp/>*title;
<nbsp/><nbsp/>char<nbsp/>*artist;
<nbsp/><nbsp/>int<nbsp/><nbsp/>genre;
}<nbsp/>MP3Info;
</alltt>
</codefragment>
<p/>
we can create a structure, populate it, and wrap it as an
object.<footnote>We cheat a bit in this example. Our <tt>MP3Info</tt>
structure has a couple of <tt>char</tt> pointers in it. In our code we
initialize them from two static strings. This means that we don't
have to free these strings when the <tt>MP3Info</tt> structure is freed.
If we'd allocated these strings dynamically, we'd have to write a
free method to dispose of them.</footnote>
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ MP3Info *p;
VALUE info;
p = ALLOC(MP3Info);
p->artist = "Maynard Ferguson";
p->title = "Chameleon";
...
info = Data_Wrap_Struct(cTest, 0, free, p);
]]></fullcode>
MP3Info<nbsp/>*p;
VALUE<nbsp/>info;
<p/>
p<nbsp/>=<nbsp/>ALLOC(MP3Info);
p->artist<nbsp/>=<nbsp/>"Maynard<nbsp/>Ferguson";
p->title<nbsp/>=<nbsp/>"Chameleon";
...
info<nbsp/>=<nbsp/>Data_Wrap_Struct(cTest,<nbsp/>0,<nbsp/>free,<nbsp/>p);
</alltt>
</codefragment>
<p/>
<tt>info</tt> is a <tt>VALUE</tt> type, a genuine Ruby object of class
<tt>Test</tt> (represented in C by the built-in type <tt>T_DATA</tt>). You
can push it onto an array, hold a reference to it in an object, and so
on. At some later point in the code, we may want to access this
structure again, given the <tt>VALUE</tt>:
<p/>
<codefragment>
<alltt>
VALUE doit(VALUE info) {
MP3Info *p;
Data_Get_Struct(info, MP3Info, p);
...
p->artist <returns>"Maynard Ferguson"</returns>
p->title <returns>"Chameleon"</returns>
...
}
</alltt>
</codefragment>
<p/>
In order to follow convention, however, you may need a few more
things: support for an <meth>initialize</meth> method, and
a ``C-constructor.'' If you
were writing Ruby source, you'd allocate and initialize an object by
calling <meth>new</meth>. In C extensions, the corresponding call is
<tt>Data_Make_Struct</tt>. However, although this allocates memory for
the object, it does <em>not</em> automatically call an <kw>initialize</kw>
method; you need to do that yourself:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ info = Data_Make_Struct(cTest, MP3Info, 0, free, one);
rb_obj_call_init(info, argc, argv);
]]></fullcode>
info<nbsp/>=<nbsp/>Data_Make_Struct(cTest,<nbsp/>MP3Info,<nbsp/>0,<nbsp/>free,<nbsp/>one);
rb_obj_call_init(info,<nbsp/>argc,<nbsp/>argv);
</alltt>
</codefragment>
<p/>
This has the benefit of allowing subclasses in Ruby to override or
augment the basic <kw>initialize</kw> in your class. Within
<kw>initialize</kw>, it is allowable (but not necessarily advisable) to
alter the existing data pointer, which may be accessed directly with
<tt>DATA_PTR(obj)</tt>.
<p/>
And finally, you may want to define a ``C-constructor''---that
is, a globally available C function that will
create the object in one convenient call. You can use this function
within your own code or allow other extension libraries to use it.
All of the built-in classes support this idea with functions such as
<tt>rb_str_new</tt>, <tt>rb_ary_new</tt>, and so on. We can make our own:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ VALUE mp3_info_new() {
VALUE info;
MP3Info *one;
info = Data_Make_Struct(cTest, MP3Info, 0, free, one);
...
rb_obj_call_init(info, 0, 0);
return info;
}
]]></fullcode>
VALUE<nbsp/>mp3_info_new()<nbsp/>{
<nbsp/><nbsp/>VALUE<nbsp/>info;
<nbsp/><nbsp/>MP3Info<nbsp/>*one;
<nbsp/><nbsp/>info<nbsp/>=<nbsp/>Data_Make_Struct(cTest,<nbsp/>MP3Info,<nbsp/>0,<nbsp/>free,<nbsp/>one);
<nbsp/><nbsp/>...
<nbsp/><nbsp/>rb_obj_call_init(info,<nbsp/>0,<nbsp/>0);
<nbsp/><nbsp/>return<nbsp/>info;
}
</alltt>
</codefragment>
<subsection>An Example</subsection>
<p/>
Okay, now we're ready for a full-size example.
Given our vendor's header file above, we write the following code.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[#include "ruby.h"
#include "cdjukebox.h"
VALUE cCDPlayer;
static void cd_free(void *p) {
CDPlayerDispose(p);
}
static void progress(CDJukebox *rec, int percent)
{
if (rb_block_given_p()) {
if (percent > 100) percent = 100;
if (percent < 0) percent = 0;
rb_yield(INT2FIX(percent));
}
}
static VALUE
cd_seek(VALUE self, VALUE disc, VALUE track)
{
CDJukebox *ptr;
Data_Get_Struct(self, CDJukebox, ptr);
CDPlayerSeek(ptr,
NUM2INT(disc),
NUM2INT(track),
progress);
return Qnil;
}
static VALUE
cd_seekTime(VALUE self)
{
double tm;
CDJukebox *ptr;
Data_Get_Struct(self, CDJukebox, ptr);
tm = CDPlayerAvgSeekTime(ptr);
return rb_float_new(tm);
}
static VALUE
cd_unit(VALUE self)
{
return rb_iv_get(self, "@unit");
}
static VALUE
cd_init(VALUE self, VALUE unit)
{
rb_iv_set(self, "@unit", unit);
return self;
}
VALUE cd_new(VALUE class, VALUE unit)
{
VALUE argv[1];
CDJukebox *ptr = CDPlayerNew(NUM2INT(unit));
VALUE tdata = Data_Wrap_Struct(class, 0, cd_free, ptr);
argv[0] = unit;
rb_obj_call_init(tdata, 1, argv);
return tdata;
}
void Init_CDJukebox() {
cCDPlayer = rb_define_class("CDPlayer", rb_cObject);
rb_define_singleton_method(cCDPlayer, "new", cd_new, 1);
rb_define_method(cCDPlayer, "initialize", cd_init, 1);
rb_define_method(cCDPlayer, "seek", cd_seek, 2);
rb_define_method(cCDPlayer, "seekTime", cd_seekTime, 0);
rb_define_method(cCDPlayer, "unit", cd_unit, 0);
}
]]></fullcode>
#include<nbsp/>"ruby.h"
#include<nbsp/>"cdjukebox.h"
<p/>
VALUE<nbsp/>cCDPlayer;
<p/>
static<nbsp/>void<nbsp/>cd_free(void<nbsp/>*p)<nbsp/>{
<nbsp/><nbsp/>CDPlayerDispose(p);
}
<p/>
static<nbsp/>void<nbsp/>progress(CDJukebox<nbsp/>*rec,<nbsp/>int<nbsp/>percent)
{
<nbsp/><nbsp/>if<nbsp/>(rb_block_given_p())<nbsp/>{
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>(percent<nbsp/>><nbsp/>100)<nbsp/>percent<nbsp/>=<nbsp/>100;
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>(percent<nbsp/><<nbsp/>0)<nbsp/>percent<nbsp/>=<nbsp/>0;
<nbsp/><nbsp/><nbsp/><nbsp/>rb_yield(INT2FIX(percent));
<nbsp/><nbsp/>}
}
<p/>
static<nbsp/>VALUE
cd_seek(VALUE<nbsp/>self,<nbsp/>VALUE<nbsp/>disc,<nbsp/>VALUE<nbsp/>track)
{
<nbsp/><nbsp/>CDJukebox<nbsp/>*ptr;
<nbsp/><nbsp/>Data_Get_Struct(self,<nbsp/>CDJukebox,<nbsp/>ptr);
<p/>
<nbsp/><nbsp/>CDPlayerSeek(ptr,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>NUM2INT(disc),
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>NUM2INT(track),
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>progress);
<nbsp/><nbsp/>return<nbsp/>Qnil;
}
<p/>
static<nbsp/>VALUE
cd_seekTime(VALUE<nbsp/>self)
{
<nbsp/><nbsp/>double<nbsp/>tm;
<nbsp/><nbsp/>CDJukebox<nbsp/>*ptr;
<nbsp/><nbsp/>Data_Get_Struct(self,<nbsp/>CDJukebox,<nbsp/>ptr);
<nbsp/><nbsp/>tm<nbsp/>=<nbsp/>CDPlayerAvgSeekTime(ptr);
<nbsp/><nbsp/>return<nbsp/>rb_float_new(tm);
}
<p/>
static<nbsp/>VALUE
cd_unit(VALUE<nbsp/>self)
{
<nbsp/><nbsp/>return<nbsp/>rb_iv_get(self,<nbsp/>"@unit");
}
<p/>
static<nbsp/>VALUE
cd_init(VALUE<nbsp/>self,<nbsp/>VALUE<nbsp/>unit)
{
<nbsp/><nbsp/>rb_iv_set(self,<nbsp/>"@unit",<nbsp/>unit);
<nbsp/><nbsp/>return<nbsp/>self;
}
<p/>
VALUE<nbsp/>cd_new(VALUE<nbsp/>class,<nbsp/>VALUE<nbsp/>unit)
{
<nbsp/><nbsp/>VALUE<nbsp/>argv[1];
<nbsp/><nbsp/>CDJukebox<nbsp/>*ptr<nbsp/>=<nbsp/>CDPlayerNew(NUM2INT(unit));
<nbsp/><nbsp/>VALUE<nbsp/>tdata<nbsp/>=<nbsp/>Data_Wrap_Struct(class,<nbsp/>0,<nbsp/>cd_free,<nbsp/>ptr);
<nbsp/><nbsp/>argv[0]<nbsp/>=<nbsp/>unit;
<nbsp/><nbsp/>rb_obj_call_init(tdata,<nbsp/>1,<nbsp/>argv);
<nbsp/><nbsp/>return<nbsp/>tdata;
}
<p/>
void<nbsp/>Init_CDJukebox()<nbsp/>{
<nbsp/><nbsp/>cCDPlayer<nbsp/>=<nbsp/>rb_define_class("CDPlayer",<nbsp/>rb_cObject);
<nbsp/><nbsp/>rb_define_singleton_method(cCDPlayer,<nbsp/>"new",<nbsp/>cd_new,<nbsp/>1);
<nbsp/><nbsp/>rb_define_method(cCDPlayer,<nbsp/>"initialize",<nbsp/>cd_init,<nbsp/>1);
<nbsp/><nbsp/>rb_define_method(cCDPlayer,<nbsp/>"seek",<nbsp/>cd_seek,<nbsp/>2);
<nbsp/><nbsp/>rb_define_method(cCDPlayer,<nbsp/>"seekTime",<nbsp/>cd_seekTime,<nbsp/>0);
<nbsp/><nbsp/>rb_define_method(cCDPlayer,<nbsp/>"unit",<nbsp/>cd_unit,<nbsp/>0);
}
</alltt>
</codefragment>
<p/>
Now we have the ability to control our jukebox from Ruby in a nice,
object-oriented manner:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ require "code/ext/CDJukebox"
p = CDPlayer.new(1)
puts "Unit is #{p.unit}"
p.seek(3, 16) {|x| puts "#{x}% done" }
puts "Avg. time was #{p.seekTime} seconds"
]]></fullcode>
require<nbsp/>"code/ext/CDJukebox"
p<nbsp/>=<nbsp/>CDPlayer.new(1)
puts<nbsp/>"Unit<nbsp/>is<nbsp/>#{p.unit}"
p.seek(3,<nbsp/>16)<nbsp/>{|x|<nbsp/>puts<nbsp/>"#{x}%<nbsp/>done"<nbsp/>}
puts<nbsp/>"Avg.<nbsp/>time<nbsp/>was<nbsp/>#{p.seekTime}<nbsp/>seconds"
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Unit<nbsp/>is<nbsp/>1
26%<nbsp/>done
79%<nbsp/>done
100%<nbsp/>done
Avg.<nbsp/>time<nbsp/>was<nbsp/>1.2<nbsp/>seconds
</alltt>
</codefragment>
<p/>
This example demonstrates most of what we've talked about so far, with
one additional neat feature. The vendor's library provided a callback
routine---a function pointer that is called every so often while the
hardware is grinding its way to the next disc. We've set that up here
to run a code block passed as an argument to <tt>seek</tt>. In the
<tt>progress</tt> function, we check to see if there is an iterator in the
current context and, if there is, run it
with the current percent done as an argument.
<section>Memory Allocation</section>
<p/>
You may sometimes need to allocate memory in an extension that
won't be used for object storage---perhaps you've got a giant bitmap
for a Bloom filter, or an image, or a whole bunch of little structures
that Ruby doesn't use directly.
<p/>
In order to work correctly with the garbage collector, you should use
the following memory allocation routines. These routines do a little
bit more work than the standard <tt>malloc</tt>. For instance, if
<tt>ALLOC_N</tt> determines that it cannot allocate the desired amount of
memory, it will invoke the garbage collector to try to reclaim some
space. It will raise a
<exception>NoMemError</exception> if it can't or if the requested amount of memory is
invalid.
<p/>
<table>
<cdoctitle>Memory Allocation</cdoctitle>
<cfunc name="ALLOC_N">
<creturns><em>type *</em></creturns>
<cparams><em>c-type</em>, n"</cparams>
<cbody> Allocates <em>n</em> <em>c-type</em> objects, where <em>c-type</em> is
the literal name of the C type, not a variable of that type.</cbody>
</cfunc>
<cfunc name="ALLOC">
<creturns><em>type *</em></creturns>
<cparams><em>c-type</em>"</cparams>
<cbody> Allocates a <em>c-type</em> and casts the result to a pointer of
that type.</cbody>
</cfunc>
<cfunc name="REALLOC_N">
<creturns></creturns>
<cparams><em>var</em>, <em>c-type</em>, n"</cparams>
<cbody> Reallocates <em>n</em> <em>c-type</em>s and assigns the result to <em>var</em>,
a pointer to a <em>c-type</em>.</cbody>
</cfunc>
<cfunc name="ALLOCA_N">
<creturns><em>type *</em></creturns>
<cparams><em>c-type</em>, n"</cparams>
<cbody> Allocates memory for <em>n</em> objects of <em>c-type</em> on the
stack---this memory will be automatically freed when the function
that invokes <tt>ALLOCA_N</tt> returns.</cbody>
</cfunc>
<p/>
</table>
<section>Creating an Extension</section>
<p/>
Having written the source code for an extension, we now need to compile
it so Ruby can use it. We can either do this as a shared
object, which is dynamically loaded at runtime, or statically link
the extension into the main Ruby interpreter itself. The basic
procedure is the same:
<ul>
<li> Create the C source code file(s) in a given directory.
</li><li> Create <tt>extconf.rb</tt>.
</li><li> Run <tt>extconf.rb</tt> to create a <tt>Makefile</tt> for the C files in
this directory.
</li><li> Run <tt>make</tt>.
</li><li> Run <tt>make install</tt>.
</li></ul>
<figure type="figure">Figure not available...</figure>
<p/>
<subsection>Creating a Makefile with extconf.rb</subsection>
<p/>
Figure 17.2 on page 184 shows the overall workflow when building an
extension.
The key to the whole process is the <tt>extconf.rb</tt>
program which you, as a developer, create. In <tt>extconf.rb</tt>, you
write a simple program that determines what features are available on
the user's system and where those features may be located. Executing
<tt>extconf.rb</tt> builds a customized
<tt>Makefile</tt>, tailored for both your application and the system on
which it's being compiled. When you run the <tt>make</tt> command against
this <tt>Makefile</tt>, your extension is built and (optionally) installed.
<p/>
The simplest <tt>extconf.rb</tt> may be just two lines long, and for many
extensions this is sufficient.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ require 'mkmf'
create_makefile("Test")
]]></fullcode>
require<nbsp/>'mkmf'
create_makefile("Test")
</alltt>
</codefragment>
<p/>
The first line brings in the <classname>mkmf</classname> library module
(documented beginning on page 455). This contains all the
commands we'll be using. The second line creates a <tt>Makefile</tt> for an
extension called ``Test.'' (Note that ``Test'' is the name of the
extension; the makefile will always be called ``Makefile.'')
<tt>Test</tt> will be built from all the C source files in the
current directory.
<p/>
Let's say that we run this <tt>extconf.rb</tt> program in a directory
containing a single source file, <tt>main.c</tt>. The
result is a <tt>Makefile</tt> that will build our extension. On our system,
this contains the following commands.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ gcc -fPIC -I/usr/local/lib/ruby/1.6/i686-linux -g -O2 \
-c main.c -o main.o
gcc -shared -o Test.so main.o -lc
]]></fullcode>
gcc<nbsp/>-fPIC<nbsp/>-I/usr/local/lib/ruby/1.6/i686-linux<nbsp/>-g<nbsp/>-O2<nbsp/><nbsp/>\
<nbsp/><nbsp/>-c<nbsp/>main.c<nbsp/>-o<nbsp/>main.o
gcc<nbsp/>-shared<nbsp/>-o<nbsp/>Test.so<nbsp/>main.o<nbsp/>-lc
</alltt>
</codefragment>
<p/>
The result of this compilation is <tt>Test.so</tt>, which may be
dynamically linked into Ruby at runtime with ``<tt>require</tt>''. See how
the <tt>mkmf</tt> commands have located platform-specific libraries and
used compiler-specific options automatically. Pretty neat, eh?
<p/>
Although this basic program works for many simple extensions, you may
have to do some more work if your extension needs header files or
libraries that aren't included in the default compilation environment,
or if you conditionally compile code based on the presence of
libraries or functions.
<p/>
A common requirement is to specify nonstandard directories where
include files and libraries may be found. This is a two-step process.
First, your <tt>extconf.rb</tt> should contain one or more
<meth>dir_config</meth> commands.
This specifies a tag for a set of directories. Then, when you run the
<tt>extconf.rb</tt> program, you tell <tt>mkmf</tt> where the corresponding
physical directories are on the current system.
<p/>
If <tt>extconf.rb</tt> contains the line <tt>dir_config(</tt><em>name</em><tt>)</tt>,
then you give the location of the corresponding directories with the
command-line options:
<p/>
<dl>
<dt><tt>--with-<em>name</em>-include=<em>directory</em></tt></dt><dd><br/>*
Add <em>directory</em>/<tt>include</tt> to the compile command.
</dd><dt><tt>--with-<em>name</em>-lib=<em>directory</em></tt></dt><dd><br/>*
Add <em>directory</em>/<tt>lib</tt> to the link command.
</dd></dl>
<p/>
If (as is common) your include and library directories are both
subdirectories of some other directory, and (as is also common) they're
called <tt>include</tt> and <tt>lib</tt>, you can take a shortcut:
<p/>
<dl>
<dt><tt>--with-<em>name</em>-dir=<em>directory</em></tt></dt><dd><br/>*
Add <em>directory</em>/<tt>lib</tt> and <em>directory</em>/<tt>include</tt> to the link
command and compile command, respectively.
</dd></dl>
<p/>
There's a twist here. As well as specifying all these <tt>--with</tt>
options when you run <tt>extconf.rb</tt>, you can also use the <tt>--with</tt>
options that were specified when Ruby was built for your machine. This
means you can find out the locations of libraries that are used by
Ruby itself.
<p/>
To make all this concrete, lets say you need to use libraries and
include files for the CD jukebox we're developing. Your
<tt>extconf.rb</tt> program might contain
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ require 'mkmf'
dir_config('cdjukebox')
# .. more stuff
create_makefile("CDJukeBox")
]]></fullcode>
require<nbsp/>'mkmf'
dir_config('cdjukebox')
#<nbsp/>..<nbsp/>more<nbsp/>stuff
create_makefile("CDJukeBox")
</alltt>
</codefragment>
<p/>
You'd then run <tt>extconf.rb</tt> with something like:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ % ruby extconf.rb --with-cdjukebox-dir=/usr/local/cdjb
]]></fullcode>
%<nbsp/>ruby<nbsp/>extconf.rb<nbsp/>--with-cdjukebox-dir=/usr/local/cdjb
</alltt>
</codefragment>
<p/>
The generated <tt>Makefile</tt> would assume that the libraries were in
<tt>/usr/local/cdjb/lib</tt> and the include files were in
<tt>/usr/local/cdjb/include</tt>.
<p/>
The <meth>dir_config</meth> command adds to the list of places to search
for libraries and include files. It does not, however, link the
libraries into your application. To do that, you'll need to use one
or more <meth>have_library</meth> or <meth>find_library</meth> commands.
<p/>
<meth>have_library</meth> looks for
a given entry point in a named library. If it finds the entry point,
it adds the library to the list of libraries to be used when linking
your extension.
<meth>find_library</meth> is
similar, but allows you to specify a list of directories to search for
the library.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ require 'mkmf'
dir_config('cdjukebox')
have_library('cdjb', 'CDPlayerNew')
create_makefile("CDJukeBox")
]]></fullcode>
require<nbsp/>'mkmf'
dir_config('cdjukebox')
have_library('cdjb',<nbsp/>'CDPlayerNew')
create_makefile("CDJukeBox")
</alltt>
</codefragment>
<p/>
On some platforms, a popular library may be in one of several places.
The X Window system, for example, is notorious for living in different
directories on different systems. The <tt>find_library</tt> command will
search a list of supplied directories to find the right one (this is
different from <tt>have_library</tt>, which uses only configuration
information for the search). For example, to create a <tt>Makefile</tt>
that uses X Windows and a jpeg library, <tt>extconf.rb</tt> might contain
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ require 'mkmf'
if have_library("jpeg","jpeg_mem_init") and
find_library("X11", "XOpenDisplay", "/usr/X11/lib",
"/usr/X11R6/lib", "/usr/openwin/lib")
then
create_makefile("XThing")
else
puts "No X/JPEG support available"
end
]]></fullcode>
require<nbsp/>'mkmf'
<p/>
if<nbsp/>have_library("jpeg","jpeg_mem_init")<nbsp/>and
<nbsp/><nbsp/><nbsp/>find_library("X11",<nbsp/>"XOpenDisplay",<nbsp/>"/usr/X11/lib",
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"/usr/X11R6/lib",<nbsp/>"/usr/openwin/lib")
then
<nbsp/><nbsp/><nbsp/><nbsp/>create_makefile("XThing")
else
<nbsp/><nbsp/><nbsp/><nbsp/>puts<nbsp/>"No<nbsp/>X/JPEG<nbsp/>support<nbsp/>available"
end
</alltt>
</codefragment>
<p/>
We've added some additional functionality to this program. All of the
<tt>mkmf</tt> commands return <const>false</const> if they fail. This means that
we can write an <tt>extconf.rb</tt> that generates a <tt>Makefile</tt> only if
everything it needs is present. The Ruby distribution does
this so that it will try to compile only those extensions that are supported
on your system.
<p/>
You also may want your extension code to be able to configure the
features it uses depending on the target environment. For example, our
CD jukebox may be able to use a high-performance MP3 decoder if the
end user has one installed. We can check by looking for its header
file.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ require 'mkmf'
dir_config('cdjukebox')
have_library('cdjb', 'CDPlayerNew')
have_header('hp_mp3.h')
create_makefile("CDJukeBox")
]]></fullcode>
require<nbsp/>'mkmf'
dir_config('cdjukebox')
have_library('cdjb',<nbsp/>'CDPlayerNew')
have_header('hp_mp3.h')
create_makefile("CDJukeBox")
</alltt>
</codefragment>
<p/>
We can also check to see if the target environment has a particular
function in any of the libraries we'll be using. For example, the
<meth>setpriority</meth> call would be useful but isn't always
available. We can check for it with:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ require 'mkmf'
dir_config('cdjukebox')
have_func('setpriority')
create_makefile("CDJukeBox")
]]></fullcode>
require<nbsp/>'mkmf'
dir_config('cdjukebox')
have_func('setpriority')
create_makefile("CDJukeBox")
</alltt>
</codefragment>
<p/>
Both <meth>have_header</meth> and <meth>have_func</meth> define
preprocessor constants if they find their targets. The names are
formed by converting the target name to uppercase and prepending
``HAVE_''. Your C code can take advantage of this using constructs
such as:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ #if defined(HAVE_HP_MP3_H)
# include <hp_mp3.h>
#endif
#if defined(HAVE_SETPRIORITY)
err = setpriority(PRIOR_PROCESS, 0, -10)
#endif
]]></fullcode>
#if<nbsp/>defined(HAVE_HP_MP3_H)
#<nbsp/><nbsp/>include<nbsp/><hp_mp3.h>
#endif
<p/>
#if<nbsp/>defined(HAVE_SETPRIORITY)
<nbsp/><nbsp/>err<nbsp/>=<nbsp/>setpriority(PRIOR_PROCESS,<nbsp/>0,<nbsp/>-10)
#endif
</alltt>
</codefragment>
<p/>
If you have special requirements that can't be met with all
these <tt>mkmf</tt> commands, your program can directly add to the global
variables <tt>$CFLAGS</tt> and <tt>$LFLAGS</tt>, which are passed to the
compiler and linker, respectively.
<subsection>Static Linking</subsection>
<p/>
Finally, if your system doesn't support dynamic linking, or if you
have an extension module that you want to have statically linked into
Ruby itself, edit the file <tt>ext/Setup</tt> in
the distribution and add your directory to the list of extensions in
the file, then rebuild Ruby.
The extensions listed in <tt>Setup</tt> will be
statically linked into the Ruby executable. If you want to disable
any dynamic linking, and link all extensions statically, edit
<tt>ext/Setup</tt> to contain the following option.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ option nodynamic
]]></fullcode>
option<nbsp/>nodynamic
</alltt>
</codefragment>
<section>Embedding a Ruby Interpreter</section>
<p/>
In addition to extending Ruby by adding C code, you can also turn the
problem around and embed Ruby itself within your application.
Here's an example.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[#include "ruby.h"
main() {
/* ... our own application stuff ... */
ruby_init();
ruby_script("embedded");
rb_load_file("start.rb");
while (1) {
if (need_to_do_ruby) {
ruby_run();
}
/* ... run our app stuff */
}
}
]]></fullcode>
#include<nbsp/>"ruby.h"
<p/>
main()<nbsp/>{
<nbsp/><nbsp/>/*<nbsp/>...<nbsp/>our<nbsp/>own<nbsp/>application<nbsp/>stuff<nbsp/>...<nbsp/>*/
<nbsp/><nbsp/>ruby_init();
<nbsp/><nbsp/>ruby_script("embedded");
<nbsp/><nbsp/>rb_load_file("start.rb");
<nbsp/><nbsp/>while<nbsp/>(1)<nbsp/>{
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>(need_to_do_ruby)<nbsp/>{
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>ruby_run();
<nbsp/><nbsp/><nbsp/><nbsp/>}
<nbsp/><nbsp/><nbsp/><nbsp/>/*<nbsp/>...<nbsp/>run<nbsp/>our<nbsp/>app<nbsp/>stuff<nbsp/>*/
<nbsp/><nbsp/>}
}
</alltt>
</codefragment>
<p/>
To initialize the Ruby interpreter, you need to call
<tt>ruby_init()</tt>. But on some platforms, you may need to take special
steps before that:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[ #if defined(NT)
NtInitialize(&argc, &argv);
#endif
#if defined(__MACOS__) && defined(__MWERKS__)
argc = ccommand(&argv);
#endif
]]></fullcode>
#if<nbsp/>defined(NT)
<nbsp/><nbsp/>NtInitialize(&argc,<nbsp/>&argv);
#endif
#if<nbsp/>defined(__MACOS__)<nbsp/>&&<nbsp/>defined(__MWERKS__)
<nbsp/><nbsp/>argc<nbsp/>=<nbsp/>ccommand(&argv);
#endif
</alltt>
</codefragment>
<p/>
See <tt>main.c</tt> in the Ruby distribution for any other special defines
or setup needed for your platform.
<p/>
<table>
<cdoctitle>Embedded Ruby API</cdoctitle>
<cfunc name="ruby_init">
<creturns>void</creturns>
<cparams>"</cparams>
<cbody> Sets up and initializes the interpreter. This function should be
called before any other Ruby-related functions.
</cbody>
</cfunc>
<cfunc name="ruby_options">
<creturns>void</creturns>
<cparams>int<nbsp/>argc, char<nbsp/>**argv"</cparams>
<cbody> Gives the Ruby interpreter the command-line options.
</cbody>
</cfunc>
<cfunc name="ruby_script">
<creturns>void</creturns>
<cparams>char<nbsp/>*name"</cparams>
<cbody> Sets the name of the Ruby script (and <kw>$0</kw>) to <em>name</em>.
</cbody>
</cfunc>
<cfunc name="rb_load_file">
<creturns>void</creturns>
<cparams>char<nbsp/>*file"</cparams>
<cbody> Loads the given file into the interpreter.
</cbody>
</cfunc>
<cfunc name="ruby_run">
<creturns>void</creturns>
<cparams>"</cparams>
<cbody> Runs the interpreter.
</cbody>
</cfunc>
<p/>
</table>
<p/>
You need to take some special care with exception handling; any Ruby
calls you make at this top level should be protected to catch
exceptions and handle them cleanly. <tt>rb_protect</tt>, <tt>rb_rescue</tt>, and related
functions are documented on page 194.
<p/>
For an example of embedding a Ruby interpreter within another program,
see also <tt>eruby</tt>, which is described beginning on page 149.
<section>Bridging Ruby to Other Languages</section>
<p/>
So far, we've discussed extending Ruby by adding routines written in C.
However, you can write extensions in just about any language, as long
as you can bridge the two languages with C. Almost anything is
possible, including awkward marriages of Ruby and C++, Ruby and Java,
and so on.
<p/>
But you may be able to accomplish the same thing without resorting to C
code. For example, you could bridge to other languages using
middleware such as CORBA or COM. See the section on Windows automation
beginning on page 166 for more details.
<section>Ruby C Language API</section>
<p/>
Last, but by no means least, here are several C-level functions
that you may find useful when writing an extension.
<p/>
Some functions require an <tt>ID</tt>: you can
obtain an <tt>ID</tt> for a string by using <tt>rb_intern</tt> and
reconstruct the name from an <tt>ID</tt> by using <tt>rb_id2name</tt>.
<p/>
As most of these C functions have Ruby equivalents that are already
described in detail elsewhere in this book, the descriptions here will
be brief.
<p/>
Also note that the following listing is not complete. There are many more
functions available---too many to document them all, as it turns out.
If you need a method that you can't find here, check ``<tt>ruby.h</tt>'' or
``<tt>intern.h</tt>'' for likely candidates. Also, at or near the bottom
of each source file is a set of method definitions that describe the
binding from Ruby methods to C functions. You may be able to call the
C function directly, or search for a wrapper function that calls the
function you are looking for. The following list, based on the list
in <tt>README.EXT</tt>, shows the main source
files in the interpreter.
<p/>
<dl>
<dt>Ruby Language Core</dt><dd><br/>class.c error.c eval.c gc.c object.c parse.y variable.c
</dd><dt>Utility Functions</dt><dd><br/>dln.c regex.c st.c util.c
</dd><dt>Ruby Interpreter</dt><dd><br/>dmyext.c inits.c keywords main.c ruby.c version.c
</dd><dt>Base Library</dt><dd><br/>array.c bignum.c compar.c dir.c enum.c file.c hash.c io.c marshal.c math.c numeric.c pack.c prec.c process.c random.c range.c re.c signal.c sprintf.c string.c struct.c time.c
</dd></dl>
<p/>
<table>
<cdoctitle>Defining Objects</cdoctitle>
<cfunc name="rb_define_class">
<creturns>VALUE</creturns>
<cparams>char<nbsp/>*name, VALUE<nbsp/>superclass"</cparams>
<cbody> Defines a new class at the top level with the given <em>name</em> and
<em>superclass</em> (for class <tt>Object</tt>, use <tt>rb_cObject</tt>).
</cbody>
</cfunc>
<cfunc name="rb_define_module">
<creturns>VALUE</creturns>
<cparams>char<nbsp/>*name"</cparams>
<cbody> Defines a new module at the top level with the given <em>name</em>.
</cbody>
</cfunc>
<cfunc name="rb_define_class_under">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>under, char<nbsp/>*name,
VALUE<nbsp/>superclass"</cparams>
<cbody> Defines a nested class under the class or module <em>under</em>.
</cbody>
</cfunc>
<cfunc name="rb_define_module_under">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>under, char<nbsp/>*name"</cparams>
<cbody> Defines a nested module under the class or module <em>under</em>.
</cbody>
</cfunc>
<cfunc name="rb_include_module">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>parent, VALUE<nbsp/>module"</cparams>
<cbody> Includes the given <em>module</em> into the class or module
<em>parent</em>.
</cbody>
</cfunc>
<cfunc name="rb_extend_object">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>obj, VALUE<nbsp/>module"</cparams>
<cbody> Extends <em>obj</em> with <em>module</em>.
</cbody>
</cfunc>
<cfunc name="rb_require">
<creturns>VALUE</creturns>
<cparams>const<nbsp/>char<nbsp/>*name"</cparams>
<cbody> Equivalent to ``<kw>require</kw> <em>name</em>.''
Returns <tt>Qtrue</tt> or <tt>Qfalse</tt>.
</cbody>
</cfunc>
<p/>
</table>
<p/>
In some of the function definitions that follow, the parameter
<em>argc</em> specifies how many arguments a Ruby method takes. It
may have the following values.
<p/>
<table>
<th>
<td><b><em>argc</em></b></td>
<td><b>Function prototype</b></td>
</th>
<tr>
<td>0..17</td>
<td><tt>VALUE func(VALUE self, VALUE arg...)</tt></td>
</tr>
<tr>
<td></td>
<td>The C function will be called with this many actual arguments.</td>
</tr>
<tr>
<td>-1</td>
<td><tt>VALUE func(int argc, VALUE *argv, VALUE self)</tt></td>
</tr>
<tr>
<td></td>
<td>The C function will be given a variable number of arguments passed
as a C array.</td>
</tr>
<tr>
<td>-2</td>
<td><tt>VALUE func(VALUE self, VALUE args)</tt></td>
</tr>
<tr>
<td></td>
<td>The C function will be given a variable number of arguments
passed as a Ruby array.</td>
</tr>
<bottomrule/></table>
<p/>
In a function that has been given a variable number of arguments,
you can use the C function <tt>rb_scan_args</tt> to sort things out (see below).
<p/>
<table>
<cdoctitle>Defining Methods</cdoctitle>
<cfunc name="rb_define_method">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>classmod, char<nbsp/>*name,
VALUE(*func)(), int<nbsp/>argc"</cparams>
<cbody> Defines an instance method in the class or module <em>classmod</em> with the given <em>name</em>, implemented
by the C function <em>func</em> and taking <em>argc</em> arguments.
</cbody>
</cfunc>
<cfunc name="rb_define_module_function">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>classmod, char<nbsp/>*name,
VALUE(*func)(), int<nbsp/>argc)"</cparams>
<cbody> Defines a method in class <em>classmod</em> with the given <em>name</em>, implemented
by the C function <em>func</em> and taking <em>argc</em> arguments.
</cbody>
</cfunc>
<cfunc name="rb_define_global_function">
<creturns>void</creturns>
<cparams>char<nbsp/>*name, VALUE(*func)(),
int<nbsp/>argc"</cparams>
<cbody> Defines a global function (a private method of <modulename>Kernel</modulename>) with the given <em>name</em>, implemented
by the C function <em>func</em> and taking <em>argc</em> arguments.
</cbody>
</cfunc>
<cfunc name="rb_define_singleton_method">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>classmod, char<nbsp/>*name,
VALUE(*func)(), int<nbsp/>argc"</cparams>
<cbody> Defines a singleton method in class <em>classmod</em> with the given <em>name</em>, implemented
by the C function <em>func</em> and taking <em>argc</em> arguments.
</cbody>
</cfunc>
<cfunc name="rb_scan_args">
<creturns>int</creturns>
<cparams>int<nbsp/>argcount, VALUE<nbsp/>*argv, char<nbsp/>*fmt, ..."</cparams>
<cbody>
Scans the argument list and assigns to variables similar to
<tt>scanf</tt>: <em>fmt</em> is a string containing zero, one, or two
digits followed by some flag characters.
The first digit indicates the count of
mandatory arguments; the second is the count of optional
arguments. A ``*'' means to pack the rest of the arguments into a
Ruby array. A ``&'' means that an attached code block will be
taken and assigned to the given variable (if no code block was
given, <tt>Qnil</tt> will be assigned).
After the <em>fmt</em> string, pointers to <tt>VALUE</tt>
are given (as with <tt>scanf</tt>) to which the arguments are
assigned.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[VALUE name, one, two, rest;
rb_scan_args(argc, argv, "12", &name, &one, &two);
rb_scan_args(argc, argv, "1*", &name, &rest);
]]></fullcode>
VALUE<nbsp/>name,<nbsp/>one,<nbsp/>two,<nbsp/>rest;
rb_scan_args(argc,<nbsp/>argv,<nbsp/>"12",<nbsp/>&name,<nbsp/>&one,<nbsp/>&two);
rb_scan_args(argc,<nbsp/>argv,<nbsp/>"1*",<nbsp/>&name,<nbsp/>&rest);
</alltt>
</codefragment>
</cbody>
</cfunc>
<p/>
<cfunc name="rb_undef_method">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>classmod, const<nbsp/>char<nbsp/>*name"</cparams>
<cbody> Undefines the given method <em>name</em> in the given <em>classmod</em>
class or module.
</cbody>
</cfunc>
<cfunc name="rb_define_alias">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>classmod, const<nbsp/>char<nbsp/>*newname,
const<nbsp/>char<nbsp/>*oldname"</cparams>
<cbody> Defines an alias for <em>oldname</em> in class or module
<em>classmod</em>.
</cbody>
</cfunc>
<p/>
</table>
<p/>
<table>
<cdoctitle>Defining Variables and Constants</cdoctitle>
<cfunc name="rb_define_const">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>classmod, char<nbsp/>*name, VALUE<nbsp/>value"</cparams>
<cbody> Defines a constant in the class or module <em>classmod</em>, with the
given <em>name</em> and <em>value</em>.
</cbody>
</cfunc>
<cfunc name="rb_define_global_const">
<creturns>void</creturns>
<cparams>char<nbsp/>*name, VALUE<nbsp/>value"</cparams>
<cbody> Defines a global constant with the
given <em>name</em> and <em>value</em>.
</cbody>
</cfunc>
<p/>
<cfunc name="rb_define_variable">
<creturns>void</creturns>
<cparams>const<nbsp/>char<nbsp/>*name, VALUE<nbsp/>*object"</cparams>
<cbody> Exports the address of the given <em>object</em> that was created
in C to the Ruby namespace as <em>name</em>. From Ruby, this will
be a global variable, so <em>name</em> should start with a leading
dollar sign. Be sure to honor Ruby's rules for allowed variable
names; illegally named variables will not be accessible from Ruby.
</cbody>
</cfunc>
<p/>
<cfunc name="rb_define_class_variable">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>class, const<nbsp/>char<nbsp/>*name,
VALUE<nbsp/>val"</cparams>
<cbody> Defines a class variable <em>name</em>
(which must be specified with a ``<tt>@@</tt>'' prefix) in the given
<em>class</em>, initialized to <em>value</em>.
</cbody>
</cfunc>
<p/>
<cfunc name="rb_define_virtual_variable">
<creturns>void</creturns>
<cparams>const<nbsp/>char<nbsp/>*name,
VALUE(*getter)(), void(*setter)()"</cparams>
<cbody>
Exports a virtual variable to Ruby namespace as the global
$<em>name</em>. No
actual storage exists for the variable; attempts to get and set
the value will call the given functions with the prototypes:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[VALUE getter(ID id, VALUE *data,
struct global_entry *entry);
void setter(VALUE value, ID id, VALUE *data,
struct global_entry *entry);
]]></fullcode>
VALUE<nbsp/>getter(ID<nbsp/>id,<nbsp/>VALUE<nbsp/>*data,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>struct<nbsp/>global_entry<nbsp/>*entry);
void<nbsp/>setter(VALUE<nbsp/>value,<nbsp/>ID<nbsp/>id,<nbsp/>VALUE<nbsp/>*data,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>struct<nbsp/>global_entry<nbsp/>*entry);
</alltt>
</codefragment>
<p/>
You will likely not need to use the <em>entry</em> parameter
and can safely omit it from your function
declarations.
</cbody>
</cfunc>
<p/>
<cfunc name="rb_define_hooked_variable">
<creturns>void</creturns>
<cparams>const<nbsp/>char<nbsp/>*name,
VALUE<nbsp/>*variable, VALUE(*getter)(), void(*setter)()"</cparams>
<cbody> Defines functions to be called when reading or writing to
<em>variable</em>. See also <tt>rb_define_virtual_variable</tt>.
</cbody>
</cfunc>
<cfunc name="rb_define_readonly_variable">
<creturns>void</creturns>
<cparams>const<nbsp/>char<nbsp/>*name,
VALUE<nbsp/>*value"</cparams>
<cbody> Same as <kw>rb_define_variable</kw>, but read-only from Ruby.
</cbody>
</cfunc>
<cfunc name="rb_define_attr">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>variable, const<nbsp/>char<nbsp/>*name,
int<nbsp/>read, int<nbsp/>write"</cparams>
<cbody> Creates accessor methods for the given <em>variable</em>, with the given
<em>name</em>. If <em>read</em> is nonzero, create a read method; if
<em>write</em> is nonzero, create a write method.
</cbody>
</cfunc>
<cfunc name="rb_global_variable">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>*obj"</cparams>
<cbody> Registers the given address with the garbage collector.</cbody>
</cfunc>
<p/>
</table>
<p/>
<table>
<cdoctitle>Calling Methods</cdoctitle>
<cfunc name="rb_funcall">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>recv, ID<nbsp/>id, int<nbsp/>argc, ..."</cparams>
<cbody> Invokes the method given by <em>id</em> in the object <em>recv</em>
with the given number of arguments <em>argc</em> and the arguments
themselves (possibly none).
</cbody>
</cfunc>
<cfunc name="rb_funcall2">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>recv, ID<nbsp/>id, int<nbsp/>argc, VALUE<nbsp/>*args"</cparams>
<cbody> Invokes the method given by <em>id</em> in the object <em>recv</em>
with the given number of arguments <em>argc</em> and the arguments
themselves given in the C array <em>args</em>.
</cbody>
</cfunc>
<cfunc name="rb_funcall3">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>recv, ID<nbsp/>id, int<nbsp/>argc, VALUE<nbsp/>*args"</cparams>
<cbody> Same as <tt>rb_funcall2</tt>, but will not call private methods.
</cbody>
</cfunc>
<p/>
<cfunc name="rb_apply">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>recv, ID<nbsp/>name, int<nbsp/>argc, VALUE<nbsp/>args"</cparams>
<cbody> Invokes the method given by <em>id</em> in the object <em>recv</em>
with the given number of arguments <em>argc</em> and the arguments
themselves given in the Ruby <classname>Array</classname> <em>args</em>.
</cbody>
</cfunc>
<cfunc name="rb_intern">
<creturns>ID</creturns>
<cparams>char<nbsp/>*name"</cparams>
<cbody> Returns an <kw>ID</kw> for a given <em>name</em>. If the name does not
exist, a symbol table entry will be created for it.
</cbody>
</cfunc>
<cfunc name="rb_id2name">
<creturns>char *</creturns>
<cparams>ID<nbsp/>id"</cparams>
<cbody> Returns a name for the given <em>id</em>.
</cbody>
</cfunc>
<cfunc name="rb_call_super">
<creturns>VALUE</creturns>
<cparams>int<nbsp/>argc, VALUE<nbsp/>*args"</cparams>
<cbody> Calls the current method in the superclass of the current object.
</cbody>
</cfunc>
<p/>
</table>
<p/>
<table>
<cdoctitle>Exceptions</cdoctitle>
<cfunc name="rb_raise">
<creturns>void</creturns>
<cparams>VALUE exception, const<nbsp/>char<nbsp/>*fmt, ..."</cparams>
<cbody> Raises an <em>exception</em>.
The given string <em>fmt</em> and remaining arguments
are interpreted as with <kw>printf</kw>.
</cbody>
</cfunc>
<cfunc name="rb_fatal">
<creturns>void</creturns>
<cparams>const<nbsp/>char<nbsp/>*fmt, ..."</cparams>
<cbody> Raises a <exception>Fatal</exception> exception, terminating the process. No
rescue blocks are called, but ensure blocks will be called.
The given string <em>fmt</em> and remaining arguments
are interpreted as with <kw>printf</kw>.
</cbody>
</cfunc>
<cfunc name="rb_bug">
<creturns>void</creturns>
<cparams>const<nbsp/>char<nbsp/>*fmt, ..."</cparams>
<cbody> Terminates the process immediately---no handlers of any sort will
be called.
The given string <em>fmt</em> and remaining arguments
are interpreted as with <kw>printf</kw>.
You should call this function only if a fatal bug
has been exposed. You don't write fatal bugs, do you?
</cbody>
</cfunc>
<cfunc name="rb_sys_fail">
<creturns>void</creturns>
<cparams>const<nbsp/>char<nbsp/>*msg"</cparams>
<cbody> Raises a platform-specific exception corresponding to the last
known system error, with the given <em>msg</em>.
</cbody>
</cfunc>
<cfunc name="rb_rescue">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>(*body)(), VALUE<nbsp/>args,
VALUE(*rescue)(), VALUE<nbsp/>rargs"</cparams>
<cbody> Executes <em>body</em> with the given <em>args</em>. If a
<exception>StandardError</exception> exception is raised,
then execute <em>rescue</em> with the given <em>rargs</em>.
</cbody>
</cfunc>
<cfunc name="rb_ensure">
<creturns>VALUE</creturns>
<cparams>VALUE(*body)(), VALUE<nbsp/>args,
VALUE(*ensure)(), VALUE<nbsp/>eargs"</cparams>
<cbody> Executes <em>body</em> with the given <em>args</em>. Whether or not an
exception is raised, execute <em>ensure</em> with the given <em>rargs</em>
after <em>body</em> has completed.
</cbody>
</cfunc>
<cfunc name="rb_protect">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>(*body)(), VALUE<nbsp/>args,
int<nbsp/>*result"</cparams>
<cbody> Executes <em>body</em> with the given
<em>args</em> and returns nonzero in <em>result</em> if any exception
was raised.
</cbody>
</cfunc>
<cfunc name="rb_notimplement">
<creturns>void</creturns>
<cparams>"</cparams>
<cbody> Raises a <exception>NotImpError</exception> exception to indicate that the enclosed
function is not implemented yet, or not available on this
platform.
</cbody>
</cfunc>
<cfunc name="rb_exit">
<creturns>void</creturns>
<cparams>int<nbsp/>status"</cparams>
<cbody> Exits Ruby with the given <em>status</em>. Raises a <exception>SystemExit</exception>
exception and calls registered exit functions and
finalizers.
</cbody>
</cfunc>
<cfunc name="rb_warn">
<creturns>void</creturns>
<cparams>const<nbsp/>char<nbsp/>*fmt, ..."</cparams>
<cbody> Unconditionally issues a warning message to standard error.
The given string <em>fmt</em> and remaining arguments
are interpreted as with <kw>printf</kw>.
</cbody>
</cfunc>
<cfunc name="rb_warning">
<creturns>void</creturns>
<cparams>const<nbsp/>char<nbsp/>*fmt, ..."</cparams>
<cbody> Conditionally issues a warning message to standard error if Ruby
was invoked with the <kw>-w</kw> flag.
The given string <em>fmt</em> and remaining arguments
are interpreted as with <kw>printf</kw>.
</cbody>
</cfunc>
<p/>
</table>
<p/>
<table>
<cdoctitle>Iterators</cdoctitle>
<cfunc name="rb_iter_break">
<creturns>void</creturns>
<cparams>"</cparams>
<cbody> Breaks out of the enclosing iterator block.
</cbody>
</cfunc>
<cfunc name="rb_each">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>obj"</cparams>
<cbody> Invokes the <kw>each</kw> method of the given <em>obj</em>.
</cbody>
</cfunc>
<cfunc name="rb_yield">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>arg"</cparams>
<cbody> Transfers execution to the iterator block in the current context,
passing <em>arg</em> as an argument. Multiple values may be passed
in an array.
</cbody>
</cfunc>
<cfunc name="rb_block_given_p">
<creturns>int</creturns>
<cparams>"</cparams>
<cbody> Returns true if <tt>yield</tt> would execute a block in the current
context---that is, if a code block was passed to the current method
and is available to be called.
</cbody>
</cfunc>
<cfunc name="rb_iterate">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>(*method)(), VALUE<nbsp/>args,
VALUE<nbsp/>(*block)(), VALUE<nbsp/>arg2"</cparams>
<cbody> Invokes <em>method</em> with argument <em>args</em> and block
<em>block</em>. A <kw>yield</kw> from that method will invoke
<em>block</em> with the argument given to <kw>yield</kw>, and a second
argument <em>arg2</em>.
</cbody>
</cfunc>
<cfunc name="rb_catch">
<creturns>VALUE</creturns>
<cparams>const<nbsp/>char<nbsp/>*tag, VALUE<nbsp/>(*proc)(), VALUE<nbsp/>value"</cparams>
<cbody> Equivalent to Ruby <tt>catch</tt>.
</cbody>
</cfunc>
<cfunc name="rb_throw">
<creturns>void</creturns>
<cparams>const<nbsp/>char<nbsp/>*tag , VALUE<nbsp/>value"</cparams>
<cbody> Equivalent to Ruby <tt>throw</tt>.
</cbody>
</cfunc>
<p/>
</table>
<p/>
<table>
<cdoctitle>Accessing Variables</cdoctitle>
<cfunc name="rb_iv_get">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>obj, char<nbsp/>*name"</cparams>
<cbody> Returns the instance variable <em>name</em> (which must be specified
with a ``<tt>@</tt>'' prefix) from the given <em>obj</em>.
</cbody>
</cfunc>
<cfunc name="rb_ivar_get">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>obj, ID<nbsp/>name"</cparams>
<cbody> Returns the instance variable <em>name</em> from the given <em>obj</em>.
</cbody>
</cfunc>
<cfunc name="rb_iv_set">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>obj, char<nbsp/>*name, VALUE<nbsp/>value"</cparams>
<cbody> Sets the value of the instance variable <em>name</em> (which must be
specified with a ``<tt>@</tt>'' prefix) in the given <em>obj</em> to
<em>value</em>. Returns <em>value</em>.
</cbody>
</cfunc>
<cfunc name="rb_ivar_set">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>obj, ID<nbsp/>name, VALUE<nbsp/>value"</cparams>
<cbody> Sets the value of the instance variable <em>name</em>
in the given <em>obj</em> to <em>value</em>. Returns
<em>value</em>.
</cbody>
</cfunc>
<cfunc name="rb_gv_set">
<creturns>VALUE</creturns>
<cparams>const<nbsp/>char<nbsp/>*name, VALUE<nbsp/>value"</cparams>
<cbody> Sets the global variable <em>name</em> (the ``<tt>$</tt>'' prefix is
optional) to <em>value</em>. Returns <em>value</em>.
</cbody>
</cfunc>
<cfunc name="rb_gv_get">
<creturns>VALUE</creturns>
<cparams>const<nbsp/>char<nbsp/>*name"</cparams>
<cbody> Returns the global variable <em>name</em> (the ``<tt>$</tt>'' prefix is
optional).
</cbody>
</cfunc>
<cfunc name="rb_cvar_set">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>class, ID<nbsp/>name, VALUE<nbsp/>val"</cparams>
<cbody> Sets the class variable <em>name</em> in the given
<em>class</em> to <em>value</em>.
</cbody>
</cfunc>
<p/>
<cfunc name="rb_cvar_get">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>class, ID<nbsp/>name"</cparams>
<cbody> Returns the class variable <em>name</em>
from the given <em>class</em>.
</cbody>
</cfunc>
<p/>
<cfunc name="rb_cvar_defined">
<creturns>int</creturns>
<cparams>VALUE<nbsp/>class, ID<nbsp/>name"</cparams>
<cbody> Returns <tt>Qtrue</tt> if the given class variable
<em>name</em> has been defined for <em>class</em>; otherwise, returns
<tt>Qfalse</tt>.
</cbody>
</cfunc>
<p/>
<cfunc name="rb_cv_set">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>class, const<nbsp/>char<nbsp/>*name, VALUE<nbsp/>val"</cparams>
<cbody> Sets the class variable <em>name</em>
(which must be specified with a ``<tt>@@</tt>'' prefix) in the given
<em>class</em> to <em>value</em>.
</cbody>
</cfunc>
<p/>
<cfunc name="rb_cv_get">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>class, const<nbsp/>char<nbsp/>*name"</cparams>
<cbody> Returns the class variable <em>name</em> (which must be specified
with a ``<tt>@@</tt>'' prefix) from the given <em>class</em>.
</cbody>
</cfunc>
<p/>
</table>
<p/>
<table>
<cdoctitle>Object Status</cdoctitle>
<cfunc name="OBJ_TAINT">
<creturns></creturns>
<cparams>VALUE<nbsp/>obj"</cparams>
<cbody> Marks the given <em>obj</em> as tainted.
</cbody>
</cfunc>
<cfunc name="OBJ_TAINTED">
<creturns>int</creturns>
<cparams>VALUE<nbsp/>obj"</cparams>
<cbody> Returns nonzero if the given <em>obj</em> is tainted.
</cbody>
</cfunc>
<cfunc name="OBJ_FREEZE">
<creturns></creturns>
<cparams>VALUE<nbsp/>obj"</cparams>
<cbody> Marks the given <em>obj</em> as frozen.
</cbody>
</cfunc>
<cfunc name="OBJ_FROZEN">
<creturns>int</creturns>
<cparams>VALUE<nbsp/>obj"</cparams>
<cbody> Returns nonzero if the given <em>obj</em> is frozen.
</cbody>
</cfunc>
<cfunc name="Check_SafeStr">
<creturns></creturns>
<cparams>VALUE<nbsp/>str"</cparams>
<cbody> Raises <exception>SecurityError</exception> if current safe level > 0 and <em>str</em> is
tainted, or a <exception>TypeError</exception> if <em>str</em> is not a <tt>T_STRING</tt>.
</cbody>
</cfunc>
<cfunc name="rb_safe_level">
<creturns>int</creturns>
<cparams>"</cparams>
<cbody> Returns the current safe level.
</cbody>
</cfunc>
<cfunc name="rb_secure">
<creturns>void</creturns>
<cparams>int<nbsp/>level"</cparams>
<cbody> Raises <exception>SecurityError</exception> if <em>level</em> <= current safe level.
</cbody>
</cfunc>
<cfunc name="rb_set_safe_level">
<creturns>void</creturns>
<cparams>int<nbsp/>newlevel"</cparams>
<cbody> Sets the current safe level to <em>newlevel</em>.
</cbody>
</cfunc>
<p/>
</table>
<p/>
<table>
<cdoctitle>Commonly Used Methods</cdoctitle>
<cfunc name="rb_ary_new">
<creturns>VALUE</creturns>
<cparams>"</cparams>
<cbody> Returns a new <classname>Array</classname> with default size.
</cbody>
</cfunc>
<cfunc name="rb_ary_new2">
<creturns>VALUE</creturns>
<cparams>long<nbsp/>length"</cparams>
<cbody> Returns a new <classname>Array</classname> of the given <em>length</em>.
</cbody>
</cfunc>
<cfunc name="rb_ary_new3">
<creturns>VALUE</creturns>
<cparams>long<nbsp/>length, ..."</cparams>
<cbody> Returns a new <classname>Array</classname> of the given <em>length</em> and populated
with the remaining arguments.
</cbody>
</cfunc>
<cfunc name="rb_ary_new4">
<creturns>VALUE</creturns>
<cparams>long<nbsp/>length, VALUE<nbsp/>*values"</cparams>
<cbody> Returns a new <classname>Array</classname> of the given <em>length</em> and populated
with the C array <em>values</em>.
</cbody>
</cfunc>
<cfunc name="rb_ary_store">
<creturns>void</creturns>
<cparams>VALUE<nbsp/>self, long<nbsp/>index, VALUE<nbsp/>value"</cparams>
<cbody> Stores <em>value</em> at <em>index</em> in array <em>self</em>.
</cbody>
</cfunc>
<cfunc name="rb_ary_push">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>self, VALUE<nbsp/>value"</cparams>
<cbody> Pushes <em>value</em> onto the end of array <em>self</em>. Returns
<em>value</em>.
</cbody>
</cfunc>
<cfunc name="rb_ary_pop">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>self"</cparams>
<cbody> Removes and returns the last element from the array <em>self</em>.
</cbody>
</cfunc>
<cfunc name="rb_ary_shift">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>self"</cparams>
<cbody> Removes and returns the first element from the array <em>self</em>.
</cbody>
</cfunc>
<cfunc name="rb_ary_unshift">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>self, VALUE<nbsp/>value"</cparams>
<cbody> Pushes <em>value</em> onto the front of array <em>self</em>. Returns
<em>value</em>.
</cbody>
</cfunc>
<cfunc name="rb_ary_entry">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>self, long<nbsp/>index"</cparams>
<cbody> Returns array <em>self</em>'s element at <em>index</em>.
</cbody>
</cfunc>
<cfunc name="rb_respond_to">
<creturns>int</creturns>
<cparams>VALUE<nbsp/>self, ID<nbsp/>method"</cparams>
<cbody> Returns nonzero if <em>self</em> responds to <em>method</em>.
</cbody>
</cfunc>
<cfunc name="rb_thread_create">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>(*func)(), void<nbsp/>*data"</cparams>
<cbody> Runs <em>func</em> in a new thread, passing <em>data</em> as an
argument.
</cbody>
</cfunc>
<cfunc name="rb_hash_new">
<creturns>VALUE</creturns>
<cparams>"</cparams>
<cbody> Returns a new, empty <classname>Hash</classname>.
</cbody>
</cfunc>
<cfunc name="rb_hash_aref">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>self, VALUE<nbsp/>key"</cparams>
<cbody> Returns the element corresponding to <em>key</em> in <em>self</em>.
</cbody>
</cfunc>
<cfunc name="rb_hash_aset">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>self, VALUE<nbsp/>key, VALUE<nbsp/>value"</cparams>
<cbody> Sets the value for <em>key</em> to <em>value</em> in
<em>self</em>. Returns <em>value</em>.
</cbody>
</cfunc>
<cfunc name="rb_obj_is_instance_of">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>obj, VALUE<nbsp/>klass"</cparams>
<cbody> Returns <tt>Qtrue</tt> if <em>obj</em> is an instance of <em>klass</em>.
</cbody>
</cfunc>
<cfunc name="rb_obj_is_kind_of">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>obj, VALUE<nbsp/>klass"</cparams>
<cbody> Returns <tt>Qtrue</tt> if <em>klass</em> is the class of <em>obj</em> or
<em>class</em> is
one of the superclasses of the class of <em>obj</em>.
</cbody>
</cfunc>
<cfunc name="rb_str_new">
<creturns>VALUE</creturns>
<cparams>const<nbsp/>char<nbsp/>*src, long<nbsp/>length"</cparams>
<cbody> Returns a new <classname>String</classname> initialized with <em>length</em> characters
from <em>src</em>.
</cbody>
</cfunc>
<cfunc name="rb_str_new2">
<creturns>VALUE</creturns>
<cparams>const<nbsp/>char<nbsp/>*src"</cparams>
<cbody> Returns a new <classname>String</classname> initialized with the null-terminated
C string <em>src</em>.
</cbody>
</cfunc>
<cfunc name="rb_str_dup">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>str"</cparams>
<cbody> Returns a new <classname>String</classname> object duplicated from <em>str</em>.
</cbody>
</cfunc>
<cfunc name="rb_str_cat">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>self, const<nbsp/>char<nbsp/>*src, long<nbsp/>length"</cparams>
<cbody> Concatenates <em>length</em> characters from <em>src</em> onto
the <classname>String</classname> <em>self</em>. Returns <em>self</em>.
</cbody>
</cfunc>
<cfunc name="rb_str_concat">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>self, VALUE<nbsp/>other"</cparams>
<cbody> Concatenates <em>other</em> onto
the <classname>String</classname> <em>self</em>. Returns <em>self</em>.
</cbody>
</cfunc>
<cfunc name="rb_str_split">
<creturns>VALUE</creturns>
<cparams>VALUE<nbsp/>self, const<nbsp/>char<nbsp/>*delim"</cparams>
<cbody> Returns an array of <classname>String</classname> objects created by splitting
<em>self</em> on <em>delim</em>. </cbody>
</cfunc>
<p/>
</table>
<p/>
</chapter>
</ppdoc>
|