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 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>SWI-Prolog 7.3.6 Reference Manual: Section 10.4</title><link rel="home" href="index.html">
<link rel="contents" href="Contents.html">
<link rel="index" href="DocIndex.html">
<link rel="summary" href="summary.html">
<link rel="previous" href="foreigntypes.html">
<link rel="next" href="plld.html">
<style type="text/css">
/* Style sheet for SWI-Prolog latex2html
*/
dd.defbody
{ margin-bottom: 1em;
}
dt.pubdef, dt.multidef
{ color: #fff;
padding: 2px 10px 0px 10px;
margin-bottom: 5px;
font-size: 18px;
vertical-align: middle;
overflow: hidden;
}
dt.pubdef { background-color: #0c3d6e; }
dt.multidef { background-color: #ef9439; }
.bib dd
{ margin-bottom: 1em;
}
.bib dt
{ float: left;
margin-right: 1.3ex;
}
pre.code
{ margin-left: 1.5em;
margin-right: 1.5em;
border: 1px dotted;
padding-top: 5px;
padding-left: 5px;
padding-bottom: 5px;
background-color: #f8f8f8;
}
div.navigate
{ text-align: center;
background-color: #f0f0f0;
border: 1px dotted;
padding: 5px;
}
div.title
{ text-align: center;
padding-bottom: 1em;
font-size: 200%;
font-weight: bold;
}
div.author
{ text-align: center;
font-style: italic;
}
div.abstract
{ margin-top: 2em;
background-color: #f0f0f0;
border: 1px dotted;
padding: 5px;
margin-left: 10%; margin-right:10%;
}
div.abstract-title
{ text-align: center;
padding: 5px;
font-size: 120%;
font-weight: bold;
}
div.toc-h1
{ font-size: 200%;
font-weight: bold;
}
div.toc-h2
{ font-size: 120%;
font-weight: bold;
margin-left: 2em;
}
div.toc-h3
{ font-size: 100%;
font-weight: bold;
margin-left: 4em;
}
div.toc-h4
{ font-size: 100%;
margin-left: 6em;
}
span.sec-nr
{
}
span.sec-title
{
}
span.pred-ext
{ font-weight: bold;
}
span.pred-tag
{ float: right;
padding-top: 0.2em;
font-size: 80%;
font-style: italic;
color: #fff;
}
div.caption
{ width: 80%;
margin: auto;
text-align:center;
}
/* Footnotes */
.fn {
color: red;
font-size: 70%;
}
.fn-text, .fnp {
position: absolute;
top: auto;
left: 10%;
border: 1px solid #000;
box-shadow: 5px 5px 5px #888;
display: none;
background: #fff;
color: #000;
margin-top: 25px;
padding: 8px 12px;
font-size: larger;
}
sup:hover span.fn-text
{ display: block;
}
/* Lists */
dl.latex
{ margin-top: 1ex;
margin-bottom: 0.5ex;
}
dl.latex dl.latex dd.defbody
{ margin-bottom: 0.5ex;
}
/* PlDoc Tags */
dl.tags
{ font-size: 90%;
margin-left: 5ex;
margin-top: 1ex;
margin-bottom: 0.5ex;
}
dl.tags dt
{ margin-left: 0pt;
font-weight: bold;
}
dl.tags dd
{ margin-left: 3ex;
}
td.param
{ font-style: italic;
font-weight: bold;
}
/* Index */
dt.index-sep
{ font-weight: bold;
font-size: +1;
margin-top: 1ex;
}
/* Tables */
table.center
{ margin: auto;
}
table.latex
{ border-collapse:collapse;
}
table.latex tr
{ vertical-align: text-top;
}
table.latex td,th
{ padding: 2px 1em;
}
table.latex tr.hline td,th
{ border-top: 1px solid black;
}
table.frame-box
{ border: 2px solid black;
}
</style>
</head>
<body style="background:white">
<div class="navigate"><a class="nav" href="index.html"><img src="home.gif" alt="Home"></a>
<a class="nav" href="Contents.html"><img src="index.gif" alt="Contents"></a>
<a class="nav" href="DocIndex.html"><img src="yellow_pages.gif" alt="Index"></a>
<a class="nav" href="summary.html"><img src="info.gif" alt="Summary"></a>
<a class="nav" href="foreigntypes.html"><img src="prev.gif" alt="Previous"></a>
<a class="nav" href="plld.html"><img src="next.gif" alt="Next"></a>
</div>
<h2 id="sec:foreigninclude"><a id="sec:10.4"><span class="sec-nr">10.4</span> <span class="sec-title">The
Foreign Include File</span></a></h2>
<a id="sec:foreigninclude"></a>
<p><h3 id="sec:foreign-control"><a id="sec:10.4.1"><span class="sec-nr">10.4.1</span> <span class="sec-title">Argument
Passing and Control</span></a></h3>
<a id="sec:foreign-control"></a>
<p>If Prolog encounters a foreign predicate at run time it will call a
function specified in the predicate definition of the foreign predicate.
The arguments <var>1, ... , <<var>arity</var>></var> pass the
Prolog arguments to the goal as Prolog terms. Foreign functions should
be declared of type
<code>foreign_t</code>. Deterministic foreign functions have two
alternatives to return control back to Prolog:
<dl class="latex">
<dt class="pubdef"><a id="PL_succeed()"><var>(return) foreign_t</var> <strong>PL_succeed</strong>(<var></var>)</a></dt>
<dd class="defbody">
Succeed deterministically. PL_succeed is defined as
<code>return <code>TRUE</code></code>.
</dd>
<dt class="pubdef"><a id="PL_fail()"><var>(return) foreign_t</var> <strong>PL_fail</strong>(<var></var>)</a></dt>
<dd class="defbody">
Fail and start Prolog backtracking. PL_fail is defined as <code>return <code>FALSE</code></code>.
</dd>
</dl>
<p><h4 id="sec:foreignnondet"><a id="sec:10.4.1.1"><span class="sec-nr">10.4.1.1</span> <span class="sec-title">Non-deterministic
Foreign Predicates</span></a></h4>
<a id="sec:foreignnondet"></a>
<p>By default foreign predicates are deterministic. Using the
<code>PL_FA_NONDETERMINISTIC</code> attribute (see <a class="func" href="foreigninclude.html#PL_register_foreign()">PL_register_foreign()</a>)
it is possible to register a predicate as a non-deterministic predicate.
Writing non-deterministic foreign predicates is slightly more
complicated as the foreign function needs context information for
generating the next solution. Note that the same foreign function should
be prepared to be simultaneously active in more than one goal. Suppose
the natural_number_below_n/2 is a non-deterministic foreign predicate,
backtracking over all natural numbers lower than the first argument. Now
consider the following predicate:
<pre class="code">
quotient_below_n(Q, N) :-
natural_number_below_n(N, N1),
natural_number_below_n(N, N2),
Q =:= N1 / N2, !.
</pre>
<p>In this predicate the function natural_number_below_n/2
simultaneously generates solutions for both its invocations.
<p>Non-deterministic foreign functions should be prepared to handle
three different calls from Prolog:
<p>
<ul class="latex">
<li><i>Initial call (<code>PL_FIRST_CALL</code>)</i><br>
Prolog has just created a frame for the foreign function and asks it to
produce the first answer.
<li><i>Redo call (<code>PL_REDO</code>)</i><br>
The previous invocation of the foreign function associated with the
current goal indicated it was possible to backtrack. The foreign
function should produce the next solution.
<li><i>Terminate call (<code>PL_PRUNED</code>)</i><br>
The choice point left by the foreign function has been destroyed by a
cut. The foreign function is given the opportunity to clean the
environment.
</ul>
<p>Both the context information and the type of call is provided by an
argument of type <code>control_t</code> appended to the argument list
for deterministic foreign functions. The macro <a class="func" href="foreigninclude.html#PL_foreign_control()">PL_foreign_control()</a>
extracts the type of call from the control argument. The foreign
function can pass a context handle using the <code>PL_retry*()</code>
macros and extract the handle from the extra argument using the
<code>PL_foreign_context*()</code> macro.
<dl class="latex">
<dt class="pubdef"><a id="PL_retry()"><var>(return) foreign_t</var> <strong>PL_retry</strong>(<var>intptr_t
value</var>)</a></dt>
<dd class="defbody">
The foreign function succeeds while leaving a choice point. On
backtracking over this goal the foreign function will be called again,
but the control argument now indicates it is a `Redo' call and the macro <a class="func" href="foreigninclude.html#PL_foreign_context()">PL_foreign_context()</a>
returns the handle passed via
<a class="func" href="foreigninclude.html#PL_retry()">PL_retry()</a>.
This handle is a signed value two bits smaller than a pointer, i.e., 30
or 62 bits (two bits are used for status indication). Defined as <code>return
_<a class="func" href="foreigninclude.html#PL_retry()">PL_retry(n)</a></code>.
See also <a class="func" href="foreigninclude.html#PL_succeed()">PL_succeed()</a>.</dd>
<dt class="pubdef"><a id="PL_retry_address()"><var>(return) foreign_t</var> <strong>PL_retry_address</strong>(<var>void
*</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_retry()">PL_retry()</a>,
but ensures an address as returned by malloc() is correctly recovered by <a class="func" href="foreigninclude.html#PL_foreign_context_address()">PL_foreign_context_address()</a>.
Defined as <code>return _<a class="func" href="foreigninclude.html#PL_retry_address()">PL_retry_address(n)</a></code>.
See also
<a class="func" href="foreigninclude.html#PL_succeed()">PL_succeed()</a>.</dd>
<dt class="pubdef"><a id="PL_foreign_control()"><var>int</var> <strong>PL_foreign_control</strong>(<var>control_t</var>)</a></dt>
<dd class="defbody">
Extracts the type of call from the control argument. The return values
are described above. Note that the function should be prepared to handle
the <code>PL_PRUNED</code> case and should be aware that the other
arguments are not valid in this case.</dd>
<dt class="pubdef"><a id="PL_foreign_context()"><var>intptr_t</var> <strong>PL_foreign_context</strong>(<var>control_t</var>)</a></dt>
<dd class="defbody">
Extracts the context from the context argument. If the call type is
<code>PL_FIRST_CALL</code> the context value is 0L. Otherwise it is the
value returned by the last <a class="func" href="foreigninclude.html#PL_retry()">PL_retry()</a>
associated with this goal (both if the call type is <code>PL_REDO</code>
or <code>PL_PRUNED</code>).</dd>
<dt class="pubdef"><a id="PL_foreign_context_address()"><var>void *</var> <strong>PL_foreign_context_address</strong>(<var>control_t</var>)</a></dt>
<dd class="defbody">
Extracts an address as passed in by <a class="func" href="foreigninclude.html#PL_retry_address()">PL_retry_address()</a>.</dd>
<dt class="pubdef"><a id="PL_foreign_context_predicate()"><var>predicate_t</var> <strong>PL_foreign_context_predicate</strong>(<var>control_t</var>)</a></dt>
<dd class="defbody">
<p>Fetch the Prolog predicate that is executing this function. Note that
if the predicate is imported, the returned predicate refers to the final
definition rather than the imported predicate, i.e., the module reported
by <a class="func" href="foreigninclude.html#PL_predicate_info()">PL_predicate_info()</a>
is the module in which the predicate is defined rather than the module
where it was called. See also
<a class="func" href="foreigninclude.html#PL_predicate_info()">PL_predicate_info()</a>.
</dd>
</dl>
<p>Note: If a non-deterministic foreign function returns using <a class="func" href="foreigninclude.html#PL_succeed()">PL_succeed()</a>
or <a class="func" href="foreigninclude.html#PL_fail()">PL_fail()</a>,
Prolog assumes the foreign function has cleaned its environment. <b>No</b>
call with control argument <code>PL_PRUNED</code> will follow.
<p>The code of <a class="fig" href="foreigninclude.html#fig:nondetermf">figure
6</a> shows a skeleton for a non-deterministic foreign predicate
definition.
<pre class="code">
typedef struct /* define a context structure */
{ ...
} context;
foreign_t
my_function(term_t a0, term_t a1, control_t handle)
{ struct context * ctxt;
switch( PL_foreign_control(handle) )
{ case PL_FIRST_CALL:
ctxt = malloc(sizeof(struct context));
...
PL_retry_address(ctxt);
case PL_REDO:
ctxt = PL_foreign_context_address(handle);
...
PL_retry_address(ctxt);
case PL_PRUNED:
ctxt = PL_foreign_context_address(handle);
...
free(ctxt);
PL_succeed;
}
}
</pre>
<div class="caption"><b>Figure 6 : </b>Skeleton for non-deterministic
foreign functions</div>
<a id="fig:nondetermf"></a>
<p><h3 id="sec:foreign-atoms"><a id="sec:10.4.2"><span class="sec-nr">10.4.2</span> <span class="sec-title">Atoms
and functors</span></a></h3>
<a id="sec:foreign-atoms"></a>
<p>The following functions provide for communication using atoms and
functors.
<dl class="latex">
<dt class="pubdef"><a id="PL_new_atom()"><var>atom_t</var> <strong>PL_new_atom</strong>(<var>const
char *</var>)</a></dt>
<dd class="defbody">
Return an atom handle for the given C-string. This function always
succeeds. The returned handle is valid as long as the atom is referenced
(see <a class="sec" href="foreigninclude.html">section 10.4.2.1</a>).
The following atoms are provided as macros, giving access to the empty
list symbol and the name of the list constructor. Prior to version 7, <code>ATOM_nil</code>
is the same as <code><a class="func" href="foreigninclude.html#PL_new_atom()">PL_new_atom("[]")</a></code>
and <code>ATOM_dot</code> is the same as
<code><a class="func" href="foreigninclude.html#PL_new_atom()">PL_new_atom(".")</a></code>.
This is no long the case in SWI-Prolog version 7.
<dl class="latex">
<dt class="pubdef"><a id="ATOM_nil()"><var>atom_t</var> <strong>ATOM_nil</strong>(<var>ATOM_nil</var>)</a></dt>
<dd class="defbody">
tomic constant that represents the empty list. It is adviced to use <a class="func" href="foreigninclude.html#PL_get_nil()">PL_get_nil()</a>, <a class="func" href="foreigninclude.html#PL_put_nil()">PL_put_nil()</a>
or <a class="func" href="foreigninclude.html#PL_unify_nil()">PL_unify_nil()</a>
where applicable.</dd>
<dt class="pubdef"><a id="ATOM_dot()"><var>atom_t</var> <strong>ATOM_dot</strong>(<var>ATOM_dot</var>)</a></dt>
<dd class="defbody">
tomic constant that represents the name of the list constructor. The
list constructor itself is created using
<code><a class="func" href="foreigninclude.html#PL_new_functor()">PL_new_functor(ATOM_dot,2)</a></code>.
It is adviced to use
<a class="func" href="foreigninclude.html#PL_get_list()">PL_get_list()</a>, <a class="func" href="foreigninclude.html#PL_put_list()">PL_put_list()</a>
or <a class="func" href="foreigninclude.html#PL_unify_list()">PL_unify_list()</a>
where applicable.
</dd>
</dl>
</dd>
<dt class="pubdef"><a id="PL_atom_chars()"><var>const char*</var> <strong>PL_atom_chars</strong>(<var>atom_t
atom</var>)</a></dt>
<dd class="defbody">
Return a C-string for the text represented by the given atom. The
returned text will not be changed by Prolog. It is not allowed to modify
the contents, not even `temporary' as the string may reside in read-only
memory. The returned string becomes invalid if the atom is garbage
collected (see <a class="sec" href="foreigninclude.html">section
10.4.2.1</a>). Foreign functions that require the text from an atom
passed in a <code>term_t</code> normally use
<a class="func" href="foreigninclude.html#PL_get_atom_chars()">PL_get_atom_chars()</a>
or <a class="func" href="foreigninclude.html#PL_get_atom_nchars()">PL_get_atom_nchars()</a>.</dd>
<dt class="pubdef"><a id="PL_new_functor()"><var>functor_t</var> <strong>PL_new_functor</strong>(<var>atom_t
name, int arity</var>)</a></dt>
<dd class="defbody">
Returns a <em>functor identifier</em>, a handle for the name/arity pair.
The returned handle is valid for the entire Prolog session.
</dd>
<dt class="pubdef"><a id="PL_functor_name()"><var>atom_t</var> <strong>PL_functor_name</strong>(<var>functor_t
f</var>)</a></dt>
<dd class="defbody">
Return an atom representing the name of the given functor.
</dd>
<dt class="pubdef"><a id="PL_functor_arity()"><var>int</var> <strong>PL_functor_arity</strong>(<var>functor_t
f</var>)</a></dt>
<dd class="defbody">
Return the arity of the given functor.
</dd>
</dl>
<p><h4 id="sec:atomgc"><a id="sec:10.4.2.1"><span class="sec-nr">10.4.2.1</span> <span class="sec-title">Atoms
and atom garbage collection</span></a></h4>
<a id="sec:atomgc"></a>
<p>With the introduction of atom garbage collection in version 3.3.0,
atoms no longer live as long as the process. Instead, their lifetime is
guaranteed only as long as they are referenced. In the single-threaded
version, atom garbage collections are only invoked at the
<em>call-port</em>. In the multithreaded version (see <a class="sec" href="threads.html">chapter
9</a>), they appear asynchronously, except for the invoking thread.
<p>For dealing with atom garbage collection, two additional functions
are provided:
<dl class="latex">
<dt class="pubdef"><a id="PL_register_atom()"><var>void</var> <strong>PL_register_atom</strong>(<var>atom_t
atom</var>)</a></dt>
<dd class="defbody">
Increment the reference count of the atom by one. <a class="func" href="foreigninclude.html#PL_new_atom()">PL_new_atom()</a>
performs this automatically, returning an atom with a reference count of
at least one.<sup class="fn">151<span class="fn-text">Otherwise
asynchronous atom garbage collection might destroy the atom before it is
used.</span></sup></dd>
<dt class="pubdef"><a id="PL_unregister_atom()"><var>void</var> <strong>PL_unregister_atom</strong>(<var>atom_t
atom</var>)</a></dt>
<dd class="defbody">
Decrement the reference count of the atom. If the reference count drops
below zero, an assertion error is raised.
</dd>
</dl>
<p>Please note that the following two calls are different with respect
to atom garbage collection:
<pre class="code">
PL_unify_atom_chars(t, "text");
PL_unify_atom(t, PL_new_atom("text"));
</pre>
<p>The latter increments the reference count of the atom <code>text</code>,
which effectively ensures the atom will never be collected. It is
advised to use the *_chars() or *_nchars() functions whenever
applicable.
<p><h3 id="sec:foreign-term-analysis"><a id="sec:10.4.3"><span class="sec-nr">10.4.3</span> <span class="sec-title">Analysing
Terms via the Foreign Interface</span></a></h3>
<a id="sec:foreign-term-analysis"></a>
<p>Each argument of a foreign function (except for the control argument)
is of type <code>term_t</code>, an opaque handle to a Prolog term. Three
groups of functions are available for the analysis of terms. The first
just validates the type, like the Prolog predicates <a id="idx:var1:1831"></a><a class="pred" href="typetest.html#var/1">var/1</a>, <a id="idx:atom1:1832"></a><a class="pred" href="typetest.html#atom/1">atom/1</a>,
etc., and are called <code>PL_is_*()</code>. The second group attempts
to translate the argument into a C primitive type. These predicates take
a <code>term_t</code> and a pointer to the appropriate C type and return <code>TRUE</code>
or
<code>FALSE</code> depending on successful or unsuccessful translation.
If the translation fails, the pointed-to data is never modified.
<p><h4 id="sec:foreign-term-type"><a id="sec:10.4.3.1"><span class="sec-nr">10.4.3.1</span> <span class="sec-title">Testing
the type of a term</span></a></h4>
<a id="sec:foreign-term-type"></a>
<dl class="latex">
<dt class="pubdef"><a id="PL_term_type()"><var>int</var> <strong>PL_term_type</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Obtain the type of a term, which should be a term returned by one of the
other interface predicates or passed as an argument. The function
returns the type of the Prolog term. The type identifiers are listed
below. Note that the extraction functions <code>PL_get_*()</code> also
validate the type and thus the two sections below are equivalent.
<pre class="code">
if ( PL_is_atom(t) )
{ char *s;
PL_get_atom_chars(t, &s);
...;
}
or
char *s;
if ( PL_get_atom_chars(t, &s) )
{ ...;
}
</pre>
<p><b>Version 7</b> added <code>PL_NIL</code>, <code>PL_BLOB</code>,
<code>PL_LIST_PAIR</code> and <code>PL_DICT</code>. Older versions
classify <code>PL_NIL</code> and <code>PL_BLOB</code> as <code>PL_ATOM</code>,
<code>PL_LIST_PAIR</code> as <code>PL_TERM</code> and do not have dicts.
<p><table class="latex frame-box">
<tr><td><code>PL_VARIABLE</code> </td><td>A variable or attributed
variable </td></tr>
<tr><td><code>PL_ATOM</code> </td><td>A Prolog atom </td></tr>
<tr><td><code>PL_NIL</code> </td><td>The constant <code>[]</code> </td></tr>
<tr><td><code>PL_BLOB</code> </td><td>A blob (see <a class="sec" href="foreigninclude.html">section
10.4.7.2</a>) </td></tr>
<tr><td><code>PL_STRING</code> </td><td>A string (see <a class="sec" href="strings.html">section
5.2</a>) </td></tr>
<tr><td><code>PL_INTEGER</code> </td><td>A integer </td></tr>
<tr><td><code>PL_FLOAT</code> </td><td>A floating point number </td></tr>
<tr><td><code>PL_TERM</code> </td><td>A compound term </td></tr>
<tr><td><code>PL_LIST_PAIR</code> </td><td>A list cell (<code>[H|T]</code>) </td></tr>
<tr><td><code>PL_DICT</code> </td><td>A dict (see <a class="sec" href="dicts.html">section
5.4</a>)) </td></tr>
</table>
</dd>
</dl>
<p>The functions PL_is_<<var>type</var>> are an alternative to <a class="func" href="foreigninclude.html#PL_term_type()">PL_term_type()</a>.
The test <code><a class="func" href="foreigninclude.html#PL_is_variable()">PL_is_variable(term)</a></code>
is equivalent to
<code><a class="func" href="foreigninclude.html#PL_term_type()">PL_term_type(term)</a>
== PL_VARIABLE</code>, but the first is considerably faster. On the
other hand, using a switch over <a class="func" href="foreigninclude.html#PL_term_type()">PL_term_type()</a>
is faster and more readable then using an if-then-else using the
functions below. All these functions return either <code>TRUE</code> or <code>FALSE</code>.
<dl class="latex">
<dt class="pubdef"><a id="PL_is_variable()"><var>int</var> <strong>PL_is_variable</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is a variable.</dd>
<dt class="pubdef"><a id="PL_is_ground()"><var>int</var> <strong>PL_is_ground</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is a ground term. See also <a id="idx:ground1:1833"></a><a class="pred" href="typetest.html#ground/1">ground/1</a>.
This function is cycle-safe.</dd>
<dt class="pubdef"><a id="PL_is_atom()"><var>int</var> <strong>PL_is_atom</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is an atom.</dd>
<dt class="pubdef"><a id="PL_is_string()"><var>int</var> <strong>PL_is_string</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is a string.</dd>
<dt class="pubdef"><a id="PL_is_integer()"><var>int</var> <strong>PL_is_integer</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is an integer.</dd>
<dt class="pubdef"><a id="PL_is_float()"><var>int</var> <strong>PL_is_float</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is a float.</dd>
<dt class="pubdef"><a id="PL_is_callable()"><var>int</var> <strong>PL_is_callable</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is a callable term. See <a id="idx:callable1:1834"></a><a class="pred" href="typetest.html#callable/1">callable/1</a>
for details.</dd>
<dt class="pubdef"><a id="PL_is_compound()"><var>int</var> <strong>PL_is_compound</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is a compound term.</dd>
<dt class="pubdef"><a id="PL_is_functor()"><var>int</var> <strong>PL_is_functor</strong>(<var>term_t,
functor_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is compound and its functor is <var>functor</var>.
This test is equivalent to <a class="func" href="foreigninclude.html#PL_get_functor()">PL_get_functor()</a>,
followed by testing the functor, but easier to write and faster.</dd>
<dt class="pubdef"><a id="PL_is_list()"><var>int</var> <strong>PL_is_list</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is a compound term using the list
constructor or the list terminator. See also <a class="func" href="foreigninclude.html#PL_is_pair()">PL_is_pair()</a>
and
<a class="func" href="foreigninclude.html#PL_skip_list()">PL_skip_list()</a>.</dd>
<dt class="pubdef"><a id="PL_is_pair()"><var>int</var> <strong>PL_is_pair</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is a compound term using the list
constructor. See also <a class="func" href="foreigninclude.html#PL_is_list()">PL_is_list()</a>
and <a class="func" href="foreigninclude.html#PL_skip_list()">PL_skip_list()</a>.</dd>
<dt class="pubdef"><a id="PL_is_atomic()"><var>int</var> <strong>PL_is_atomic</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is atomic (not variable or
compound).</dd>
<dt class="pubdef"><a id="PL_is_number()"><var>int</var> <strong>PL_is_number</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is an integer or float.</dd>
<dt class="pubdef"><a id="PL_is_acyclic()"><var>int</var> <strong>PL_is_acyclic</strong>(<var>term_t</var>)</a></dt>
<dd class="defbody">
Returns non-zero if <var>term</var> is acyclic (i.e. a finite tree).
</dd>
</dl>
<p><h4 id="sec:foreign-extract-from-term"><a id="sec:10.4.3.2"><span class="sec-nr">10.4.3.2</span> <span class="sec-title">Reading
data from a term</span></a></h4>
<a id="sec:foreign-extract-from-term"></a>
<p>The functions <code>PL_get_*()</code> read information from a Prolog
term. Most of them take two arguments. The first is the input term and
the second is a pointer to the output value or a term reference.
<dl class="latex">
<dt class="pubdef"><a id="PL_get_atom()"><var>int</var> <strong>PL_get_atom</strong>(<var>term_t
+t, atom_t *a</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is an atom, store the unique atom identifier over <var>a</var>.
See also <a class="func" href="foreigninclude.html#PL_atom_chars()">PL_atom_chars()</a>
and <a class="func" href="foreigninclude.html#PL_new_atom()">PL_new_atom()</a>.
If there is no need to access the data (characters) of an atom, it is
advised to manipulate atoms using their handle. As the atom is
referenced by <var>t</var>, it will live at least as long as <var>t</var>
does. If longer live-time is required, the atom should be locked using <a class="func" href="foreigninclude.html#PL_register_atom()">PL_register_atom()</a>.</dd>
<dt class="pubdef"><a id="PL_get_atom_chars()"><var>int</var> <strong>PL_get_atom_chars</strong>(<var>term_t
+t, char **s</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is an atom, store a pointer to a 0-terminated C-string
in
<var>s</var>. It is explicitly <strong>not</strong> allowed to modify
the contents of this string. Some built-in atoms may have the string
allocated in read-only memory, so `temporary manipulation' can cause an
error.</dd>
<dt class="pubdef"><a id="PL_get_string_chars()"><var>int</var> <strong>PL_get_string_chars</strong>(<var>term_t
+t, char **s, int *len</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is a string object, store a pointer to a 0-terminated
C-string in <var>s</var> and the length of the string in <var>len</var>.
Note that this pointer is invalidated by backtracking, garbage
collection and stack-shifts, so generally the only save operations are
to pass it immediately to a C function that doesn't involve Prolog.</dd>
<dt class="pubdef"><a id="PL_get_chars()"><var>int</var> <strong>PL_get_chars</strong>(<var>term_t
+t, char **s, unsigned flags</var>)</a></dt>
<dd class="defbody">
Convert the argument term <var>t</var> to a 0-terminated C-string. <em>flags</em>
is a bitwise disjunction from two groups of constants. The first
specifies which term types should be converted and the second how the
argument is stored. Below is a specification of these constants. <code>BUF_RING</code>
implies, if the data is not static (as from an atom), that the data is
copied to the next buffer from a ring of 16 buffers. This is a
convenient way of converting multiple arguments passed to a foreign
predicate to C-strings. If BUF_MALLOC is used, the data must be freed
using <a class="func" href="foreignnotes.html#PL_free()">PL_free()</a>
when no longer needed.
<p>With the introduction of wide characters (see <a class="sec" href="widechars.html">section
2.18.1</a>), not all atoms can be converted into a <code>char*</code>.
This function fails if <var>t</var> is of the wrong type, but also if
the text cannot be represented. See the <code>REP_*</code> flags below
for details.
<dl class="latex">
<dt><strong>CVT_ATOM</strong></dt>
<dd class="defbody">
Convert if term is an atom.</dd>
<dt><strong>CVT_STRING</strong></dt>
<dd class="defbody">
Convert if term is a string.</dd>
<dt><strong>CVT_LIST</strong></dt>
<dd class="defbody">
Convert if term is a list of of character codes.</dd>
<dt><strong>CVT_INTEGER</strong></dt>
<dd class="defbody">
Convert if term is an integer.</dd>
<dt><strong>CVT_FLOAT</strong></dt>
<dd class="defbody">
Convert if term is a float. The characters returned are the same as
<a id="idx:write1:1835"></a><a class="pred" href="termrw.html#write/1">write/1</a>
would write for the floating point number.</dd>
<dt><strong>CVT_NUMBER</strong></dt>
<dd class="defbody">
Convert if term is an integer or float.</dd>
<dt><strong>CVT_ATOMIC</strong></dt>
<dd class="defbody">
Convert if term is atomic.</dd>
<dt><strong>CVT_VARIABLE</strong></dt>
<dd class="defbody">
Convert variable to print-name</dd>
<dt><strong>CVT_WRITE</strong></dt>
<dd class="defbody">
Convert any term that is not converted by any of the other flags using
<a id="idx:write1:1836"></a><a class="pred" href="termrw.html#write/1">write/1</a>.
If no <code>BUF_*</code> is provided, <code>BUF_RING</code> is implied.</dd>
<dt><strong>CVT_WRITE_CANONICAL</strong></dt>
<dd class="defbody">
As <code>CVT_WRITE</code>, but using <a id="idx:writecanonical2:1837"></a><a class="pred" href="termrw.html#write_canonical/2">write_canonical/2</a>.</dd>
<dt><strong>CVT_WRITEQ</strong></dt>
<dd class="defbody">
As <code>CVT_WRITE</code>, but using <a id="idx:writeq2:1838"></a><a class="pred" href="termrw.html#writeq/2">writeq/2</a>.</dd>
<dt><strong>CVT_ALL</strong></dt>
<dd class="defbody">
Convert if term is any of the above, except for <code>CVT_VARIABLE</code>
and
<code>CVT_WRITE*</code>.</dd>
<dt><strong>CVT_EXCEPTION</strong></dt>
<dd class="defbody">
If conversion fails due to a type error, raise a Prolog type error
exception in addition to failure</dd>
<dt><strong>BUF_DISCARDABLE</strong></dt>
<dd class="defbody">
Data must copied immediately</dd>
<dt><strong>BUF_RING</strong></dt>
<dd class="defbody">
Data is stored in a ring of buffers</dd>
<dt><strong>BUF_MALLOC</strong></dt>
<dd class="defbody">
Data is copied to a new buffer returned by <strong>PL_malloc</strong>(3).
When no longer needed the user must call <a class="func" href="foreignnotes.html#PL_free()">PL_free()</a>
on the data.</dd>
<dt><strong>REP_ISO_LATIN_1</strong></dt>
<dd class="defbody">
Text is in ISO Latin-1 encoding and the call fails if text cannot be
represented. This flag has the value 0 and is thus the default.</dd>
<dt><strong>REP_UTF8</strong></dt>
<dd class="defbody">
Convert the text to a UTF-8 string. This works for all text.</dd>
<dt><strong>REP_MB</strong></dt>
<dd class="defbody">
Convert to default locale-defined 8-bit string. Success depends on the
locale. Conversion is done using the wcrtomb() C library function.
</dd>
</dl>
</dd>
<dt class="pubdef"><a id="PL_get_list_chars()"><var>int</var> <strong>PL_get_list_chars</strong>(<var>+term_t
l, char **s, unsigned flags</var>)</a></dt>
<dd class="defbody">
Same as <code><a class="func" href="foreigninclude.html#PL_get_chars()">PL_get_chars(<var>l</var>, <var>s</var>,
CVT_LIST|<var>flags</var>)</a></code>, provided <var>flags</var>
contains none of the <code>CVT_*</code> flags.
</dd>
<dt class="pubdef"><a id="PL_get_integer()"><var>int</var> <strong>PL_get_integer</strong>(<var>+term_t
t, int *i</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is a Prolog integer, assign its value over <var>i</var>.
On 32-bit machines, this is the same as <a class="func" href="foreigninclude.html#PL_get_long()">PL_get_long()</a>,
but avoids a warning from the compiler. See also <a class="func" href="foreigninclude.html#PL_get_long()">PL_get_long()</a>.</dd>
<dt class="pubdef"><a id="PL_get_long()"><var>int</var> <strong>PL_get_long</strong>(<var>term_t
+t, long *i</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is a Prolog integer that can be represented as a long,
assign its value over <var>i</var>. If <var>t</var> is an integer that
cannot be represented by a C long, this function returns <code>FALSE</code>.
If <var>t</var> is a floating point number that can be represented as a
long, this function succeeds as well. See also <a class="func" href="foreigninclude.html#PL_get_int64()">PL_get_int64()</a>.</dd>
<dt class="pubdef"><a id="PL_get_int64()"><var>int</var> <strong>PL_get_int64</strong>(<var>term_t
+t, int64_t *i</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is a Prolog integer or float that can be represented as
a
<code>int64_t</code>, assign its value over <var>i</var>. Currently all
Prolog integers can be represented using this type, but this might
change if SWI-Prolog introduces unbounded integers.</dd>
<dt class="pubdef"><a id="PL_get_intptr()"><var>int</var> <strong>PL_get_intptr</strong>(<var>term_t
+t, intptr_t *i</var>)</a></dt>
<dd class="defbody">
Get an integer that is at least as wide as a pointer. On most platforms
this is the same as <a class="func" href="foreigninclude.html#PL_get_long()">PL_get_long()</a>,
but on Win64 pointers are 8 bytes and longs only 4. Unlike <a class="func" href="foreigninclude.html#PL_get_pointer()">PL_get_pointer()</a>,
the value is not modified.</dd>
<dt class="pubdef"><a id="PL_get_bool()"><var>int</var> <strong>PL_get_bool</strong>(<var>term_t
+t, int *val</var>)</a></dt>
<dd class="defbody">
If <var>t</var> has the value <code>true</code> or <code>false</code>,
set <var>val</var> to the C constant <code>TRUE</code> or <code>FALSE</code>
and return success, otherwise return failure.
</dd>
<dt class="pubdef"><a id="PL_get_pointer()"><var>int</var> <strong>PL_get_pointer</strong>(<var>term_t
+t, void **ptr</var>)</a></dt>
<dd class="defbody">
In the current system, pointers are represented by Prolog integers, but
need some manipulation to make sure they do not get truncated due to the
limited Prolog integer range. <a class="func" href="foreigninclude.html#PL_put_pointer()">PL_put_pointer()</a>
and <a class="func" href="foreigninclude.html#PL_get_pointer()">PL_get_pointer()</a>
guarantee pointers in the range of malloc() are handled without
truncating.
</dd>
<dt class="pubdef"><a id="PL_get_float()"><var>int</var> <strong>PL_get_float</strong>(<var>term_t
+t, double *f</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is a float or integer, its value is assigned over <var>f</var>.
</dd>
<dt class="pubdef"><a id="PL_get_functor()"><var>int</var> <strong>PL_get_functor</strong>(<var>term_t
+t, functor_t *f</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is compound or an atom, the Prolog representation of the
name-arity pair will be assigned over <var>f</var>. See also
<a class="func" href="foreigninclude.html#PL_get_name_arity()">PL_get_name_arity()</a>
and <a class="func" href="foreigninclude.html#PL_is_functor()">PL_is_functor()</a>.</dd>
<dt class="pubdef"><a id="PL_get_name_arity()"><var>int</var> <strong>PL_get_name_arity</strong>(<var>term_t
+t, atom_t *name, int *arity</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is compound or an atom, the functor name will be
assigned over <var>name</var> and the arity over <var>arity</var>. See
also
<a class="func" href="foreigninclude.html#PL_get_functor()">PL_get_functor()</a>
and <a class="func" href="foreigninclude.html#PL_is_functor()">PL_is_functor()</a>.</dd>
<dt class="pubdef"><a id="PL_get_compound_name_arity()"><var>int</var> <strong>PL_get_compound_name_arity</strong>(<var>term_t
+t, atom_t *name, int *arity</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is compound term, the functor name will be assigned over
<var>name</var> and the arity over <var>arity</var>. This is the same as
<a class="func" href="foreigninclude.html#PL_get_name_arity()">PL_get_name_arity()</a>,
but this function fails if <var>t</var> is an atom.</dd>
<dt class="pubdef"><a id="PL_get_module()"><var>int</var> <strong>PL_get_module</strong>(<var>term_t
+t, module_t *module</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is an atom, the system will look up or create the
corresponding module and assign an opaque pointer to it over <em>module</em>.
</dd>
<dt class="pubdef"><a id="PL_get_arg()"><var>int</var> <strong>PL_get_arg</strong>(<var>int
index, term_t +t, term_t -a</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is compound and index is between 1 and arity
(inclusive), assign <var>a</var> with a term reference to the argument.
</dd>
<dt class="pubdef"><a id="_PL_get_arg()"><var>int</var> <strong>_PL_get_arg</strong>(<var>int
index, term_t +t, term_t -a</var>)</a></dt>
<dd class="defbody">
Same as <a class="func" href="foreigninclude.html#PL_get_arg()">PL_get_arg()</a>,
but no checking is performed, neither whether <var>t</var> is actually a
term nor whether <var>index</var> is a valid argument index.
</dd>
</dl>
<p><h4 id="sec:foreign-text-with-length"><a id="sec:10.4.3.3"><span class="sec-nr">10.4.3.3</span> <span class="sec-title">Exchanging
text using length and string</span></a></h4>
<a id="sec:foreign-text-with-length"></a>
<p>All internal text representation in SWI-Prolog is represented using
<code>char *</code> plus length and allow for <em>0-bytes</em> in them.
The foreign library supports this by implementing a *_nchars() function
for each applicable *_chars() function. Below we briefly present the
signatures of these functions. For full documentation consult the
*_chars() function.
<dl class="latex">
<dt class="pubdef"><a id="PL_get_atom_nchars()"><var>int</var> <strong>PL_get_atom_nchars</strong>(<var>term_t
t, size_t *len, char **s</var>)</a></dt>
<dd class="defbody">
See <a class="func" href="foreigninclude.html#PL_get_atom_chars()">PL_get_atom_chars()</a>.
</dd>
<dt class="pubdef"><a id="PL_get_list_nchars()"><var>int</var> <strong>PL_get_list_nchars</strong>(<var>term_t
t, size_t *len, char **s</var>)</a></dt>
<dd class="defbody">
See <a class="func" href="foreigninclude.html#PL_get_list_chars()">PL_get_list_chars()</a>.
</dd>
<dt class="pubdef"><a id="PL_get_nchars()"><var>int</var> <strong>PL_get_nchars</strong>(<var>term_t
t, size_t *len, char **s, unsigned int flags</var>)</a></dt>
<dd class="defbody">
See <a class="func" href="foreigninclude.html#PL_get_chars()">PL_get_chars()</a>.
</dd>
<dt class="pubdef"><a id="PL_put_atom_nchars()"><var>int</var> <strong>PL_put_atom_nchars</strong>(<var>term_t
t, size_t len, const char *s</var>)</a></dt>
<dd class="defbody">
See <a class="func" href="foreigninclude.html#PL_put_atom_chars()">PL_put_atom_chars()</a>.
</dd>
<dt class="pubdef"><a id="PL_put_string_nchars()"><var>int</var> <strong>PL_put_string_nchars</strong>(<var>term_t
t, size_t len, const char *s</var>)</a></dt>
<dd class="defbody">
See <a class="func" href="foreigninclude.html#PL_put_string_chars()">PL_put_string_chars()</a>.
</dd>
<dt class="pubdef"><a id="PL_put_list_ncodes()"><var>int</var> <strong>PL_put_list_ncodes</strong>(<var>term_t
t, size_t len, const char *s</var>)</a></dt>
<dd class="defbody">
See <b>PL_put_list_codes()</b>.
</dd>
<dt class="pubdef"><a id="PL_put_list_nchars()"><var>int</var> <strong>PL_put_list_nchars</strong>(<var>term_t
t, size_t len, const char *s</var>)</a></dt>
<dd class="defbody">
See <a class="func" href="foreigninclude.html#PL_put_list_chars()">PL_put_list_chars()</a>.
</dd>
<dt class="pubdef"><a id="PL_unify_atom_nchars()"><var>int</var> <strong>PL_unify_atom_nchars</strong>(<var>term_t
t, size_t len, const char *s</var>)</a></dt>
<dd class="defbody">
See <a class="func" href="foreigninclude.html#PL_unify_atom_chars()">PL_unify_atom_chars()</a>.
</dd>
<dt class="pubdef"><a id="PL_unify_string_nchars()"><var>int</var> <strong>PL_unify_string_nchars</strong>(<var>term_t
t, size_t len, const char *s</var>)</a></dt>
<dd class="defbody">
See <a class="func" href="foreigninclude.html#PL_unify_string_chars()">PL_unify_string_chars()</a>.
</dd>
<dt class="pubdef"><a id="PL_unify_list_ncodes()"><var>int</var> <strong>PL_unify_list_ncodes</strong>(<var>term_t
t, size_t len, const char *s</var>)</a></dt>
<dd class="defbody">
See <b>PL_unify_codes()</b>.
</dd>
<dt class="pubdef"><a id="PL_unify_list_nchars()"><var>int</var> <strong>PL_unify_list_nchars</strong>(<var>term_t
t, size_t len, const char *s</var>)</a></dt>
<dd class="defbody">
See <a class="func" href="foreigninclude.html#PL_unify_list_chars()">PL_unify_list_chars()</a>.
</dd>
</dl>
<p>In addition, the following functions are available for creating and
inspecting atoms:
<dl class="latex">
<dt class="pubdef"><a id="PL_new_atom_nchars()"><var>atom_t</var> <strong>PL_new_atom_nchars</strong>(<var>size_t
len, const char *s</var>)</a></dt>
<dd class="defbody">
Create a new atom as <a class="func" href="foreigninclude.html#PL_new_atom()">PL_new_atom()</a>,
but using the given length and characters. If <var>len</var> is <code>(size_t)-1</code>,
it is computed from <var>s</var> using strlen().</dd>
<dt class="pubdef"><a id="PL_atom_nchars()"><var>const char *</var> <strong>PL_atom_nchars</strong>(<var>atom_t
a, size_t *len</var>)</a></dt>
<dd class="defbody">
Extract the text and length of an atom.
</dd>
</dl>
<p><h4 id="sec:foreign-unicode"><a id="sec:10.4.3.4"><span class="sec-nr">10.4.3.4</span> <span class="sec-title">Wide-character
versions</span></a></h4>
<a id="sec:foreign-unicode"></a>
<p>Support for exchange of wide-character strings is still under
consideration. The functions dealing with 8-bit character strings return
failure when operating on a wide-character atom or Prolog string object.
The functions below can extract and unify both 8-bit and wide atoms and
string objects. Wide character strings are represented as C arrays of
objects of the type <code>pl_wchar_t</code>, which is guaranteed to be
the same as <code>wchar_t</code> on platforms supporting this type. For
example, on MS-Windows, this represents 16-bit UCS2 characters, while
using the GNU C library (glibc) this represents 32-bit UCS4 characters.
<dl class="latex">
<dt class="pubdef"><a id="PL_new_atom_wchars()"><var>atom_t</var> <strong>PL_new_atom_wchars</strong>(<var>size_t
len, const pl_wchar_t *s</var>)</a></dt>
<dd class="defbody">
Create atom from wide-character string as <a class="func" href="foreigninclude.html#PL_new_atom_nchars()">PL_new_atom_nchars()</a>
does for ISO-Latin-1 strings. If <var>s</var> only contains ISO-Latin-1
characters a normal byte-array atom is created. If <var>len</var> is <code>(size_t)-1</code>,
it is computed from <var>s</var> using wcslen().</dd>
<dt class="pubdef"><a id="PL_atom_wchars()"><var>pl_wchar_t*</var> <strong>PL_atom_wchars</strong>(<var>atom_t
atom, int *len</var>)</a></dt>
<dd class="defbody">
Extract characters from a wide-character atom. Succeeds on any atom
marked as `text'. If the underlying atom is a wide-character atom, the
returned pointer is a pointer into the atom structure. If it is an
ISO-Latin-1 character, the returned pointer comes from Prolog's `buffer
ring' (see <a class="func" href="foreigninclude.html#PL_get_chars()">PL_get_chars()</a>).</dd>
<dt class="pubdef"><a id="PL_get_wchars()"><var>int</var> <strong>PL_get_wchars</strong>(<var>term_t
t, size_t *len, pl_wchar_t **s, unsigned flags</var>)</a></dt>
<dd class="defbody">
Wide-character version of <a class="func" href="foreigninclude.html#PL_get_chars()">PL_get_chars()</a>.
The <var>flags</var> argument is the same as for <a class="func" href="foreigninclude.html#PL_get_chars()">PL_get_chars()</a>.</dd>
<dt class="pubdef"><a id="PL_unify_wchars()"><var>int</var> <strong>PL_unify_wchars</strong>(<var>term_t
t, int type, size_t len, const pl_wchar_t *s</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with a textual representation of the C wide-character
array <var>s</var>. The <var>type</var> argument defines the Prolog
representation and is one of <code>PL_ATOM</code>, <code>PL_STRING</code>,
<code>PL_CODE_LIST</code> or <code>PL_CHAR_LIST</code>.
</dd>
<dt class="pubdef"><a id="PL_unify_wchars_diff()"><var>int</var> <strong>PL_unify_wchars_diff</strong>(<var>term_t
+t, term_t -tail, int type, size_t len, const pl_wchar_t *s</var>)</a></dt>
<dd class="defbody">
Difference list version of <a class="func" href="foreigninclude.html#PL_unify_wchars()">PL_unify_wchars()</a>,
only supporting the types <code>PL_CODE_LIST</code> and <code>PL_CHAR_LIST</code>.
It serves two purposes. It allows for returning very long lists from
data read from a stream without the need for a resizing buffer in C.
Also, the use of difference lists is often practical for further
processing in Prolog. Examples can be found in <code>packages/clib/readutil.c</code>
from the source distribution.
</dd>
</dl>
<p><h4 id="sec:foreign-read-list"><a id="sec:10.4.3.5"><span class="sec-nr">10.4.3.5</span> <span class="sec-title">Reading
a list</span></a></h4>
<a id="sec:foreign-read-list"></a>
<p>The functions from this section are intended to read a Prolog list
from C. Suppose we expect a list of atoms; the following code will print
the atoms, each on a line:
<pre class="code">
foreign_t
pl_write_atoms(term_t l)
{ term_t head = PL_new_term_ref(); /* the elements */
term_t list = PL_copy_term_ref(l); /* copy (we modify list) */
while( PL_get_list(list, head, list) )
{ char *s;
if ( PL_get_atom_chars(head, &s) )
Sprintf("%s\n", s);
else
PL_fail;
}
return PL_get_nil(list); /* test end for [] */
}
</pre>
<p>Note that as of version 7, lists have a new representation
unless the option <strong>--traditional</strong> is used. see <a class="sec" href="ext-lists.html">section
5.1</a>.
<dl class="latex">
<dt class="pubdef"><a id="PL_get_list()"><var>int</var> <strong>PL_get_list</strong>(<var>term_t
+l, term_t -h, term_t -t</var>)</a></dt>
<dd class="defbody">
If <var>l</var> is a list and not the empty list, assign a term
reference to the head to <var>h</var> and to the tail to <var>t</var>.</dd>
<dt class="pubdef"><a id="PL_get_head()"><var>int</var> <strong>PL_get_head</strong>(<var>term_t
+l, term_t -h</var>)</a></dt>
<dd class="defbody">
If <var>l</var> is a list and not the empty list, assign a term
reference to the head to <var>h</var>.</dd>
<dt class="pubdef"><a id="PL_get_tail()"><var>int</var> <strong>PL_get_tail</strong>(<var>term_t
+l, term_t -t</var>)</a></dt>
<dd class="defbody">
If <var>l</var> is a list and not the empty list, assign a term
reference to the tail to <var>t</var>.</dd>
<dt class="pubdef"><a id="PL_get_nil()"><var>int</var> <strong>PL_get_nil</strong>(<var>term_t
+l</var>)</a></dt>
<dd class="defbody">
Succeeds if <var>l</var> represents the list termination constant.</dd>
<dt class="pubdef"><a id="PL_skip_list()"><var>int</var> <strong>PL_skip_list</strong>(<var>term_t
+list, term_t -tail, size_t *len</var>)</a></dt>
<dd class="defbody">
This is a multi-purpose function to deal with lists. It allows for
finding the length of a list, checking whether something is a list, etc.
The reference <var>tail</var> is set to point to the end of the list,
<var>len</var> is filled with the number of list-cells skipped, and the
return value indicates the status of the list:
<dl class="latex">
<dt><a id="PL_LIST"><strong>PL_LIST</strong></a></dt>
<dd class="defbody">
The list is a `proper' list: one that ends in the list terminator
constant and <var>tail</var> is filled with the terminator constant.</dd>
<dt><a id="PL_PARTIAL_LIST"><strong>PL_PARTIAL_LIST</strong></a></dt>
<dd class="defbody">
The list is a `partial' list: one that ends in a variable and
<var>tail</var> is a reference to this variable.</dd>
<dt><a id="PL_CYCLIC_TERM"><strong>PL_CYCLIC_TERM</strong></a></dt>
<dd class="defbody">
The list is cyclic (e.g. X = [a|X]). <var>tail</var> points to an
arbitrary cell of the list and <var>len</var> is at most twice the cycle
length of the list.</dd>
<dt><a id="PL_NOT_A_LIST"><strong>PL_NOT_A_LIST</strong></a></dt>
<dd class="defbody">
The term <var>list</var> is not a list at all. <var>tail</var> is bound
to the non-list term and <var>len</var> is set to the number of
list-cells skipped.
</dd>
</dl>
<p>It is allowed to pass 0 for <var>tail</var> and <code>NULL</code> for <var>len</var>.
</dd>
</dl>
<p><h4 id="sec:foreign-write"><a id="sec:10.4.3.6"><span class="sec-nr">10.4.3.6</span> <span class="sec-title">An
example: defining write/1 in C</span></a></h4>
<a id="sec:foreign-write"></a>
<p><a class="fig" href="foreigninclude.html#fig:pl-display">Figure 7</a>
shows a simplified definition of <a id="idx:write1:1840"></a><a class="pred" href="termrw.html#write/1">write/1</a>
to illustrate the described functions. This simplified version does not
deal with operators. It is called <a id="idx:display1:1841"></a><span class="pred-ext">display/1</span>,
because it mimics closely the behaviour of this Edinburgh predicate.
<pre class="code">
foreign_t
pl_display(term_t t)
{ functor_t functor;
int arity, len, n;
char *s;
switch( PL_term_type(t) )
{ case PL_VARIABLE:
case PL_ATOM:
case PL_INTEGER:
case PL_FLOAT:
PL_get_chars(t, &s, CVT_ALL);
Sprintf("%s", s);
break;
case PL_STRING:
PL_get_string_chars(t, &s, &len);
Sprintf("\"%s\"", s);
break;
case PL_TERM:
{ term_t a = PL_new_term_ref();
PL_get_name_arity(t, &name, &arity);
Sprintf("%s(", PL_atom_chars(name));
for(n=1; n<=arity; n++)
{ PL_get_arg(n, t, a);
if ( n > 1 )
Sprintf(", ");
pl_display(a);
}
Sprintf(")");
break;
default:
PL_fail; /* should not happen */
}
}
PL_succeed;
}
</pre>
<div class="caption"><b>Figure 7 : </b>A Foreign definition of <a id="idx:display1:1842"></a><span class="pred-ext">display/1</span></div>
<a id="fig:pl-display"></a>
<p><h3 id="sec:foreign-term-construct"><a id="sec:10.4.4"><span class="sec-nr">10.4.4</span> <span class="sec-title">Constructing
Terms</span></a></h3>
<a id="sec:foreign-term-construct"></a>
<p>Terms can be constructed using functions from the <code>PL_put_*()</code>
and
<code>PL_cons_*()</code> families. This approach builds the term
`inside-out', starting at the leaves and subsequently creating compound
terms. Alternatively, terms may be created `top-down', first creating a
compound holding only variables and subsequently unifying the arguments.
This section discusses functions for the first approach. This approach
is generally used for creating arguments for <a class="func" href="foreigninclude.html#PL_call()">PL_call()</a>
and
<a class="func" href="foreigninclude.html#PL_open_query()">PL_open_query()</a>.
<dl class="latex">
<dt class="pubdef"><a id="PL_put_variable()"><var>void</var> <strong>PL_put_variable</strong>(<var>term_t
-t</var>)</a></dt>
<dd class="defbody">
Put a fresh variable in the term, resetting the term reference to its
initial state.<sup class="fn">152<span class="fn-text">Older versions
created a variable on the global stack.</span></sup>
</dd>
<dt class="pubdef"><a id="PL_put_atom()"><var>void</var> <strong>PL_put_atom</strong>(<var>term_t
-t, atom_t a</var>)</a></dt>
<dd class="defbody">
Put an atom in the term reference from a handle. See also
<a class="func" href="foreigninclude.html#PL_new_atom()">PL_new_atom()</a>
and <a class="func" href="foreigninclude.html#PL_atom_chars()">PL_atom_chars()</a>.
</dd>
<dt class="pubdef"><a id="PL_put_bool()"><var>void</var> <strong>PL_put_bool</strong>(<var>term_t
-t, int val</var>)</a></dt>
<dd class="defbody">
Put one of the atoms <code>true</code> or <code>false</code> in the term
reference See also <a class="func" href="foreigninclude.html#PL_put_atom()">PL_put_atom()</a>, <a class="func" href="foreigninclude.html#PL_unify_bool()">PL_unify_bool()</a>
and <a class="func" href="foreigninclude.html#PL_get_bool()">PL_get_bool()</a>.
</dd>
<dt class="pubdef"><a id="PL_put_atom_chars()"><var>int</var> <strong>PL_put_atom_chars</strong>(<var>term_t
-t, const char *chars</var>)</a></dt>
<dd class="defbody">
Put an atom in the term reference constructed from the zero-terminated
string. The string itself will never be referenced by Prolog after this
function.
</dd>
<dt class="pubdef"><a id="PL_put_string_chars()"><var>int</var> <strong>PL_put_string_chars</strong>(<var>term_t
-t, const char *chars</var>)</a></dt>
<dd class="defbody">
Put a zero-terminated string in the term reference. The data will be
copied. See also <a class="func" href="foreigninclude.html#PL_put_string_nchars()">PL_put_string_nchars()</a>.
</dd>
<dt class="pubdef"><a id="PL_put_string_nchars()"><var>int</var> <strong>PL_put_string_nchars</strong>(<var>term_t
-t, size_t len, const char *chars</var>)</a></dt>
<dd class="defbody">
<p>Put a string, represented by a length/start pointer pair in the term
reference. The data will be copied. This interface can deal with 0-bytes
in the string. See also <a class="sec" href="foreigninclude.html">section
10.4.20</a>.
</dd>
<dt class="pubdef"><a id="PL_put_list_chars()"><var>int</var> <strong>PL_put_list_chars</strong>(<var>term_t
-t, const char *chars</var>)</a></dt>
<dd class="defbody">
Put a list of ASCII values in the term reference.
</dd>
<dt class="pubdef"><a id="PL_put_integer()"><var>int</var> <strong>PL_put_integer</strong>(<var>term_t
-t, long i</var>)</a></dt>
<dd class="defbody">
Put a Prolog integer in the term reference.
</dd>
<dt class="pubdef"><a id="PL_put_int64()"><var>int</var> <strong>PL_put_int64</strong>(<var>term_t
-t, int64_t i</var>)</a></dt>
<dd class="defbody">
Put a Prolog integer in the term reference.
</dd>
<dt class="pubdef"><a id="PL_put_pointer()"><var>int</var> <strong>PL_put_pointer</strong>(<var>term_t
-t, void *ptr</var>)</a></dt>
<dd class="defbody">
Put a Prolog integer in the term reference. Provided <var>ptr</var> is
in the `malloc()-area', <a class="func" href="foreigninclude.html#PL_get_pointer()">PL_get_pointer()</a>
will get the pointer back.
</dd>
<dt class="pubdef"><a id="PL_put_float()"><var>int</var> <strong>PL_put_float</strong>(<var>term_t
-t, double f</var>)</a></dt>
<dd class="defbody">
Put a floating-point value in the term reference.</dd>
<dt class="pubdef"><a id="PL_put_functor()"><var>int</var> <strong>PL_put_functor</strong>(<var>term_t
-t, functor_t functor</var>)</a></dt>
<dd class="defbody">
Create a new compound term from <var>functor</var> and bind <var>t</var>
to this term. All arguments of the term will be variables. To create a
term with instantiated arguments, either instantiate the arguments using
the <code>PL_unify_*()</code> functions or use <a class="func" href="foreigninclude.html#PL_cons_functor()">PL_cons_functor()</a>.</dd>
<dt class="pubdef"><a id="PL_put_list()"><var>int</var> <strong>PL_put_list</strong>(<var>term_t
-l</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_put_functor()">PL_put_functor()</a>,
using the list-cell functor. Note that on classical Prolog systems or in
SWI-Prolog using the option
<strong>--traditional</strong>, this is <a class="function" href="arith.html#f-./2">./2</a>,
while on SWI-Prolog version 7 this is <b>\Scons/2</b>.</dd>
<dt class="pubdef"><a id="PL_put_nil()"><var>int</var> <strong>PL_put_nil</strong>(<var>term_t
-l</var>)</a></dt>
<dd class="defbody">
Put the list terminator constant in <var>l</var>. Always returns
<code>TRUE</code>. Note that in classical Prolog systems or in
SWI-Prolog using the option <strong>--traditional</strong>, this is the
same as
<code><a class="func" href="foreigninclude.html#PL_put_atom_chars()">PL_put_atom_chars("[]")</a></code>.
See <a class="sec" href="ext-lists.html">section 5.1</a>.</dd>
<dt class="pubdef"><a id="PL_put_term()"><var>void</var> <strong>PL_put_term</strong>(<var>term_t
-t1, term_t +t2</var>)</a></dt>
<dd class="defbody">
Make <var>t1</var> point to the same term as <var>t2</var>.</dd>
<dt class="pubdef"><a id="PL_cons_functor()"><var>int</var> <strong>PL_cons_functor</strong>(<var>term_t
-h, functor_t f, ...</var>)</a></dt>
<dd class="defbody">
Create a term whose arguments are filled from a variable argument list
holding the same number of <code>term_t</code> objects as the arity of
the functor. To create the term <code>animal(gnu, 50)</code>, use:
<pre class="code">
{ term_t a1 = PL_new_term_ref();
term_t a2 = PL_new_term_ref();
term_t t = PL_new_term_ref();
functor_t animal2;
/* animal2 is a constant that may be bound to a global
variable and re-used
*/
animal2 = PL_new_functor(PL_new_atom("animal"), 2);
PL_put_atom_chars(a1, "gnu");
PL_put_integer(a2, 50);
PL_cons_functor(t, animal2, a1, a2);
}
</pre>
<p>After this sequence, the term references <var>a1</var> and <var>a2</var>
may be used for other purposes.
</dd>
<dt class="pubdef"><a id="PL_cons_functor_v()"><var>int</var> <strong>PL_cons_functor_v</strong>(<var>term_t
-h, functor_t f, term_t a0</var>)</a></dt>
<dd class="defbody">
Create a compound term like <a class="func" href="foreigninclude.html#PL_cons_functor()">PL_cons_functor()</a>,
but <var>a0</var> is an array of term references as returned by <a class="func" href="foreigntypes.html#PL_new_term_refs()">PL_new_term_refs()</a>.
The length of this array should match the number of arguments required
by the functor.
</dd>
<dt class="pubdef"><a id="PL_cons_list()"><var>int</var> <strong>PL_cons_list</strong>(<var>term_t
-l, term_t +h, term_t +t</var>)</a></dt>
<dd class="defbody">
Create a list (cons-) cell in <var>l</var> from the head <var>h</var>
and tail <var>t</var>. The code below creates a list of atoms from a <code>char
**</code>. The list is built tail-to-head. The <code>PL_unify_*()</code>
functions can be used to build a list head-to-tail.
<pre class="code">
void
put_list(term_t l, int n, char **words)
{ term_t a = PL_new_term_ref();
PL_put_nil(l);
while( --n >= 0 )
{ PL_put_atom_chars(a, words[n]);
PL_cons_list(l, a, l);
}
}
</pre>
<p>Note that <var>l</var> can be redefined within a <code>PL_cons_list</code>
call as shown here because operationally its old value is consumed
before its new value is set.
</dd>
</dl>
<p><h3 id="sec:foreign-unify"><a id="sec:10.4.5"><span class="sec-nr">10.4.5</span> <span class="sec-title">Unifying
data</span></a></h3>
<a id="sec:foreign-unify"></a>
<p>The functions of this section <em>unify</em> terms with other terms
or translated C data structures. Except for <a class="func" href="foreigninclude.html#PL_unify()">PL_unify()</a>,
these functions are specific to SWI-Prolog. They have been introduced
because they shorten the code for returning data to Prolog and at the
same time make this more efficient by avoiding the need to allocate
temporary term references and reduce the number of calls to the Prolog
API. Consider the case where we want a foreign function to return the
host name of the machine Prolog is running on. Using the <code>PL_get_*()</code>
and <code>PL_put_*()</code> functions, the code becomes:
<pre class="code">
foreign_t
pl_hostname(term_t name)
{ char buf[100];
if ( gethostname(buf, sizeof(buf)) )
{ term_t tmp = PL_new_term_ref();
PL_put_atom_chars(tmp, buf);
return PL_unify(name, tmp);
}
PL_fail;
}
</pre>
<p>Using <a class="func" href="foreigninclude.html#PL_unify_atom_chars()">PL_unify_atom_chars()</a>,
this becomes:
<pre class="code">
foreign_t
pl_hostname(term_t name)
{ char buf[100];
if ( gethostname(buf, sizeof(buf)) )
return PL_unify_atom_chars(name, buf);
PL_fail;
}
</pre>
<p>Note that unification functions that perform multiple bindings may
leave part of the bindings in case of failure. See <a class="func" href="foreigninclude.html#PL_unify()">PL_unify()</a>
for details.
<dl class="latex">
<dt class="pubdef"><a id="PL_unify()"><var>int</var> <strong>PL_unify</strong>(<var>term_t
?t1, term_t ?t2</var>)</a></dt>
<dd class="defbody">
Unify two Prolog terms and return <code>TRUE</code> on success.
<p>Care is needed if <a class="func" href="foreigninclude.html#PL_unify()">PL_unify()</a>
returns <code>FAIL</code> and the foreign function does not <em>immediately</em>
return to Prolog with <code>FAIL</code>. Unification may perform
multiple changes to either <var>t1</var> or <var>t2</var>. A failing
unification may have created bindings before failure is detected. <em>Already
created bindings are not undone</em>. For example, calling <a class="func" href="foreigninclude.html#PL_unify()">PL_unify()</a>
on <code>a(X, a)</code> and <code>a(c,b)</code> binds
<var>X</var> to <code>c</code> and fails when trying to unify <code>a</code>
to
<code>b</code>. If control remains in C or even if we want to return
success to Prolog, we <em>must</em> undo such bindings. This is achieved
using
<a class="func" href="foreigninclude.html#PL_open_foreign_frame()">PL_open_foreign_frame()</a>
and <a class="func" href="foreigninclude.html#PL_rewind_foreign_frame()">PL_rewind_foreign_frame()</a>,
as shown in the snippet below.
<pre class="code">
{ fid_t fid = PL_open_foreign_frame();
...
if ( !PL_unify(t1, t2) )
PL_rewind_foreign_frame(fid);
...
PL_close_foreign_frame(fid);
}
</pre>
<p>In addition, <a class="func" href="foreigninclude.html#PL_unify()">PL_unify()</a>
may have failed on an <b>exception</b>, typically a resource (stack)
overflow. This can be tested using
<a class="func" href="foreigninclude.html#PL_exception()">PL_exception()</a>,
passing 0 (zero) for the query-id argument. Foreign functions that
encounter an exception must return <code>FAIL</code> to Prolog as soon
as possible or call <a class="func" href="foreigninclude.html#PL_clear_exception()">PL_clear_exception()</a>
if they wish to ignore the exception.</dd>
<dt class="pubdef"><a id="PL_unify_atom()"><var>int</var> <strong>PL_unify_atom</strong>(<var>term_t
?t, atom_t a</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with the atom <var>a</var> and return non-zero on
success.</dd>
<dt class="pubdef"><a id="PL_unify_bool()"><var>int</var> <strong>PL_unify_bool</strong>(<var>term_t
?t, int a</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with either <code>true</code> or <code>false</code>.</dd>
<dt class="pubdef"><a id="PL_unify_chars()"><var>int</var> <strong>PL_unify_chars</strong>(<var>term_t
?t, int flags, size_t len, const char *chars</var>)</a></dt>
<dd class="defbody">
New function to deal with unification of <code>char*</code> with various
encodings to a Prolog representation. The <var>flags</var> argument is a
bitwise <em>or</em> specifying the Prolog target type and the encoding
of
<var>chars</var>. A Prolog type is one of <code>PL_ATOM</code>, <code>PL_STRING</code>,
<code>PL_CODE_LIST</code> or <code>PL_CHAR_LIST</code>. A representation
is one of
<code>REP_ISO_LATIN_1</code>, <code>REP_UTF8</code> or <code>REP_MB</code>.
See
<a class="func" href="foreigninclude.html#PL_get_chars()">PL_get_chars()</a>
for a definition of the representation types. If
<var>len</var> is <code>-1</code> <var>chars</var> must be
zero-terminated and the length is computed from <var>chars</var> using
strlen().
<p>If <var>flags</var> includes <code>PL_DIFF_LIST</code> and type is
one of
<code>PL_CODE_LIST</code> or <code>PL_CHAR_LIST</code>, the text is
converted to a <em>difference list</em>. The tail of the difference list
is
<var>t+1</var>.</dd>
<dt class="pubdef"><a id="PL_unify_atom_chars()"><var>int</var> <strong>PL_unify_atom_chars</strong>(<var>term_t
?t, const char *chars</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with an atom created from <var>chars</var> and return
non-zero on success.</dd>
<dt class="pubdef"><a id="PL_unify_list_chars()"><var>int</var> <strong>PL_unify_list_chars</strong>(<var>term_t
?t, const char *chars</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with a list of ASCII characters constructed from
<var>chars</var>.</dd>
<dt class="pubdef"><a id="PL_unify_string_chars()"><var>void</var> <strong>PL_unify_string_chars</strong>(<var>term_t
?t, const char *chars</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with a Prolog string object created from the
zero-terminated string <var>chars</var>. The data will be copied. See
also <a class="func" href="foreigninclude.html#PL_unify_string_nchars()">PL_unify_string_nchars()</a>.
</dd>
<dt class="pubdef"><a id="PL_unify_string_nchars()"><var>void</var> <strong>PL_unify_string_nchars</strong>(<var>term_t
?t, size_t len, const char *chars</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with a Prolog string object created from the string
created from the <var>len</var>/<var>chars</var> pair. The data will be
copied. This interface can deal with 0-bytes in the string. See also
<a class="sec" href="foreigninclude.html">section 10.4.20</a>.</dd>
<dt class="pubdef"><a id="PL_unify_integer()"><var>int</var> <strong>PL_unify_integer</strong>(<var>term_t
?t, intptr_t n</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with a Prolog integer from <var>n</var>.
</dd>
<dt class="pubdef"><a id="PL_unify_int64()"><var>int</var> <strong>PL_unify_int64</strong>(<var>term_t
?t, int64_t n</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with a Prolog integer from <var>n</var>.
</dd>
<dt class="pubdef"><a id="PL_unify_float()"><var>int</var> <strong>PL_unify_float</strong>(<var>term_t
?t, double f</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with a Prolog float from <var>f</var>.
</dd>
<dt class="pubdef"><a id="PL_unify_pointer()"><var>int</var> <strong>PL_unify_pointer</strong>(<var>term_t
?t, void *ptr</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with a Prolog integer describing the pointer. See
also
<a class="func" href="foreigninclude.html#PL_put_pointer()">PL_put_pointer()</a>
and <a class="func" href="foreigninclude.html#PL_get_pointer()">PL_get_pointer()</a>.</dd>
<dt class="pubdef"><a id="PL_unify_functor()"><var>int</var> <strong>PL_unify_functor</strong>(<var>term_t
?t, functor_t f</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is a compound term with the given functor, just succeed.
If it is unbound, create a term and bind the variable, else fail. Note
that this function does not create a term if the argument is already
instantiated. If <var>f</var> is a functor with arity 0, <var>t</var> is
unified with an atom. See also <a class="func" href="foreigninclude.html#PL_unify_compound()">PL_unify_compound()</a>.</dd>
<dt class="pubdef"><a id="PL_unify_compound()"><var>int</var> <strong>PL_unify_compound</strong>(<var>term_t
?t, functor_t f</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is a compound term with the given functor, just succeed.
If it is unbound, create a term and bind the variable, else fail. Note
that this function does not create a term if the argument is already
instantiated. If <var>f</var> is a functor with arity 0, <var>t</var> is
unified with compound without arguments. See also
<a class="func" href="foreigninclude.html#PL_unify_functor()">PL_unify_functor()</a>.</dd>
<dt class="pubdef"><a id="PL_unify_list()"><var>int</var> <strong>PL_unify_list</strong>(<var>term_t
?l, term_t -h, term_t -t</var>)</a></dt>
<dd class="defbody">
Unify <var>l</var> with a list-cell (<code>./2</code>). If successful,
write a reference to the head of the list into <var>h</var> and a
reference to the tail of the list into <var>t</var>. This reference may
be used for subsequent calls to this function. Suppose we want to return
a list of atoms from a <code>char **</code>. We could use the example
described by
<a class="func" href="foreigninclude.html#PL_put_list()">PL_put_list()</a>,
followed by a call to <a class="func" href="foreigninclude.html#PL_unify()">PL_unify()</a>,
or we can use the code below. If the predicate argument is unbound, the
difference is minimal (the code based on <a class="func" href="foreigninclude.html#PL_put_list()">PL_put_list()</a>
is probably slightly faster). If the argument is bound, the code below
may fail before reaching the end of the word list, but even if the
unification succeeds, this code avoids a duplicate (garbage) list and a
deep unification.
<pre class="code">
foreign_t
pl_get_environ(term_t env)
{ term_t l = PL_copy_term_ref(env);
term_t a = PL_new_term_ref();
extern char **environ;
char **e;
for(e = environ; *e; e++)
{ if ( !PL_unify_list(l, a, l) ||
!PL_unify_atom_chars(a, *e) )
PL_fail;
}
return PL_unify_nil(l);
}
</pre>
</dd>
<dt class="pubdef"><a id="PL_unify_nil()"><var>int</var> <strong>PL_unify_nil</strong>(<var>term_t
?l</var>)</a></dt>
<dd class="defbody">
Unify <var>l</var> with the atom <code>[]</code>.
</dd>
<dt class="pubdef"><a id="PL_unify_arg()"><var>int</var> <strong>PL_unify_arg</strong>(<var>int
index, term_t ?t, term_t ?a</var>)</a></dt>
<dd class="defbody">
Unifies the <em>index-th</em> argument (1-based) of <var>t</var> with
<var>a</var>.
</dd>
<dt class="pubdef"><a id="PL_unify_term()"><var>int</var> <strong>PL_unify_term</strong>(<var>term_t
?t, ...</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with a (normally) compound term. The remaining
arguments are a sequence of a type identifier followed by the required
arguments. This predicate is an extension to the Quintus and SICStus
foreign interface from which the SWI-Prolog foreign interface has been
derived, but has proved to be a powerful and comfortable way to create
compound terms from C. Due to the vararg packing/unpacking and the
required type-switching this interface is slightly slower than using the
primitives. Please note that some bad C compilers have fairly low limits
on the number of arguments that may be passed to a function.
<p>Special attention is required when passing numbers. C `promotes' any
integral smaller than <code>int</code> to <code>int</code>. That is, the
types
<code>char</code>, <code>short</code> and <code>int</code> are all
passed as <code>int</code>. In addition, on most 32-bit platforms <code>int</code>
and <code>long</code> are the same. Up to version 4.0.5, only <code>PL_INTEGER</code>
could be specified, which was taken from the stack as <code>long</code>.
Such code fails when passing small integral types on machines where <code>int</code>
is smaller than <code>long</code>. It is advised to use <code>PL_SHORT</code>, <code>PL_INT</code>
or <code>PL_LONG</code> as appropriate. Similarly, C compilers promote
<code>float</code> to <code>double</code> and therefore <code>PL_FLOAT</code>
and
<code>PL_DOUBLE</code> are synonyms.
<p>The type identifiers are:
<dl class="latex">
<dt><b><code>PL_VARIABLE</code> <var>none</var></b></dt>
<dd class="defbody">
No op. Used in arguments of <code>PL_FUNCTOR</code>.
</dd>
<dt><b><code>PL_BOOL</code> <var>int</var></b></dt>
<dd class="defbody">
Unify the argument with <code>true</code> or <code>false</code>.
</dd>
<dt><b><code>PL_ATOM</code> <var>atom_t</var></b></dt>
<dd class="defbody">
Unify the argument with an atom, as in <a class="func" href="foreigninclude.html#PL_unify_atom()">PL_unify_atom()</a>.
</dd>
<dt><b><code>PL_CHARS</code> <var>const char *</var></b></dt>
<dd class="defbody">
Unify the argument with an atom constructed from the C <code>char *</code>,
as in <a class="func" href="foreigninclude.html#PL_unify_atom_chars()">PL_unify_atom_chars()</a>.
</dd>
<dt><b><code>PL_NCHARS</code> <var>size_t, const char *</var></b></dt>
<dd class="defbody">
Unify the argument with an atom constructed from length and
<code>char*</code> as in <a class="func" href="foreigninclude.html#PL_unify_atom_nchars()">PL_unify_atom_nchars()</a>.
</dd>
<dt><b><code>PL_UTF8_CHARS</code> <var>const char *</var></b></dt>
<dd class="defbody">
Create an atom from a UTF-8 string.
</dd>
<dt><b><code>PL_UTF8_STRING</code> <var>const char *</var></b></dt>
<dd class="defbody">
Create a packed string object from a UTF-8 string.
</dd>
<dt><b><code>PL_MBCHARS</code> <var>const char *</var></b></dt>
<dd class="defbody">
Create an atom from a multi-byte string in the current locale.
</dd>
<dt><b><code>PL_MBCODES</code> <var>const char *</var></b></dt>
<dd class="defbody">
Create a list of character codes from a multi-byte string in the current
locale.
</dd>
<dt><b><code>PL_MBSTRING</code> <var>const char *</var></b></dt>
<dd class="defbody">
Create a packed string object from a multi-byte string in the current
locale.
</dd>
<dt><b><code>PL_NWCHARS</code> <var>size_t, const wchar_t *</var></b></dt>
<dd class="defbody">
Create an atom from a length and a wide character pointer.
</dd>
<dt><b><code>PL_NWCODES</code> <var>size_t, const wchar_t *</var></b></dt>
<dd class="defbody">
Create a list of character codes from a length and a wide character
pointer.
</dd>
<dt><b><code>PL_NWSTRING</code> <var>size_t, const wchar_t *</var></b></dt>
<dd class="defbody">
Create a packed string object from a length and a wide character
pointer.
</dd>
<dt><b><code>PL_SHORT</code> <var>short</var></b></dt>
<dd class="defbody">
Unify the argument with an integer, as in <a class="func" href="foreigninclude.html#PL_unify_integer()">PL_unify_integer()</a>.
As
<code>short</code> is promoted to <code>int</code>, <code>PL_SHORT</code>
is a synonym for <code>PL_INT</code>.
</dd>
<dt><b><code>PL_INTEGER</code> <var>long</var></b></dt>
<dd class="defbody">
Unify the argument with an integer, as in <a class="func" href="foreigninclude.html#PL_unify_integer()">PL_unify_integer()</a>.
</dd>
<dt><b><code>PL_INT</code> <var>int</var></b></dt>
<dd class="defbody">
Unify the argument with an integer, as in <a class="func" href="foreigninclude.html#PL_unify_integer()">PL_unify_integer()</a>.
</dd>
<dt><b><code>PL_LONG</code> <var>long</var></b></dt>
<dd class="defbody">
Unify the argument with an integer, as in <a class="func" href="foreigninclude.html#PL_unify_integer()">PL_unify_integer()</a>.
</dd>
<dt><b><code>PL_INT64</code> <var>int64_t</var></b></dt>
<dd class="defbody">
Unify the argument with a 64-bit integer, as in <a class="func" href="foreigninclude.html#PL_unify_int64()">PL_unify_int64()</a>.
</dd>
<dt><b><code>PL_INTPTR</code> <var>intptr_t</var></b></dt>
<dd class="defbody">
Unify the argument with an integer with the same width as a pointer. On
most machines this is the same as <code>PL_LONG</code>. but on 64-bit
MS-Windows pointers are 64 bits while longs are only 32 bits.
</dd>
<dt><b><code>PL_DOUBLE</code> <var>double</var></b></dt>
<dd class="defbody">
Unify the argument with a float, as in <a class="func" href="foreigninclude.html#PL_unify_float()">PL_unify_float()</a>.
Note that, as the argument is passed using the C vararg conventions, a
float must be casted to a double explicitly.
</dd>
<dt><b><code>PL_FLOAT</code> <var>double</var></b></dt>
<dd class="defbody">
Unify the argument with a float, as in <a class="func" href="foreigninclude.html#PL_unify_float()">PL_unify_float()</a>.
</dd>
<dt><b><code>PL_POINTER</code> <var>void *</var></b></dt>
<dd class="defbody">
Unify the argument with a pointer, as in <a class="func" href="foreigninclude.html#PL_unify_pointer()">PL_unify_pointer()</a>.
</dd>
<dt><b><code>PL_STRING</code> <var>const char *</var></b></dt>
<dd class="defbody">
Unify the argument with a string object, as in <a class="func" href="foreigninclude.html#PL_unify_string_chars()">PL_unify_string_chars()</a>.
</dd>
<dt><b><code>PL_TERM</code> <var>term_t</var></b></dt>
<dd class="defbody">
Unify a subterm. Note this may be the return value of a <a class="func" href="foreigntypes.html#PL_new_term_ref()">PL_new_term_ref()</a>
call to get access to a variable.
</dd>
<dt><b><code>PL_FUNCTOR</code> <var>functor_t, ...</var></b></dt>
<dd class="defbody">
Unify the argument with a compound term. This specification should be
followed by exactly as many specifications as the number of arguments of
the compound term.
</dd>
<dt><b><code>PL_FUNCTOR_CHARS</code> <var>const char *name, int arity,
...</var></b></dt>
<dd class="defbody">
Create a functor from the given name and arity and then behave as
<code>PL_FUNCTOR</code>.
</dd>
<dt><b><code>PL_LIST</code> <var>int length, ...</var></b></dt>
<dd class="defbody">
Create a list of the indicated length. The remaining arguments contain
the elements of the list.
</dd>
</dl>
<p>For example, to unify an argument with the term <code>language(dutch)</code>,
the following skeleton may be used:
<pre class="code">
static functor_t FUNCTOR_language1;
static void
init_constants()
{ FUNCTOR_language1 = PL_new_functor(PL_new_atom("language"),1);
}
foreign_t
pl_get_lang(term_t r)
{ return PL_unify_term(r,
PL_FUNCTOR, FUNCTOR_language1,
PL_CHARS, "dutch");
}
install_t
install()
{ PL_register_foreign("get_lang", 1, pl_get_lang, 0);
init_constants();
}
</pre>
</dd>
<dt class="pubdef"><a id="PL_chars_to_term()"><var>int</var> <strong>PL_chars_to_term</strong>(<var>const
char *chars, term_t -t</var>)</a></dt>
<dd class="defbody">
Parse the string <var>chars</var> and put the resulting Prolog term into
<var>t</var>. <var>chars</var> may or may not be closed using a Prolog
full-stop (i.e., a dot followed by a blank). Returns <code>FALSE</code>
if a syntax error was encountered and <code>TRUE</code> after successful
completion. In addition to returning <code>FALSE</code>, the
exception-term is returned in <var>t</var> on a syntax error. See also <a id="idx:termtoatom2:1843"></a><a class="pred" href="manipatom.html#term_to_atom/2">term_to_atom/2</a>.
<p>The following example builds a goal term from a string and calls it.
<pre class="code">
int
call_chars(const char *goal)
{ fid_t fid = PL_open_foreign_frame();
term_t g = PL_new_term_ref();
BOOL rval;
if ( PL_chars_to_term(goal, g) )
rval = PL_call(goal, NULL);
else
rval = FALSE;
PL_discard_foreign_frame(fid);
return rval;
}
...
call_chars("consult(load)");
...
</pre>
</dd>
<dt class="pubdef"><a id="PL_wchars_to_term()"><var>int</var> <strong>PL_wchars_to_term</strong>(<var>const
pl_wchar_t *chars, term_t -t</var>)</a></dt>
<dd class="defbody">
Wide character version of <a class="func" href="foreigninclude.html#PL_chars_to_term()">PL_chars_to_term()</a>.</dd>
<dt class="pubdef"><a id="PL_quote()"><var>char *</var> <strong>PL_quote</strong>(<var>int
chr, const char *string</var>)</a></dt>
<dd class="defbody">
Return a quoted version of <var>string</var>. If <var>chr</var> is
<code>'\''</code>, the result is a quoted atom. If <var>chr</var> is
<code>'"'</code>, the result is a string. The result string is stored in
the same ring of buffers as described with the <code>BUF_RING</code>
argument of <a class="func" href="foreigninclude.html#PL_get_chars()">PL_get_chars()</a>;
<p>In the current implementation, the string is surrounded by
<var>chr</var> and any occurrence of <var>chr</var> is doubled. In the
future the behaviour will depend on the
<a class="flag" href="flags.html#flag:character_escapes">character_escapes</a>
Prolog flag.
</dd>
</dl>
<p><h3 id="sec:cerror"><a id="sec:10.4.6"><span class="sec-nr">10.4.6</span> <span class="sec-title">Convenient
functions to generate Prolog exceptions</span></a></h3>
<a id="sec:cerror"></a>
<p>The typical implementation of a foreign predicate first uses the
PL_get_*() functions to extract C data types from the Prolog terms.
Failure of any of these functions is normally because the Prolog term is
of the wrong type. The *_ex() family of functions are wrappers around
(mostly) the PL_get_*() functions, such that we can write code in the
style below and get proper exceptions if an argument is uninstantiated
or of the wrong type.
<pre class="code">
/** set_size(+Name:atom, +Width:int, +Height:int) is det.
static foreign_t
set_size(term_t name, term_t width, term_t height)
{ char *n;
int w, h;
if ( !PL_get_chars(name, &n, CVT_ATOM|CVT_EXCEPTION) ||
!PL_get_integer_ex(with, &w) ||
!PL_get_integer_ex(height, &h) )
return FALSE;
...
}
</pre>
<dl class="latex">
<dt class="pubdef"><a id="PL_get_atom_ex()"><var>int</var> <strong>PL_get_atom_ex</strong>(<var>term_t
t, atom_t *a</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_get_atom()">PL_get_atom()</a>,
but raises a type or instantiation error if
<var>t</var> is not an atom.</dd>
<dt class="pubdef"><a id="PL_get_integer_ex()"><var>int</var> <strong>PL_get_integer_ex</strong>(<var>term_t
t, int *i</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_get_integer()">PL_get_integer()</a>,
but raises a type or instantiation error if
<var>t</var> is not an integer, or a representation error if the Prolog
integer does not fit in a C <code>int</code>.</dd>
<dt class="pubdef"><a id="PL_get_long_ex()"><var>int</var> <strong>PL_get_long_ex</strong>(<var>term_t
t, long *i</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_get_long()">PL_get_long()</a>,
but raises a type or instantiation error if
<var>t</var> is not an atom, or a representation error if the Prolog
integer does not fit in a C <code>long</code>.</dd>
<dt class="pubdef"><a id="PL_get_int64_ex()"><var>int</var> <strong>PL_get_int64_ex</strong>(<var>term_t
t, int64_t *i</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_get_int64()">PL_get_int64()</a>,
but raises a type or instantiation error if
<var>t</var> is not an atom, or a representation error if the Prolog
integer does not fit in a C <code>int64_t</code>.</dd>
<dt class="pubdef"><a id="PL_get_intptr_ex()"><var>int</var> <strong>PL_get_intptr_ex</strong>(<var>term_t
t, intptr_t *i</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_get_intptr()">PL_get_intptr()</a>,
but raises a type or instantiation error if
<var>t</var> is not an atom, or a representation error if the Prolog
integer does not fit in a C <code>intptr_t</code>.</dd>
<dt class="pubdef"><a id="PL_get_size_ex()"><var>int</var> <strong>PL_get_size_ex</strong>(<var>term_t
t, size_t *i</var>)</a></dt>
<dd class="defbody">
As <b>PL_get_size()</b>, but raises a type or instantiation error if
<var>t</var> is not an atom, or a representation error if the Prolog
integer does not fit in a C <code>size_t</code>.</dd>
<dt class="pubdef"><a id="PL_get_bool_ex()"><var>int</var> <strong>PL_get_bool_ex</strong>(<var>term_t
t, int *i</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_get_bool()">PL_get_bool()</a>,
but raises a type or instantiation error if
<var>t</var> is not an boolean.</dd>
<dt class="pubdef"><a id="PL_get_float_ex()"><var>int</var> <strong>PL_get_float_ex</strong>(<var>term_t
t, double *f</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_get_float()">PL_get_float()</a>,
but raises a type or instantiation error if
<var>t</var> is not a float.</dd>
<dt class="pubdef"><a id="PL_get_char_ex()"><var>int</var> <strong>PL_get_char_ex</strong>(<var>term_t
t, int *p, int eof</var>)</a></dt>
<dd class="defbody">
Get a character code from <var>t</var>, where <var>t</var> is either an
integer or an atom with length one. If <var>eof</var> is <code>TRUE</code>
and <var>t</var> is -1, <var>p</var> is filled with -1. Raises an
appropriate error if the conversion is not possible.</dd>
<dt class="pubdef"><a id="PL_get_pointer_ex()"><var>int</var> <strong>PL_get_pointer_ex</strong>(<var>term_t
t, void **addrp</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_get_pointer()">PL_get_pointer()</a>,
but raises a type or instantiation error if
<var>t</var> is not a pointer.</dd>
<dt class="pubdef"><a id="PL_get_list_ex()"><var>int</var> <strong>PL_get_list_ex</strong>(<var>term_t
l, term_t h, term_t t</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_get_list()">PL_get_list()</a>,
but raises a type or instantiation error if
<var>t</var> is not a list.</dd>
<dt class="pubdef"><a id="PL_get_nil_ex()"><var>int</var> <strong>PL_get_nil_ex</strong>(<var>term_t
l</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_get_nil()">PL_get_nil()</a>,
but raises a type or instantiation error if
<var>t</var> is not the empty list.</dd>
<dt class="pubdef"><a id="PL_unify_list_ex()"><var>int</var> <strong>PL_unify_list_ex</strong>(<var>term_t
l, term_t h, term_t t</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_unify_list()">PL_unify_list()</a>,
but raises a type error if <var>t</var> is not a variable, list-cell or
the empty list.</dd>
<dt class="pubdef"><a id="PL_unify_nil_ex()"><var>int</var> <strong>PL_unify_nil_ex</strong>(<var>term_t
l</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_unify_nil()">PL_unify_nil()</a>,
but raises a type error if <var>t</var> is not a variable, list-cell or
the empty list.</dd>
<dt class="pubdef"><a id="PL_unify_bool_ex()"><var>int</var> <strong>PL_unify_bool_ex</strong>(<var>term_t
t, int val</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_unify_bool()">PL_unify_bool()</a>,
but raises a type error if <var>t</var> is not a variable or a boolean.
</dd>
</dl>
<p>The second family of functions in this section simplifies the
generation of ISO compatible error terms. Any foreign function that
calls this function must return to Prolog with the return code of the
error function or the constant <code>FALSE</code>. If available, these
error functions add the name of the calling predicate to the error
context. See also <a class="func" href="foreigninclude.html#PL_raise_exception()">PL_raise_exception()</a>.
<dl class="latex">
<dt class="pubdef"><a id="PL_instantiation_error()"><var>int</var> <strong>PL_instantiation_error</strong>(<var>term_t
culprit</var>)</a></dt>
<dd class="defbody">
Raise <code>instantiation_error</code>. <var>Culprit</var> is ignored,
but should be bound to the term that is insufficiently instantiated. See
<a id="idx:instantiationerror1:1844"></a><span class="pred-ext">instantiation_error/1</span>.</dd>
<dt class="pubdef"><a id="PL_uninstantiation_error()"><var>int</var> <strong>PL_uninstantiation_error</strong>(<var>term_t
culprit</var>)</a></dt>
<dd class="defbody">
Raise <code>uninstantiation_error(culprit)</code>. This should be called
if an argument that must be unbound at entry is bound to <var>culprit</var>.
This error is typically raised for a pure output arguments such as a
newly created stream handle (e.g., the third argument of <a id="idx:open3:1845"></a><a class="pred" href="IO.html#open/3">open/3</a>).</dd>
<dt class="pubdef"><a id="PL_representation_error()"><var>int</var> <strong>PL_representation_error</strong>(<var>const
char *resource</var>)</a></dt>
<dd class="defbody">
Raise <code>representation_error(resource)</code>. See <a id="idx:representationerror1:1846"></a><span class="pred-ext">representation_error/1</span>.</dd>
<dt class="pubdef"><a id="PL_type_error()"><var>int</var> <strong>PL_type_error</strong>(<var>const
char *expected, term_t culprit</var>)</a></dt>
<dd class="defbody">
Raise <code>type_error(expected, culprit)</code>. See <a id="idx:typeerror2:1847"></a><span class="pred-ext">type_error/2</span>.</dd>
<dt class="pubdef"><a id="PL_domain_error()"><var>int</var> <strong>PL_domain_error</strong>(<var>const
char *expected, term_t culprit</var>)</a></dt>
<dd class="defbody">
Raise <code>domain_error(expected, culprit)</code>. See <a id="idx:domainerror2:1848"></a><span class="pred-ext">domain_error/2</span>.</dd>
<dt class="pubdef"><a id="PL_existence_error()"><var>int</var> <strong>PL_existence_error</strong>(<var>const
char *type, term_t culprit</var>)</a></dt>
<dd class="defbody">
Raise <code>existence_error(type, culprit)</code>. See <a id="idx:typeerror2:1849"></a><span class="pred-ext">type_error/2</span>.</dd>
<dt class="pubdef"><a id="PL_permission_error()"><var>int</var> <strong>PL_permission_error</strong>(<var>const
char *operation, const char *type, term_t culprit</var>)</a></dt>
<dd class="defbody">
Raise <code>permission_error(operation, type, culprit)</code>. See
<a id="idx:permissionerror3:1850"></a><span class="pred-ext">permission_error/3</span>.
</dd>
<dt class="pubdef"><a id="PL_resource_error()"><var>int</var> <strong>PL_resource_error</strong>(<var>const
char *resource</var>)</a></dt>
<dd class="defbody">
Raise <code>resource_error(resource)</code>. See <a id="idx:resourceerror1:1851"></a><span class="pred-ext">resource_error/1</span>.
</dd>
<dt class="pubdef"><a id="PL_syntax_error()"><var>int</var> <strong>PL_syntax_error</strong>(<var>const
char *message, IOSTREAM *in</var>)</a></dt>
<dd class="defbody">
Raise <code>syntax_error(message)</code>. If <var>arg</var> is not <code>NULL</code>,
add information about the current position of the input stream.
</dd>
</dl>
<p><h3 id="sec:blob"><a id="sec:10.4.7"><span class="sec-nr">10.4.7</span> <span class="sec-title">BLOBS:
Using atoms to store arbitrary binary data</span></a></h3>
<a id="sec:blob"></a>
<p><a id="idx:Java:1852"></a><a id="idx:COM:1853"></a>SWI-Prolog atoms
as well as strings can represent arbitrary binary data of arbitrary
length. This facility is attractive for storing foreign data such as
images in an atom. An atom is a unique handle to this data and the atom
garbage collector is able to destroy atoms that are no longer referenced
by the Prolog engine. This property of atoms makes them attractive as a
handle to foreign resources, such as Java atoms, Microsoft's COM
objects, etc., providing safe combined garbage collection.
<p>To exploit these features safely and in an organised manner, the
SWI-Prolog foreign interface allows for creating `atoms' with additional
type information. The type is represented by a structure holding C
function pointers that tell Prolog how to handle releasing the atom,
writing it, sorting it, etc. Two atoms created with different types can
represent the same sequence of bytes. Atoms are first ordered on the
rank number of the type and then on the result of the
<a class="func" href="foreigninclude.html#compare()">compare()</a>
function. Rank numbers are assigned when the type is registered.
<p><h4 id="sec:blobtype"><a id="sec:10.4.7.1"><span class="sec-nr">10.4.7.1</span> <span class="sec-title">Defining
a BLOB type</span></a></h4>
<a id="sec:blobtype"></a>
<p>The type <code>PL_blob_t</code> represents a structure with the
layout displayed below. The structure contains additional fields at the
... for internal bookkeeping as well as future extensions.
<pre class="code">
typedef struct PL_blob_t
{ uintptr_t magic; /* PL_BLOB_MAGIC */
uintptr_t flags; /* Bitwise or of PL_BLOB_* */
char * name; /* name of the type */
int (*release)(atom_t a);
int (*compare)(atom_t a, atom_t b);
int (*write)(IOSTREAM *s, atom_t a, int flags);
void (*acquire)(atom_t a);
...
} PL_blob_t;
</pre>
<p>For each type, exactly one such structure should be allocated. Its
first field must be initialised to <code>PL_BLOB_MAGIC</code>. The
<var>flags</var> is a bitwise <em>or</em> of the following constants:
<dl class="latex">
<dt><a id="PL_BLOB_TEXT"><strong>PL_BLOB_TEXT</strong></a></dt>
<dd class="defbody">
If specified the blob is assumed to contain text and is considered a
normal Prolog atom.</dd>
<dt><a id="PL_BLOB_UNIQUE"><strong>PL_BLOB_UNIQUE</strong></a></dt>
<dd class="defbody">
If specified the system ensures that the blob-handle is a unique
reference for a blob with the given type, length and content. If this
flag is not specified, each lookup creates a new blob.</dd>
<dt><a id="PL_BLOB_NOCOPY"><strong>PL_BLOB_NOCOPY</strong></a></dt>
<dd class="defbody">
By default the content of the blob is copied. Using this flag the blob
references the external data directly. The user must ensure the provided
pointer is valid as long as the atom lives. If <code>PL_BLOB_UNIQUE</code>
is also specified, uniqueness is determined by comparing the pointer
rather than the data pointed at.
</dd>
</dl>
<p>The <var>name</var> field represents the type name as available to
Prolog. See also <a id="idx:currentblob2:1854"></a><a class="pred" href="examineprog.html#current_blob/2">current_blob/2</a>.
The other fields are function pointers that must be initialised to
proper functions or <code>NULL</code> to get the default behaviour of
built-in atoms. Below are the defined member functions:
<dl class="latex">
<dt class="pubdef"><a id="acquire()"><var>void</var> <strong>acquire</strong>(<var>atom_t
a</var>)</a></dt>
<dd class="defbody">
Called if a new blob of this type is created through <a class="func" href="foreigninclude.html#PL_put_blob()">PL_put_blob()</a>
or <a class="func" href="foreigninclude.html#PL_unify_blob()">PL_unify_blob()</a>.
This callback may be used together with the release hook to deal with
reference-counted external objects.</dd>
<dt class="pubdef"><a id="release()"><var>int</var> <strong>release</strong>(<var>atom_t
a</var>)</a></dt>
<dd class="defbody">
The blob (atom) <var>a</var> is about to be released. This function can
retrieve the data of the blob using <a class="func" href="foreigninclude.html#PL_blob_data()">PL_blob_data()</a>.
If it returns <code>FALSE</code> the atom garbage collector will <em>not</em>
reclaim the atom.</dd>
<dt class="pubdef"><a id="compare()"><var>int</var> <strong>compare</strong>(<var>atom_t
a, atom_t b</var>)</a></dt>
<dd class="defbody">
Compare the blobs <var>a</var> and <var>b</var>, both of which are of
the type associated to this blob type. Return values are, as memcmp(),
<var>< 0</var> if <var>a</var> is less than <var>b</var>, <var>= 0</var>
if both are equal, and
<var>> 0</var> otherwise.</dd>
<dt class="pubdef"><a id="write()"><var>int</var> <strong>write</strong>(<var>IOSTREAM
*s, atom_t a, int flags</var>)</a></dt>
<dd class="defbody">
Write the content of the blob <var>a</var> to the stream <var>s</var>
respecting the <var>flags</var>. The <var>flags</var> are a bitwise
or of zero or more of the <code>PL_WRT_*</code> flags defined in
<code>SWI-Prolog.h</code>. This prototype is available if the
undocumented <code>SWI-Stream.h</code> is included <em>before</em>
<code>SWI-Prolog.h</code>.
<p>If this function is not provided, <a id="idx:write1:1855"></a><a class="pred" href="termrw.html#write/1">write/1</a>
emits the content of the blob for blobs of type <code>PL_BLOB_TEXT</code>
or a string of the format <code><#</code><i>hex data</i><code>></code>
for binary blobs.
</dd>
</dl>
<p>If a blob type is registered from a loadable object (shared object or
DLL) the blob type must be deregistered before the object may be
released.
<dl class="latex">
<dt class="pubdef"><a id="PL_unregister_blob_type()"><var>int</var> <strong>PL_unregister_blob_type</strong>(<var>PL_blob_t
*type</var>)</a></dt>
<dd class="defbody">
Unlink the blob type from the registered type and transform the type of
possible living blobs to <code>unregistered</code>, avoiding further
reference to the type structure, functions referred by it, as well as
the data. This function returns <code>TRUE</code> if no blobs of this
type existed and <code>FALSE</code> otherwise. <a class="func" href="foreigninclude.html#PL_unregister_blob_type()">PL_unregister_blob_type()</a>
is intended for the uninstall() hook of foreign modules, avoiding
further references to the module.
</dd>
</dl>
<p><h4 id="sec:blobaccess"><a id="sec:10.4.7.2"><span class="sec-nr">10.4.7.2</span> <span class="sec-title">Accessing
blobs</span></a></h4>
<a id="sec:blobaccess"></a>
<p>The blob access functions are similar to the atom accessing
functions. Blobs being atoms, the atom functions operate on blobs and
vice versa. For clarity and possible future compatibility issues,
however, it is not advised to rely on this.
<dl class="latex">
<dt class="pubdef"><a id="PL_is_blob()"><var>int</var> <strong>PL_is_blob</strong>(<var>term_t
t, PL_blob_t **type</var>)</a></dt>
<dd class="defbody">
Succeeds if <var>t</var> refers to a blob, in which case <var>type</var>
is filled with the type of the blob.</dd>
<dt class="pubdef"><a id="PL_unify_blob()"><var>int</var> <strong>PL_unify_blob</strong>(<var>term_t
t, void *blob, size_t len, PL_blob_t *type</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> to a new blob constructed from the given data and
associated to the given type. See also <a class="func" href="foreigninclude.html#PL_unify_atom_nchars()">PL_unify_atom_nchars()</a>.</dd>
<dt class="pubdef"><a id="PL_put_blob()"><var>int</var> <strong>PL_put_blob</strong>(<var>term_t
t, void *blob, size_t len, PL_blob_t *type</var>)</a></dt>
<dd class="defbody">
Store the described blob in <var>t</var>. The return value indicates
whether a new blob was allocated (<code>FALSE</code>) or the blob is a
reference to an existing blob (<code>TRUE</code>). Reporting
new/existing can be used to deal with external objects having their own
reference counts. If the return is <code>TRUE</code> this reference
count must be incremented, and it must be decremented on blob
destruction callback. See also
<a class="func" href="foreigninclude.html#PL_put_atom_nchars()">PL_put_atom_nchars()</a>.</dd>
<dt class="pubdef"><a id="PL_get_blob()"><var>int</var> <strong>PL_get_blob</strong>(<var>term_t
t, void **blob, size_t *len, PL_blob_t **type</var>)</a></dt>
<dd class="defbody">
If <var>t</var> holds a blob or atom, get the data and type and return
<code>TRUE</code>. Otherwise return <code>FALSE</code>. Each result
pointer may be <code>NULL</code>, in which case the requested
information is ignored.</dd>
<dt class="pubdef"><a id="PL_blob_data()"><var>void *</var> <strong>PL_blob_data</strong>(<var>atom_t
a, size_t *len, PL_blob_t **type</var>)</a></dt>
<dd class="defbody">
Get the data and type associated to a blob. This function is mainly used
from the callback functions described in <a class="sec" href="foreigninclude.html">section
10.4.7.1</a>.
</dd>
</dl>
<p><h3 id="sec:gmpforeign"><a id="sec:10.4.8"><span class="sec-nr">10.4.8</span> <span class="sec-title">Exchanging
GMP numbers</span></a></h3>
<a id="sec:gmpforeign"></a>
<p>If SWI-Prolog is linked with the GNU Multiple Precision Arithmetic
Library (GMP, used by default), the foreign interface provides functions
for exchanging numeric values to GMP types. To access these functions
the header <code><gmp.h></code> must be included <em>before</em>
<code><SWI-Prolog.h></code>. Foreign code using GMP linked to
SWI-Prolog asks for some considerations.
<p>
<ul class="latex">
<li>SWI-Prolog normally rebinds the GMP allocation functions using
mp_set_memory_functions(). This means SWI-Prolog must be initialised
before the foreign code touches any GMP function. You can call
<code>\cfuncref{PL_action}{PL_GMP_SET_ALLOC_FUNCTIONS, TRUE}</code> to
force Prolog's GMP initialization without doing the rest of the Prolog
initialization. If you do not want Prolog rebinding the GMP allocation,
call <code>\cfuncref{PL_action}{PL_GMP_SET_ALLOC_FUNCTIONS, FALSE}</code>
<em>before</em> initializing Prolog.
<p>
<li>On Windows, each DLL has its own memory pool. To make exchange of
GMP numbers between Prolog and foreign code possible you must either let
Prolog rebind the allocation functions (default) or you must recompile
SWI-Prolog to link to a DLL version of the GMP library.
</ul>
<p>Here is an example exploiting the function mpz_nextprime():
<pre class="code">
#include <gmp.h>
#include <SWI-Prolog.h>
static foreign_t
next_prime(term_t n, term_t prime)
{ mpz_t mpz;
int rc;
mpz_init(mpz);
if ( PL_get_mpz(n, mpz) )
{ mpz_nextprime(mpz, mpz);
rc = PL_unify_mpz(prime, mpz);
} else
rc = FALSE;
mpz_clear(mpz);
return rc;
}
install_t
install()
{ PL_register_foreign("next_prime", 2, next_prime, 0);
}
</pre>
<dl class="latex">
<dt class="pubdef"><a id="PL_get_mpz()"><var>int</var> <strong>PL_get_mpz</strong>(<var>term_t
t, mpz_t mpz</var>)</a></dt>
<dd class="defbody">
If <var>t</var> represents an integer, <var>mpz</var> is filled with the
value and the function returns <code>TRUE</code>. Otherwise <var>mpz</var>
is untouched and the function returns <code>FALSE</code>. Note that <var>mpz</var>
must have been initialised before calling this function and must be
cleared using mpz_clear() to reclaim any storage associated with it.</dd>
<dt class="pubdef"><a id="PL_get_mpq()"><var>int</var> <strong>PL_get_mpq</strong>(<var>term_t
t, mpq_t mpq</var>)</a></dt>
<dd class="defbody">
If <var>t</var> is an integer or rational number (term <code>rdiv/2</code>),
<var>mpq</var> is filled with the <em>normalised</em> rational number
and the function returns <code>TRUE</code>. Otherwise <var>mpq</var> is
untouched and the function returns <code>FALSE</code>. Note that <var>mpq</var>
must have been initialised before calling this function and must be
cleared using mpq_clear() to reclaim any storage associated with it.</dd>
<dt class="pubdef"><a id="PL_unify_mpz()"><var>int</var> <strong>PL_unify_mpz</strong>(<var>term_t
t, mpz_t mpz</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with the integer value represented by <var>mpz</var>
and return
<code>TRUE</code> on success. The <var>mpz</var> argument is not
changed.</dd>
<dt class="pubdef"><a id="PL_unify_mpq()"><var>int</var> <strong>PL_unify_mpq</strong>(<var>term_t
t, mpq_t mpq</var>)</a></dt>
<dd class="defbody">
Unify <var>t</var> with a rational number represented by <var>mpq</var>
and return
<code>TRUE</code> on success. Note that <var>t</var> is unified with an
integer if the denominator is 1. The <var>mpq</var> argument is not
changed.
</dd>
</dl>
<p><h3 id="sec:calling-prolog-from-c"><a id="sec:10.4.9"><span class="sec-nr">10.4.9</span> <span class="sec-title">Calling
Prolog from C</span></a></h3>
<a id="sec:calling-prolog-from-c"></a>
<p>The Prolog engine can be called from C. There are two interfaces for
this. For the first, a term is created that could be used as an argument
to <a id="idx:call1:1856"></a><a class="pred" href="metacall.html#call/1">call/1</a>,
and then <a class="func" href="foreigninclude.html#PL_call()">PL_call()</a>
is used to call Prolog. This system is simple, but does not allow to
inspect the different answers to a non-deterministic goal and is
relatively slow as the runtime system needs to find the predicate. The
other interface is based on
<a class="func" href="foreigninclude.html#PL_open_query()">PL_open_query()</a>, <a class="func" href="foreigninclude.html#PL_next_solution()">PL_next_solution()</a>
and <a class="func" href="foreigninclude.html#PL_cut_query()">PL_cut_query()</a>
or
<a class="func" href="foreigninclude.html#PL_close_query()">PL_close_query()</a>.
This mechanism is more powerful, but also more complicated to use.
<p><h4 id="sec:foreign-predicate-handle"><a id="sec:10.4.9.1"><span class="sec-nr">10.4.9.1</span> <span class="sec-title">Predicate
references</span></a></h4>
<a id="sec:foreign-predicate-handle"></a>
<p>This section discusses the functions used to communicate about
predicates. Though a Prolog predicate may be defined or not, redefined,
etc., a Prolog predicate has a handle that is neither destroyed nor
moved. This handle is known by the type <code>predicate_t</code>.
<dl class="latex">
<dt class="pubdef"><a id="PL_pred()"><var>predicate_t</var> <strong>PL_pred</strong>(<var>functor_t
f, module_t m</var>)</a></dt>
<dd class="defbody">
Return a handle to a predicate for the specified name/arity in the given
module. This function always succeeds, creating a handle for an
undefined predicate if no handle was available. If the module argument
<var>m</var> is <code>NULL</code>, the current context module is used.</dd>
<dt class="pubdef"><a id="PL_predicate()"><var>predicate_t</var> <strong>PL_predicate</strong>(<var>const
char *name, int arity, const char* module</var>)</a></dt>
<dd class="defbody">
Same as <a class="func" href="foreigninclude.html#PL_pred()">PL_pred()</a>,
but provides a more convenient interface to the C programmer.</dd>
<dt class="pubdef"><a id="PL_predicate_info()"><var>void</var> <strong>PL_predicate_info</strong>(<var>predicate_t
p, atom_t *n, int *a, module_t *m</var>)</a></dt>
<dd class="defbody">
Return information on the predicate <var>p</var>. The name is stored
over
<var>n</var>, the arity over <var>a</var>, while <var>m</var> receives
the definition module. Note that the latter need not be the same as
specified with
<a class="func" href="foreigninclude.html#PL_predicate()">PL_predicate()</a>.
If the predicate is imported into the module given to
<a class="func" href="foreigninclude.html#PL_predicate()">PL_predicate()</a>,
this function will return the module where the predicate is defined. Any
of the arguments <var>n</var>, <var>a</var> and <var>m</var> can be
<code>NULL</code>.
</dd>
</dl>
<p><h4 id="sec:foreign-create-query"><a id="sec:10.4.9.2"><span class="sec-nr">10.4.9.2</span> <span class="sec-title">Initiating
a query from C</span></a></h4>
<a id="sec:foreign-create-query"></a>
<p>This section discusses the functions for creating and manipulating
queries from C. Note that a foreign context can have at most one active
query. This implies that it is allowed to make strictly nested calls
between C and Prolog (Prolog calls C, calls Prolog, calls C, etc.), but
it is <strong>not</strong> allowed to open multiple queries and start
generating solutions for each of them by calling <a class="func" href="foreigninclude.html#PL_next_solution()">PL_next_solution()</a>.
Be sure to call <a class="func" href="foreigninclude.html#PL_cut_query()">PL_cut_query()</a>
or <a class="func" href="foreigninclude.html#PL_close_query()">PL_close_query()</a>
on any query you opened before opening the next or returning control
back to Prolog.
<dl class="latex">
<dt class="pubdef"><a id="PL_open_query()"><var>qid_t</var> <strong>PL_open_query</strong>(<var>module_t
ctx, int flags, predicate_t p, term_t +t0</var>)</a></dt>
<dd class="defbody">
<p>Opens a query and returns an identifier for it. <var>ctx</var> is the <em>context
module</em> of the goal. When <code>NULL</code>, the context module of
the calling context will be used, or <code>user</code> if there is no
calling context (as may happen in embedded systems). Note that the
context module only matters for <em>meta-predicates</em>. See <a id="idx:metapredicate1:1857"></a><a class="pred" href="metapred.html#meta_predicate/1">meta_predicate/1</a>,
<a id="idx:contextmodule1:1858"></a><a class="pred" href="ctxmodule.html#context_module/1">context_module/1</a>
and <a id="idx:moduletransparent1:1859"></a><a class="pred" href="ctxmodule.html#module_transparent/1">module_transparent/1</a>.
The <var>p</var> argument specifies the predicate, and should be the
result of a call to <a class="func" href="foreigninclude.html#PL_pred()">PL_pred()</a>
or <a class="func" href="foreigninclude.html#PL_predicate()">PL_predicate()</a>.
Note that it is allowed to store this handle as global data and reuse it
for future queries. The term reference <var>t0</var> is the first of a
vector of term references as returned by
<a class="func" href="foreigntypes.html#PL_new_term_refs()">PL_new_term_refs(n)</a>.
<p>The <var>flags</var> arguments provides some additional options
concerning debugging and exception handling. It is a bitwise <em>or</em>
of the following values:
<dl class="latex">
<dt><b><code>PL_Q_NORMAL</code></b></dt>
<dd class="defbody">
Normal operation. The debugger inherits its settings from the
environment. If an exception occurs that is not handled in Prolog, a
message is printed and the tracer is started to debug the error.<sup class="fn">153<span class="fn-text">Do
not pass the integer 0 for normal operation, as this is interpreted as <code>PL_Q_NODEBUG</code>
for backward compatibility reasons.</span></sup>
</dd>
<dt><b><code>PL_Q_NODEBUG</code></b></dt>
<dd class="defbody">
Switch off the debugger while executing the goal. This option is used by
many calls to hook-predicates to avoid tracing the hooks. An example is <a id="idx:print1:1860"></a><a class="pred" href="termrw.html#print/1">print/1</a>
calling <a id="idx:portray1:1861"></a><a class="pred" href="termrw.html#portray/1">portray/1</a>
from foreign code.
</dd>
<dt><b><code>PL_Q_CATCH_EXCEPTION</code></b></dt>
<dd class="defbody">
If an exception is raised while executing the goal, do not report it,
but make it available for <a class="func" href="foreigninclude.html#PL_exception()">PL_exception()</a>.
</dd>
<dt><b><code>PL_Q_PASS_EXCEPTION</code></b></dt>
<dd class="defbody">
As <code>PL_Q_CATCH_EXCEPTION</code>, but do not invalidate the
exception-term while calling <a class="func" href="foreigninclude.html#PL_close_query()">PL_close_query()</a>.
This option is experimental.
</dd>
</dl>
<p><a class="func" href="foreigninclude.html#PL_open_query()">PL_open_query()</a>
can return the query identifier `0' if there is not enough space on the
environment stack. This function succeeds, even if the referenced
predicate is not defined. In this case, running the query using <a class="func" href="foreigninclude.html#PL_next_solution()">PL_next_solution()</a>
will return an existence_error. See
<a class="func" href="foreigninclude.html#PL_exception()">PL_exception()</a>.
<p>The example below opens a query to the predicate <code>is_a/2</code>
to find the ancestor of `me'. The reference to the predicate is valid
for the duration of the process and may be cached by the client.
<pre class="code">
char *
ancestor(const char *me)
{ term_t a0 = PL_new_term_refs(2);
static predicate_t p;
if ( !p )
p = PL_predicate("is_a", 2, "database");
PL_put_atom_chars(a0, me);
PL_open_query(NULL, PL_Q_NORMAL, p, a0);
...
}
</pre>
</dd>
<dt class="pubdef"><a id="PL_next_solution()"><var>int</var> <strong>PL_next_solution</strong>(<var>qid_t
qid</var>)</a></dt>
<dd class="defbody">
Generate the first (next) solution for the given query. The return value
is <code>TRUE</code> if a solution was found, or <code>FALSE</code> to
indicate the query could not be proven. This function may be called
repeatedly until it fails to generate all solutions to the query.
</dd>
<dt class="pubdef"><a id="PL_cut_query()"><var>void</var> <strong>PL_cut_query</strong>(<var>qid_t
qid</var>)</a></dt>
<dd class="defbody">
Discards the query, but does not delete any of the data created by the
query. It just invalidates <var>qid</var>, allowing for a new call to
<a class="func" href="foreigninclude.html#PL_open_query()">PL_open_query()</a>
in this context.
</dd>
<dt class="pubdef"><a id="PL_close_query()"><var>void</var> <strong>PL_close_query</strong>(<var>qid_t
qid</var>)</a></dt>
<dd class="defbody">
As <a class="func" href="foreigninclude.html#PL_cut_query()">PL_cut_query()</a>,
but all data and bindings created by the query are destroyed.
</dd>
<dt class="pubdef"><a id="PL_call_predicate()"><var>int</var> <strong>PL_call_predicate</strong>(<var>module_t
m, int flags, predicate_t pred, term_t +t0</var>)</a></dt>
<dd class="defbody">
Shorthand for <a class="func" href="foreigninclude.html#PL_open_query()">PL_open_query()</a>, <a class="func" href="foreigninclude.html#PL_next_solution()">PL_next_solution()</a>, <a class="func" href="foreigninclude.html#PL_cut_query()">PL_cut_query()</a>,
generating a single solution. The arguments are the same as for
<a class="func" href="foreigninclude.html#PL_open_query()">PL_open_query()</a>,
the return value is the same as <a class="func" href="foreigninclude.html#PL_next_solution()">PL_next_solution()</a>.
</dd>
<dt class="pubdef"><a id="PL_call()"><var>int</var> <strong>PL_call</strong>(<var>term_t
t, module_t m</var>)</a></dt>
<dd class="defbody">
Call term <var>t</var> just like the Prolog predicate <a id="idx:once1:1862"></a><a class="pred" href="metacall.html#once/1">once/1</a>. <var>t</var>
is called in the module <var>m</var>, or in the context module if <var>m</var>
== NULL. Returns <code>TRUE</code> if the call succeeds, <code>FALSE</code>
otherwise.
<a class="fig" href="foreigninclude.html#fig:calling">Figure 8</a> shows
an example to obtain the number of defined atoms. All checks are omitted
to improve readability.
</dd>
</dl>
<p><h3 id="sec:foreign-discard-term-t"><a id="sec:10.4.10"><span class="sec-nr">10.4.10</span> <span class="sec-title">Discarding
Data</span></a></h3>
<a id="sec:foreign-discard-term-t"></a>
<p>The Prolog data created and term references needed to set up the call
and/or analyse the result can in most cases be discarded right after the
call. <a class="func" href="foreigninclude.html#PL_close_query()">PL_close_query()</a>
allows for destroying the data, while leaving the term references. The
calls below may be used to destroy term references and data. See <a class="fig" href="foreigninclude.html#fig:calling">figure
8</a> for an example.
<dl class="latex">
<dt class="pubdef"><a id="PL_open_foreign_frame()"><var>fid_t</var> <strong>PL_open_foreign_frame</strong>(<var></var>)</a></dt>
<dd class="defbody">
Create a foreign frame, holding a mark that allows the system to undo
bindings and destroy data created after it, as well as providing the
environment for creating term references. This function is called by the
kernel before calling a foreign predicate.
</dd>
<dt class="pubdef"><a id="PL_close_foreign_frame()"><var>void</var> <strong>PL_close_foreign_frame</strong>(<var>fid_t
id</var>)</a></dt>
<dd class="defbody">
Discard all term references created after the frame was opened. All
other Prolog data is retained. This function is called by the kernel
whenever a foreign function returns control back to Prolog.
</dd>
<dt class="pubdef"><a id="PL_discard_foreign_frame()"><var>void</var> <strong>PL_discard_foreign_frame</strong>(<var>fid_t
id</var>)</a></dt>
<dd class="defbody">
Same as <a class="func" href="foreigninclude.html#PL_close_foreign_frame()">PL_close_foreign_frame()</a>,
but also undo all bindings made since the open and destroy all Prolog
data.
</dd>
<dt class="pubdef"><a id="PL_rewind_foreign_frame()"><var>void</var> <strong>PL_rewind_foreign_frame</strong>(<var>fid_t
id</var>)</a></dt>
<dd class="defbody">
Undo all bindings and discard all term references created since the
frame was created, but do not pop the frame. That is, the same frame can
be rewound multiple times, and must eventually be closed or discarded.
</dd>
</dl>
<p>It is obligatory to call either of the two closing functions to
discard a foreign frame. Foreign frames may be nested.
<pre class="code">
int
count_atoms()
{ fid_t fid = PL_open_foreign_frame();
term_t goal = PL_new_term_ref();
term_t a1 = PL_new_term_ref();
term_t a2 = PL_new_term_ref();
functor_t s2 = PL_new_functor(PL_new_atom("statistics"), 2);
int atoms;
PL_put_atom_chars(a1, "atoms");
PL_cons_functor(goal, s2, a1, a2);
PL_call(goal, NULL); /* call it in current module */
PL_get_integer(a2, &atoms);
PL_discard_foreign_frame(fid);
return atoms;
}
</pre>
<div class="caption"><b>Figure 8 : </b>Calling Prolog</div>
<a id="fig:calling"></a>
<p><h3 id="sec:foreign-modules"><a id="sec:10.4.11"><span class="sec-nr">10.4.11</span> <span class="sec-title">Foreign
Code and Modules</span></a></h3>
<a id="sec:foreign-modules"></a>
<p>Modules are identified via a unique handle. The following functions
are available to query and manipulate modules.
<dl class="latex">
<dt class="pubdef"><a id="PL_context()"><var>module_t</var> <strong>PL_context</strong>(<var></var>)</a></dt>
<dd class="defbody">
Return the module identifier of the context module of the currently
active foreign predicate.</dd>
<dt class="pubdef"><a id="PL_strip_module()"><var>int</var> <strong>PL_strip_module</strong>(<var>term_t
+raw, module_t *m, term_t -plain</var>)</a></dt>
<dd class="defbody">
Utility function. If <var>raw</var> is a term, possibly holding the
module construct <<var>module</var>><code>:</code><<var>rest</var>>,
this function will make
<var>plain</var> a reference to <<var>rest</var>> and fill <var>module
*</var> with <<var>module</var>>. For further nested module
constructs the innermost module is returned via <var>module *</var>. If <var>raw</var>
is not a module construct, <var>raw</var> will simply be put in <var>plain</var>.
The value pointed to by <var>m</var> must be initialized before calling <a class="func" href="foreigninclude.html#PL_strip_module()">PL_strip_module()</a>,
either to the default module or to <code>NULL</code>. A <code>NULL</code>
value is replaced by the current context module if <var>raw</var>
carries no module. The following example shows how to obtain the plain
term and module if the default module is the user module:
<pre class="code">
{ module m = PL_new_module(PL_new_atom("user"));
term_t plain = PL_new_term_ref();
PL_strip_module(term, &m, plain);
...
}
</pre>
</dd>
<dt class="pubdef"><a id="PL_module_name()"><var>atom_t</var> <strong>PL_module_name</strong>(<var>module_t
module</var>)</a></dt>
<dd class="defbody">
Return the name of <var>module</var> as an atom.
</dd>
<dt class="pubdef"><a id="PL_new_module()"><var>module_t</var> <strong>PL_new_module</strong>(<var>atom_t
name</var>)</a></dt>
<dd class="defbody">
Find an existing module or create a new module with the name <var>name</var>.
</dd>
</dl>
<p><h3 id="sec:foreign-exceptions"><a id="sec:10.4.12"><span class="sec-nr">10.4.12</span> <span class="sec-title">Prolog
exceptions in foreign code</span></a></h3>
<a id="sec:foreign-exceptions"></a>
<p>This section discusses <a class="func" href="foreigninclude.html#PL_exception()">PL_exception()</a>, <a class="func" href="foreigninclude.html#PL_throw()">PL_throw()</a>
and
<a class="func" href="foreigninclude.html#PL_raise_exception()">PL_raise_exception()</a>,
the interface functions to detect and generate Prolog exceptions from C
code. <a class="func" href="foreigninclude.html#PL_throw()">PL_throw()</a>
and <a class="func" href="foreigninclude.html#PL_raise_exception()">PL_raise_exception()</a>
from the C interface raise an exception from foreign code. <a class="func" href="foreigninclude.html#PL_throw()">PL_throw()</a>
exploits the C function longjmp() to return immediately to the innermost
<a class="func" href="foreigninclude.html#PL_next_solution()">PL_next_solution()</a>. <a class="func" href="foreigninclude.html#PL_raise_exception()">PL_raise_exception()</a>
registers the exception term and returns <code>FALSE</code>. If a
foreign predicate returns <code>FALSE</code>, while an exception term is
registered, a Prolog exception will be raised by the virtual machine.
<p>Calling these functions outside the context of a function
implementing a foreign predicate results in undefined behaviour.
<p><a class="func" href="foreigninclude.html#PL_exception()">PL_exception()</a>
may be used after a call to <a class="func" href="foreigninclude.html#PL_next_solution()">PL_next_solution()</a>
fails, and returns a term reference to an exception term if an exception
was raised, and 0 otherwise.
<p>If a C function implementing a predicate calls Prolog and detects an
exception using <a class="func" href="foreigninclude.html#PL_exception()">PL_exception()</a>,
it can handle this exception or return with the exception. Some caution
is required though. It is
<strong>not</strong> allowed to call <a class="func" href="foreigninclude.html#PL_close_query()">PL_close_query()</a>
or
<a class="func" href="foreigninclude.html#PL_discard_foreign_frame()">PL_discard_foreign_frame()</a>
afterwards, as this will invalidate the exception term. Below is the
code that calls a Prolog-defined arithmetic function (see <a id="idx:arithmeticfunction1:1863"></a><span class="pred-ext">arithmetic_function/1</span>).
<p>If <a class="func" href="foreigninclude.html#PL_next_solution()">PL_next_solution()</a>
succeeds, the result is analysed and translated to a number, after which
the query is closed and all Prolog data created after <a class="func" href="foreigninclude.html#PL_open_foreign_frame()">PL_open_foreign_frame()</a>
is destroyed. On the other hand, if
<a class="func" href="foreigninclude.html#PL_next_solution()">PL_next_solution()</a>
fails and if an exception was raised, just pass it. Otherwise generate
an exception (<b>PL_error()</b> is an internal call for building the
standard error terms and calling <a class="func" href="foreigninclude.html#PL_raise_exception()">PL_raise_exception()</a>).
After this, the Prolog environment should be discarded using
<a class="func" href="foreigninclude.html#PL_cut_query()">PL_cut_query()</a>
and <a class="func" href="foreigninclude.html#PL_close_foreign_frame()">PL_close_foreign_frame()</a>
to avoid invalidating the exception term.
<pre class="code">
static int
prologFunction(ArithFunction f, term_t av, Number r)
{ int arity = f->proc->definition->functor->arity;
fid_t fid = PL_open_foreign_frame();
qid_t qid;
int rval;
qid = PL_open_query(NULL, PL_Q_NORMAL, f->proc, av);
if ( PL_next_solution(qid) )
{ rval = valueExpression(av+arity-1, r);
PL_close_query(qid);
PL_discard_foreign_frame(fid);
} else
{ term_t except;
if ( (except = PL_exception(qid)) )
{ rval = PL_throw(except); /* pass exception */
} else
{ char *name = stringAtom(f->proc->definition->functor->name);
/* generate exception */
rval = PL_error(name, arity-1, NULL, ERR_FAILED, f->proc);
}
PL_cut_query(qid); /* donot destroy data */
PL_close_foreign_frame(fid); /* same */
}
return rval;
}
</pre>
<dl class="latex">
<dt class="pubdef"><a id="PL_raise_exception()"><var>int</var> <strong>PL_raise_exception</strong>(<var>term_t
exception</var>)</a></dt>
<dd class="defbody">
Generate an exception (as <a id="idx:throw1:1864"></a><a class="pred" href="exception.html#throw/1">throw/1</a>)
and return <code>FALSE</code>. Below is an example returning an
exception from a foreign predicate:
<pre class="code">
foreign_t
pl_hello(term_t to)
{ char *s;
if ( PL_get_atom_chars(to, &s) )
{ Sprintf("Hello \"%s\"\n", s);
PL_succeed;
} else
{ term_t except = PL_new_term_ref();
PL_unify_term(except,
PL_FUNCTOR_CHARS, "type_error", 2,
PL_CHARS, "atom",
PL_TERM, to);
return PL_raise_exception(except);
}
}
</pre>
</dd>
<dt class="pubdef"><a id="PL_throw()"><var>int</var> <strong>PL_throw</strong>(<var>term_t
exception</var>)</a></dt>
<dd class="defbody">
Similar to <a class="func" href="foreigninclude.html#PL_raise_exception()">PL_raise_exception()</a>,
but returns using the C longjmp() function to the innermost <a class="func" href="foreigninclude.html#PL_next_solution()">PL_next_solution()</a>.</dd>
<dt class="pubdef"><a id="PL_exception()"><var>term_t</var> <strong>PL_exception</strong>(<var>qid_t
qid</var>)</a></dt>
<dd class="defbody">
If <a class="func" href="foreigninclude.html#PL_next_solution()">PL_next_solution()</a>
fails, this can be due to normal failure of the Prolog call, or because
an exception was raised using <a id="idx:throw1:1865"></a><a class="pred" href="exception.html#throw/1">throw/1</a>.
This function returns a handle to the exception term if an exception was
raised, or 0 if the Prolog goal simply failed. If there is an exception,
<a class="func" href="foreigninclude.html#PL_exception()">PL_exception()</a>
allocates a term-handle using <a class="func" href="foreigntypes.html#PL_new_term_ref()">PL_new_term_ref()</a>
that is used to return the exception term.
<p>Additionally, <code>\cfuncref{PL_exception}{0}</code> returns the
pending exception in the current query or 0 if no exception is pending.
This can be used to check the error status after a failing call to,
e.g., one of the unification functions.</dd>
<dt class="pubdef"><a id="PL_clear_exception()"><var>void</var> <strong>PL_clear_exception</strong>(<var>void</var>)</a></dt>
<dd class="defbody">
Tells Prolog that the encountered exception must be ignored. This
function must be called if control remains in C after a previous API
call fails with an exception.<sup class="fn">154<span class="fn-text">This
feature is non-portable. Other Prolog systems (e.g., YAP) have no
facilities to ignore raised exceptions, and the design of YAP's
exception handling does not support such a facility.</span></sup>
</dd>
</dl>
<p><h3 id="sec:csignal"><a id="sec:10.4.13"><span class="sec-nr">10.4.13</span> <span class="sec-title">Catching
Signals (Software Interrupts)</span></a></h3>
<a id="sec:csignal"></a>
<p>SWI-Prolog offers both a C and Prolog interface to deal with software
interrupts (signals). The Prolog mapping is defined in
<a class="sec" href="signal.html">section 4.11</a>. This subsection
deals with handling signals from C.
<p>If a signal is not used by Prolog and the handler does not call
Prolog in any way, the native signal interface routines may be used.
<p>Any handler that wishes to call one of the Prolog interface functions
should call <a class="func" href="foreigninclude.html#PL_signal()">PL_signal()</a>
for its installation.
<dl class="latex">
<dt class="pubdef"><a id="PL_signal()"><var>void (*)()</var> <strong>PL_signal</strong>(<var>sig,
func</var>)</a></dt>
<dd class="defbody">
This function is equivalent to the BSD-Unix signal() function,
regardless of the platform used. The signal handler is blocked while the
signal routine is active, and automatically reactivated after the
handler returns.
<p>After a signal handler is registered using this function, the native
signal interface redirects the signal to a generic signal handler inside
SWI-Prolog. This generic handler validates the environment, creates a
suitable environment for calling the interface functions described in
this chapter and finally calls the registered user-handler.
<p>By default, signals are handled asynchronously (i.e., at the time
they arrive). It is inherently dangerous to call extensive code
fragments, and especially exception related code from asynchronous
handlers. The interface allows for <em>synchronous</em> handling of
signals. In this case the native OS handler just schedules the signal
using <a class="func" href="foreigninclude.html#PL_raise()">PL_raise()</a>,
which is checked by <a class="func" href="foreigninclude.html#PL_handle_signals()">PL_handle_signals()</a>
at the call- and redo-port. This behaviour is realised by <em>or</em>-ing <var>sig</var>
with the constant
<code>PL_SIGSYNC</code>.<sup class="fn">155<span class="fn-text">A
better default would be to use synchronous handling, but this interface
preserves backward compatibility.</span></sup>
<p>Signal handling routines may raise exceptions using
<a class="func" href="foreigninclude.html#PL_raise_exception()">PL_raise_exception()</a>.
The use of <a class="func" href="foreigninclude.html#PL_throw()">PL_throw()</a>
is not safe. If a synchronous handler raises an exception, the exception
is delayed to the next call to <a class="func" href="foreigninclude.html#PL_handle_signals()">PL_handle_signals()</a>;</dd>
<dt class="pubdef"><a id="PL_raise()"><var>int</var> <strong>PL_raise</strong>(<var>int
sig</var>)</a></dt>
<dd class="defbody">
Register <var>sig</var> for <em>synchronous</em> handling by Prolog.
Synchronous signals are handled at the call-port or if foreign code
calls <a class="func" href="foreigninclude.html#PL_handle_signals()">PL_handle_signals()</a>.
See also <a id="idx:threadsignal2:1866"></a><a class="pred" href="threadcom.html#thread_signal/2">thread_signal/2</a>.</dd>
<dt class="pubdef"><a id="PL_handle_signals()"><var>int</var> <strong>PL_handle_signals</strong>(<var>void</var>)</a></dt>
<dd class="defbody">
Handle any signals pending from <a class="func" href="foreigninclude.html#PL_raise()">PL_raise()</a>. <a class="func" href="foreigninclude.html#PL_handle_signals()">PL_handle_signals()</a>
is called at each pass through the call- and redo-port at a safe point.
Exceptions raised by the handler using <a class="func" href="foreigninclude.html#PL_raise_exception()">PL_raise_exception()</a>
are properly passed to the environment.
<p>The user may call this function inside long-running foreign functions
to handle scheduled interrupts. This routine returns the number of
signals handled. If a handler raises an exception, the return value is
-1 and the calling routine should return with <code>FALSE</code> as soon
as possible.</dd>
<dt class="pubdef"><a id="PL_get_signum_ex()"><var>int</var> <strong>PL_get_signum_ex</strong>(<var>term_t
t, int *sig</var>)</a></dt>
<dd class="defbody">
Extract a signal specification from a Prolog term and store as an
integer signal number in <var>sig</var>. The specification is an
integer, a lowercase signal name without <code>SIG</code> or the full
signal name. These refer to the same: <code>9</code>, <code>kill</code>
and <code>SIGKILL</code>. Leaves a typed, domain or instantiation error
if the conversion fails.
</dd>
</dl>
<p><h3 id="sec:foreign-misc"><a id="sec:10.4.14"><span class="sec-nr">10.4.14</span> <span class="sec-title">Miscellaneous</span></a></h3>
<a id="sec:foreign-misc"></a>
<p><h4 id="sec:foreign-compare"><a id="sec:10.4.14.1"><span class="sec-nr">10.4.14.1</span> <span class="sec-title">Term
Comparison</span></a></h4>
<a id="sec:foreign-compare"></a>
<dl class="latex">
<dt class="pubdef"><a id="PL_compare()"><var>int</var> <strong>PL_compare</strong>(<var>term_t
t1, term_t t2</var>)</a></dt>
<dd class="defbody">
Compares two terms using the standard order of terms and returns -1, 0
or 1. See also <a id="idx:compare3:1867"></a><a class="pred" href="compare.html#compare/3">compare/3</a>.
</dd>
<dt class="pubdef"><a id="PL_same_compound()"><var>int</var> <strong>PL_same_compound</strong>(<var>term_t
t1, term_t t2</var>)</a></dt>
<dd class="defbody">
Yields <code>TRUE</code> if <var>t1</var> and <var>t2</var> refer to
physically the same compound term and <code>FALSE</code> otherwise.
</dd>
</dl>
<p><h4 id="sec:foreign-recorded"><a id="sec:10.4.14.2"><span class="sec-nr">10.4.14.2</span> <span class="sec-title">Recorded
database</span></a></h4>
<a id="sec:foreign-recorded"></a>
<p>In some applications it is useful to store and retrieve Prolog terms
from C code. For example, the XPCE graphical environment does this for
storing arbitrary Prolog data as slot-data of XPCE objects.
<p>Please note that the returned handles have no meaning at the Prolog
level and the recorded terms are not visible from Prolog. The functions
<a class="func" href="foreigninclude.html#PL_recorded()">PL_recorded()</a>
and <a class="func" href="foreigninclude.html#PL_erase()">PL_erase()</a>
are the only functions that can operate on the stored term.
<p>Two groups of functions are provided. The first group (<a class="func" href="foreigninclude.html#PL_record()">PL_record()</a>
and friends) store Prolog terms on the Prolog heap for retrieval during
the same session. These functions are also used by <a id="idx:recorda3:1868"></a><a class="pred" href="db.html#recorda/3">recorda/3</a>
and friends. The recorded database may be used to communicate Prolog
terms between threads.
<dl class="latex">
<dt class="pubdef"><a id="PL_record()"><var>record_t</var> <strong>PL_record</strong>(<var>term_t
+t</var>)</a></dt>
<dd class="defbody">
Record the term <var>t</var> into the Prolog database as <a id="idx:recorda3:1869"></a><a class="pred" href="db.html#recorda/3">recorda/3</a>
and return an opaque handle to the term. The returned handle remains
valid until <a class="func" href="foreigninclude.html#PL_erase()">PL_erase()</a>
is called on it. <a class="func" href="foreigninclude.html#PL_recorded()">PL_recorded()</a>
is used to copy recorded terms back to the Prolog stack.</dd>
<dt class="pubdef"><a id="PL_recorded()"><var>int</var> <strong>PL_recorded</strong>(<var>record_t
record, term_t -t</var>)</a></dt>
<dd class="defbody">
Copy a recorded term back to the Prolog stack. The same record may be
used to copy multiple instances at any time to the Prolog stack. Returns <code>TRUE</code>
on success, and <code>FALSE</code> if there is not enough space on the
stack to accommodate the term. See also <a class="func" href="foreigninclude.html#PL_record()">PL_record()</a>
and <a class="func" href="foreigninclude.html#PL_erase()">PL_erase()</a>.</dd>
<dt class="pubdef"><a id="PL_erase()"><var>void</var> <strong>PL_erase</strong>(<var>record_t
record</var>)</a></dt>
<dd class="defbody">
Remove the recorded term from the Prolog database, reclaiming all
associated memory resources.
</dd>
</dl>
<p>The second group (headed by <a class="func" href="foreigninclude.html#PL_record_external()">PL_record_external()</a>)
provides the same functionality, but the returned data has properties
that enable storing the data on an external device. It has been designed
to make it possible to store Prolog terms fast and compact in an
external database. Here are the main features:
<p>
<ul class="latex">
<li><i>Independent of session</i><br>
Records can be communicated to another Prolog session and made visible
using <a class="func" href="foreigninclude.html#PL_recorded_external()">PL_recorded_external()</a>.
<li><i>Binary</i><br>
The representation is binary for maximum performance. The returned data
may contain zero bytes.
<li><i>Byte-order independent</i><br>
The representation can be transferred between machines with different
byte order.
<li><i>No alignment restrictions</i><br>
There are no memory alignment restrictions and copies of the record can
thus be moved freely. For example, it is possible to use this
representation to exchange terms using shared memory between different
Prolog processes.
<li><i>Compact</i><br>
It is assumed that a smaller memory footprint will eventually outperform
slightly faster representations.
<li><i>Stable</i><br>
The format is designed for future enhancements without breaking
compatibility with older records.
</ul>
<dl class="latex">
<dt class="pubdef"><a id="PL_record_external()"><var>char *</var> <strong>PL_record_external</strong>(<var>term_t
+t, size_t *len</var>)</a></dt>
<dd class="defbody">
Record the term <var>t</var> into the Prolog database as <a id="idx:recorda3:1870"></a><a class="pred" href="db.html#recorda/3">recorda/3</a>
and return an opaque handle to the term. The returned handle remains
valid until <a class="func" href="foreigninclude.html#PL_erase_external()">PL_erase_external()</a>
is called on it.
<p>It is allowed to copy the data and use <a class="func" href="foreigninclude.html#PL_recorded_external()">PL_recorded_external()</a>
on the copy. The user is responsible for the memory management of the
copy. After copying, the original may be discarded using
<a class="func" href="foreigninclude.html#PL_erase_external()">PL_erase_external()</a>.
<p><a class="func" href="foreigninclude.html#PL_recorded_external()">PL_recorded_external()</a>
is used to copy such recorded terms back to the Prolog stack.
</dd>
<dt class="pubdef"><a id="PL_recorded_external()"><var>int</var> <strong>PL_recorded_external</strong>(<var>const
char *record, term_t -t</var>)</a></dt>
<dd class="defbody">
Copy a recorded term back to the Prolog stack. The same record may be
used to copy multiple instances at any time to the Prolog stack. See
also <a class="func" href="foreigninclude.html#PL_record_external()">PL_record_external()</a>
and <a class="func" href="foreigninclude.html#PL_erase_external()">PL_erase_external()</a>.
</dd>
<dt class="pubdef"><a id="PL_erase_external()"><var>int</var> <strong>PL_erase_external</strong>(<var>char
*record</var>)</a></dt>
<dd class="defbody">
Remove the recorded term from the Prolog database, reclaiming all
associated memory resources.
</dd>
</dl>
<p><h4 id="sec:cfilenames"><a id="sec:10.4.14.3"><span class="sec-nr">10.4.14.3</span> <span class="sec-title">Getting
file names</span></a></h4>
<a id="sec:cfilenames"></a>
<p>The function <a class="func" href="foreigninclude.html#PL_get_file_name()">PL_get_file_name()</a>
provides access to Prolog filenames and its file-search mechanism
described with <a id="idx:absolutefilename3:1871"></a><a class="pred" href="files.html#absolute_file_name/3">absolute_file_name/3</a>.
Its existence is motivated to realise a uniform interface to deal with
file properties, search, naming conventions, etc., from foreign code.
<dl class="latex">
<dt class="pubdef"><a id="PL_get_file_name()"><var>int</var> <strong>PL_get_file_name</strong>(<var>term_t
spec, char **name, int flags</var>)</a></dt>
<dd class="defbody">
Translate a Prolog term into a file name. The name is stored in the
static buffer ring described with th <a class="func" href="foreigninclude.html#PL_get_chars()">PL_get_chars()</a>
option
<code>BUF_RING</code>. Conversion from the internal UNICODE encoding is
done using standard C library functions. <var>flags</var> is a bit-mask
controlling the conversion process. Options are:
<dl class="latex">
<dt><b><code>PL_FILE_ABSOLUTE</code></b></dt>
<dd class="defbody">
Return an absolute path to the requested file.
</dd>
<dt><b><code>PL_FILE_OSPATH</code></b></dt>
<dd class="defbody">
Return the name using the hosting OS conventions. On MS-Windows,
<code><code>\</code></code> is used to separate directories rather than
the canonical
<code><code>/</code></code>.
</dd>
<dt><b><code>PL_FILE_SEARCH</code></b></dt>
<dd class="defbody">
Invoke <a id="idx:absolutefilename3:1872"></a><a class="pred" href="files.html#absolute_file_name/3">absolute_file_name/3</a>.
This implies rules from <a id="idx:filesearchpath2:1873"></a><a class="pred" href="consulting.html#file_search_path/2">file_search_path/2</a>
are used.
</dd>
<dt><b><code>PL_FILE_EXIST</code></b></dt>
<dd class="defbody">
Demand the path to refer to an existing entity.
</dd>
<dt><b><code>PL_FILE_READ</code></b></dt>
<dd class="defbody">
Demand read-access on the result.
</dd>
<dt><b><code>PL_FILE_WRITE</code></b></dt>
<dd class="defbody">
Demand write-access on the result.
</dd>
<dt><b><code>PL_FILE_EXECUTE</code></b></dt>
<dd class="defbody">
Demand execute-access on the result.
</dd>
<dt><b><code>PL_FILE_NOERRORS</code></b></dt>
<dd class="defbody">
Do not raise any exceptions.
</dd>
</dl>
</dd>
<dt class="pubdef"><a id="PL_get_file_nameW()"><var>int</var> <strong>PL_get_file_nameW</strong>(<var>term_t
spec, wchar_t **name, int flags</var>)</a></dt>
<dd class="defbody">
Same as <a class="func" href="foreigninclude.html#PL_get_file_name()">PL_get_file_name()</a>,
but returns the filename as a wide-character string. This is intended
for Windows to access the Unicode version of the Win32 API. Note that
the flag <code>PL_FILE_OSPATH</code> must be provided to fetch a
filename in OS native (e.g., <code>C:\x\y</code>) notation.
</dd>
</dl>
<p><h4 id="sec:cprologflags"><a id="sec:10.4.14.4"><span class="sec-nr">10.4.14.4</span> <span class="sec-title">Dealing
with Prolog flags from C</span></a></h4>
<a id="sec:cprologflags"></a>
<p>Foreign code can set or create Prolog flags using <a class="func" href="foreigninclude.html#PL_set_prolog_flag()">PL_set_prolog_flag()</a>.
See <a id="idx:setprologflag2:1874"></a><a class="pred" href="flags.html#set_prolog_flag/2">set_prolog_flag/2</a>
and <a id="idx:createprologflag3:1875"></a><a class="pred" href="flags.html#create_prolog_flag/3">create_prolog_flag/3</a>.<sup class="fn">156<span class="fn-text">The
current C API does not provide for a dedicated mechanism for fetching
the value of Prolog flags. Relatively slow access is provided by calling <a class="func" href="foreigninclude.html#PL_call_predicate()">PL_call_predicate()</a>
using <a id="idx:currentprologflag2:1876"></a><a class="pred" href="flags.html#current_prolog_flag/2">current_prolog_flag/2</a>.</span></sup>
<dl class="latex">
<dt class="pubdef"><a id="PL_set_prolog_flag()"><var>int</var> <strong>PL_set_prolog_flag</strong>(<var>const
char *name, int type, ...</var>)</a></dt>
<dd class="defbody">
Set/create a Prolog flag from C. <var>name</var> is the name of the
affected flag. <var>type</var> is one of the values below, which also
dictates the type of the final argument. The function returns
<code>TRUE</code> on success and <code>FALSE</code> on failure. This
function can be called <em>before</em> <a class="func" href="foreigninclude.html#PL_initialise()">PL_initialise()</a>,
making the flag available to the Prolog startup code.
<dl class="latex">
<dt><b><code>PL_BOOL</code></b></dt>
<dd class="defbody">
Create a boolean (<code>true</code> or <code>false</code>) flag. The
argument must be an <code>int</code>.
</dd>
<dt><b><code>PL_ATOM</code></b></dt>
<dd class="defbody">
Create a flag with an atom as value. The argument must be of type
<code>const char *</code>.
</dd>
<dt><b><code>PL_INTEGER</code></b></dt>
<dd class="defbody">
Create a flag with an integer as value. The argument must be of type
<code>intptr_t *</code>.
</dd>
</dl>
</dd>
</dl>
<p><h3 id="sec:foreign-print-warning"><a id="sec:10.4.15"><span class="sec-nr">10.4.15</span> <span class="sec-title">Errors
and warnings</span></a></h3>
<a id="sec:foreign-print-warning"></a>
<p><a class="func" href="foreigninclude.html#PL_warning()">PL_warning()</a>
prints a standard Prolog warning message to the standard error (<code>user_error</code>)
stream. Please note that new code should consider using <a class="func" href="foreigninclude.html#PL_raise_exception()">PL_raise_exception()</a>
to raise a Prolog exception. See also <a class="sec" href="exception.html">section
4.10</a>.
<dl class="latex">
<dt class="pubdef"><a id="PL_warning()"><var>int</var> <strong>PL_warning</strong>(<var>format,
a1, ...</var>)</a></dt>
<dd class="defbody">
Print an error message starting with `<code>[WARNING: </code>', followed
by the output from <var>format</var>, followed by a `<code>]</code>' and
a newline. Then start the tracer. <var>format</var> and the arguments
are the same as for <strong>printf</strong>(2). Always returns <code>FALSE</code>.
</dd>
</dl>
<p><h3 id="sec:foreign-control-prolog"><a id="sec:10.4.16"><span class="sec-nr">10.4.16</span> <span class="sec-title">Environment
Control from Foreign Code</span></a></h3>
<a id="sec:foreign-control-prolog"></a>
<dl class="latex">
<dt class="pubdef"><a id="PL_action()"><var>int</var> <strong>PL_action</strong>(<var>int,
...</var>)</a></dt>
<dd class="defbody">
Perform some action on the Prolog system. <var>int</var> describes the
action. Remaining arguments depend on the requested action. The actions
are listed below:
<dl class="latex">
<dt><strong>PL_ACTION_TRACE</strong></dt>
<dd class="defbody">
Start Prolog tracer (<a id="idx:trace0:1877"></a><a class="pred" href="debugger.html#trace/0">trace/0</a>).
Requires no arguments.</dd>
<dt><strong>PL_ACTION_DEBUG</strong></dt>
<dd class="defbody">
Switch on Prolog debug mode (<a id="idx:debug0:1878"></a><a class="pred" href="debugger.html#debug/0">debug/0</a>).
Requires no arguments.</dd>
<dt><strong>PL_ACTION_BACKTRACE</strong></dt>
<dd class="defbody">
Print backtrace on current output stream. The argument (an <code>int</code>)
is the number of frames printed.</dd>
<dt><strong>PL_ACTION_HALT</strong></dt>
<dd class="defbody">
Halt Prolog execution. This action should be called rather than Unix
exit() to give Prolog the opportunity to clean up. This call does not
return. The argument (an <code>int</code>) is the exit code. See <a id="idx:halt1:1879"></a><a class="pred" href="toplevel.html#halt/1">halt/1</a>.</dd>
<dt><strong>PL_ACTION_ABORT</strong></dt>
<dd class="defbody">
Generate a Prolog abort (<a id="idx:abort0:1880"></a><a class="pred" href="toplevel.html#abort/0">abort/0</a>).
This call does not return. Requires no arguments.</dd>
<dt><strong>PL_ACTION_BREAK</strong></dt>
<dd class="defbody">
Create a standard Prolog break environment (<a id="idx:break0:1881"></a><a class="pred" href="toplevel.html#break/0">break/0</a>).
Returns after the user types the end-of-file character. Requires no
arguments.</dd>
<dt><strong>PL_ACTION_GUIAPP</strong></dt>
<dd class="defbody">
Windows: Used to indicate to the kernel that the application is a GUI
application if the argument is not 0, and a console application if the
argument is 0. If a fatal error occurs, the system uses a windows
messagebox to report this on a GUI application, and otherwise simply
prints the error and exits.</dd>
<dt><strong>PL_ACTION_TRADITIONAL</strong></dt>
<dd class="defbody">
Same effect as using <strong>--traditional</strong>. Must be called
<em>before</em> <a class="func" href="foreigninclude.html#PL_initialise()">PL_initialise()</a>.</dd>
<dt><strong>PL_ACTION_WRITE</strong></dt>
<dd class="defbody">
Write the argument, a <code>char *</code> to the current output stream.</dd>
<dt><strong>PL_ACTION_FLUSH</strong></dt>
<dd class="defbody">
Flush the current output stream. Requires no arguments.</dd>
<dt><strong>PL_ACTION_ATTACH_CONSOLE</strong></dt>
<dd class="defbody">
Attach a console to a thread if it does not have one. See
<a id="idx:attachconsole0:1882"></a><a class="pred" href="thutil.html#attach_console/0">attach_console/0</a>.</dd>
<dt><strong>PL_GMP_SET_ALLOC_FUNCTIONS</strong></dt>
<dd class="defbody">
Takes an integer argument. If <code>TRUE</code>, the GMP allocations are
immediately bound to the Prolog functions. If <code>FALSE</code>,
SWI-Prolog will never rebind the GMP allocation functions. See
mp_set_memory_functions() in the GMP documentation. The action returns
<code>FALSE</code> if there is no GMP support or GMP is already
initialised.
</dd>
</dl>
</dd>
<dt class="pubdef"><a id="PL_backtrace()"><var>int</var> <strong>PL_backtrace</strong>(<var>int
depth, int flags</var>)</a></dt>
<dd class="defbody">
Print a Prolog backtrace to the standard error stream. The <var>depth</var>
argument specifies the maximum number of frames to print. The
<var>flags</var> argument is a bitwise or of the constants <code>PL_BT_SAFE</code>
(0x1) and <code>PL_BT_USER</code> (0x2). <code>PL_BT_SAFE</code> causes
frames not to be printed as normal Prolog goals, but using the
predicate, program counter and clause-number. For example, the dump
below indicates the frame is executing the 2nd clause of
<code>$autoload:load_library_index_p/0</code> at program pointer 25.
This can be interpreted by dumping the virtual machine code using <a id="idx:vmlist1:1883"></a><span class="pred-ext">vm_list/1</span>.
<pre class="code">
[34] $autoload:load_library_index_p/0 [PC=19 in clause 2]
</pre>
<p>If the constant <code>PL_BT_USER</code> is specified, `no-debug'
frames are ignored. This predicate may be used from the C-debugger
(e.g., gdb) to get the Prolog stack at a crash location. Here is an
example dumping the top 20 frames of the Prolog stack.
<pre class="code">
(gdb) call PL_backtrace(20,0)
</pre>
<p></dd>
</dl>
<p><h3 id="sec:foreign-query"><a id="sec:10.4.17"><span class="sec-nr">10.4.17</span> <span class="sec-title">Querying
Prolog</span></a></h3>
<a id="sec:foreign-query"></a>
<dl class="latex">
<dt class="pubdef"><a id="PL_query()"><var>long</var> <strong>PL_query</strong>(<var>int</var>)</a></dt>
<dd class="defbody">
Obtain status information on the Prolog system. The actual argument type
depends on the information required. <var>int</var> describes what
information is wanted.<sup class="fn">157<span class="fn-text">Returning
pointers and integers as a long is bad style. The signature of this
function should be changed.</span></sup> The options are given in <a class="tab" href="foreigninclude.html#tab:query">table
9</a>.
<blockquote><table class="latex frame-box">
<tr><td><code>PL_QUERY_ARGC</code> </td><td>Return an integer holding
the number of arguments given to Prolog from Unix. </td></tr>
<tr><td><code>PL_QUERY_ARGV</code> </td><td>Return a <code>char **</code>
holding the argument vector given to Prolog from Unix. </td></tr>
<tr><td><code>PL_QUERY_SYMBOLFILE</code> </td><td>Return a <code>char *</code>
holding the current symbol file of the running process. </td></tr>
<tr><td><code>PL_MAX_INTEGER</code> </td><td>Return a long, representing
the maximal integer value represented by a Prolog integer. </td></tr>
<tr><td><code>PL_MIN_INTEGER</code> </td><td>Return a long, representing
the minimal integer value. </td></tr>
<tr><td><code>PL_QUERY_VERSION</code> </td><td>Return a long,
representing the version as
<var>10,000 × M + 100 × m + p</var>, where
<var>M</var> is the major, <var>m</var> the minor version number and <var>p</var>
the patch level. For example,
<code>20717</code> means <code>2.7.17</code>. </td></tr>
<tr><td><code>PL_QUERY_ENCODING</code> </td><td>Return the default
stream encoding of Prolog (of type <code>IOENC</code>). </td></tr>
<tr><td><code>PL_QUERY_USER_CPU</code> </td><td>Get amount of user CPU
time of the process in milliseconds. </td></tr>
</table>
</blockquote>
<div class="caption"><b>Table 9 : </b><a class="func" href="foreigninclude.html#PL_query()">PL_query()</a>
options</div>
<a id="tab:query"></a>
</dd>
</dl>
<p><h3 id="sec:foreign-register-predicate"><a id="sec:10.4.18"><span class="sec-nr">10.4.18</span> <span class="sec-title">Registering
Foreign Predicates</span></a></h3>
<a id="sec:foreign-register-predicate"></a>
<dl class="latex">
<dt class="pubdef"><a id="PL_register_foreign_in_module()"><var>int</var> <strong>PL_register_foreign_in_module</strong>(<var>char
*mod, char *name, int arity, foreign_t (*f)(), int flags, ...</var>)</a></dt>
<dd class="defbody">
Register the C function <var>f</var> to implement a Prolog predicate.
After this call returns successfully a predicate with name <var>name</var>
(a
<code>char *</code>) and arity <var>arity</var> (a C <code>int</code>)
is created in module <var>mod</var>. If <var>mod</var> is <code>NULL</code>,
the predicate is created in the module of the calling context, or if no
context is present in the module <code>user</code>.
<p>When called in Prolog, Prolog will call <var>function</var>. <var>flags</var>
form a bitwise <em>or</em>'ed list of options for the installation.
These are:
<p><table class="latex frame-box">
<tr><td><code>PL_FA_META</code> </td><td>Provide meta-predicate info
(see below) </td></tr>
<tr><td><code>PL_FA_TRANSPARENT</code> </td><td>Predicate is module
transparent (deprecated) </td></tr>
<tr><td><code>PL_FA_NONDETERMINISTIC</code> </td><td>Predicate is
non-deterministic. See also <a class="func" href="foreigninclude.html#PL_retry()">PL_retry()</a>. </td></tr>
<tr><td><code>PL_FA_NOTRACE</code> </td><td>Predicate cannot be seen in
the tracer </td></tr>
<tr><td><code>PL_FA_VARARGS</code> </td><td>Use alternative calling
convention. </td></tr>
</table>
<p>If <code>PL_FA_META</code> is provided, <a class="func" href="foreigninclude.html#PL_register_foreign_in_module()">PL_register_foreign_in_module()</a>
takes one extra argument. This argument is of type <code>const char*</code>.
This string must be exactly as long as the number of arguments of the
predicate and filled with characters from the set <code>0-9:^-+?</code>.
See
<a id="idx:metapredicate1:1884"></a><a class="pred" href="metapred.html#meta_predicate/1">meta_predicate/1</a>
for details. <code>PL_FA_TRANSPARENT</code> is implied if at least one
meta-argument is provided (<code>0-9:^</code>). Note that meta-arguments
are <em>not always</em> passed as <<var>module</var>>:<<var>term</var>>.
Always use <a class="func" href="foreigninclude.html#PL_strip_module()">PL_strip_module()</a>
to extract the module and plain term from a meta-argument.<sup class="fn">158<span class="fn-text">It
is encouraged to pass an additional <code>NULL</code> pointer for
non-meta-predicates.</span></sup>
<p>Predicates may be registered either before or after <a class="func" href="foreigninclude.html#PL_initialise()">PL_initialise()</a>.
When registered before initialisation the registration is recorded and
executed after installing the system predicates and before loading the
saved state.
<p>Default calling (i.e. without <code>PL_FA_VARARGS</code>) <var>function</var>
is passed the same number of <code>term_t</code> arguments as the arity
of the predicate and, if the predicate is non-deterministic, an extra
argument of type
<code>control_t</code> (see <a class="sec" href="foreigninclude.html">section
10.4.1.1</a>). If <code>PL_FA_VARARGS</code> is provided, <var>function</var>
is called with three arguments. The first argument is a <code>term_t</code>
handle to the first argument. Further arguments can be reached by adding
the offset (see also
<a class="func" href="foreigntypes.html#PL_new_term_refs()">PL_new_term_refs()</a>).
The second argument is the arity, which defines the number of valid term
references in the argument vector. The last argument is used for
non-deterministic calls. It is currently undocumented and should be
defined of type <code>void*</code>. Here is an example:
<pre class="code">
static foreign_t
atom_checksum(term_t a0, int arity, void* context)
{ char *s;
if ( PL_get_atom_chars(a0, &s) )
{ int sum;
for(sum=0; *s; s++)
sum += *s&0xff;
return PL_unify_integer(a0+1, sum&0xff);
}
return FALSE;
}
install_t
install()
{ PL_register_foreign("atom_checksum", 2,
atom_checksum, PL_FA_VARARGS);
}
</pre>
</dd>
<dt class="pubdef"><a id="PL_register_foreign()"><var>int</var> <strong>PL_register_foreign</strong>(<var>const
char *name, int arity, foreign_t (*function)(), int flags, ...</var>)</a></dt>
<dd class="defbody">
Same as <a class="func" href="foreigninclude.html#PL_register_foreign_in_module()">PL_register_foreign_in_module()</a>,
passing <code>NULL</code> for the
<var>module</var>.</dd>
<dt class="pubdef"><a id="PL_register_extensions_in_module()"><var>void</var> <strong>PL_register_extensions_in_module</strong>(<var>const
char *module, PL_extension *e</var>)</a></dt>
<dd class="defbody">
Register a series of predicates from an array of definitions of the type
<code>PL_extension</code> in the given <var>module</var>. If <var>module</var>
is
<code>NULL</code>, the predicate is created in the module of the calling
context, or if no context is present in the module <code>user</code>.
The <code>PL_extension</code> type is defined as
<pre class="code">
typedef struct PL_extension
{ char *predicate_name; /* Name of the predicate */
short arity; /* Arity of the predicate */
pl_function_t function; /* Implementing functions */
short flags; /* Or of PL_FA_... */
} PL_extension;
</pre>
<p>For details, see <a class="func" href="foreigninclude.html#PL_register_foreign_in_module()">PL_register_foreign_in_module()</a>.
Here is an example of its usage:
<pre class="code">
static PL_extension predicates[] = {
{ "foo", 1, pl_foo, 0 },
{ "bar", 2, pl_bar, PL_FA_NONDETERMINISTIC },
{ NULL, 0, NULL, 0 }
};
main(int argc, char **argv)
{ PL_register_extensions_in_module("user", predicates);
if ( !PL_initialise(argc, argv) )
PL_halt(1);
...
}
</pre>
</dd>
<dt class="pubdef"><a id="PL_register_extensions()"><var>void</var> <strong>PL_register_extensions</strong>(<var>
PL_extension *e</var>)</a></dt>
<dd class="defbody">
Same as <a class="func" href="foreigninclude.html#PL_register_extensions_in_module()">PL_register_extensions_in_module()</a>
using <code>NULL</code> for the <var>module</var> argument.
</dd>
</dl>
<p><h3 id="sec:foreign-hooks"><a id="sec:10.4.19"><span class="sec-nr">10.4.19</span> <span class="sec-title">Foreign
Code Hooks</span></a></h3>
<a id="sec:foreign-hooks"></a>
<p>For various specific applications some hooks are provided.
<dl class="latex">
<dt class="pubdef"><a id="PL_dispatch_hook()"><var>PL_dispatch_hook_t</var> <strong>PL_dispatch_hook</strong>(<var>PL_dispatch_hook_t</var>)</a></dt>
<dd class="defbody">
If this hook is not NULL, this function is called when reading from the
terminal. It is supposed to dispatch events when SWI-Prolog is connected
to a window environment. It can return two values:
<code>PL_DISPATCH_INPUT</code> indicates Prolog input is available on
file descriptor 0 or <code>PL_DISPATCH_TIMEOUT</code> to indicate a
timeout. The old hook is returned. The type <code>PL_dispatch_hook_t</code>
is defined as:
<pre class="code">
typedef int (*PL_dispatch_hook_t)(void);
</pre>
</dd>
<dt class="pubdef"><a id="PL_abort_hook()"><var>void</var> <strong>PL_abort_hook</strong>(<var>PL_abort_hook_t</var>)</a></dt>
<dd class="defbody">
Install a hook when <a id="idx:abort0:1885"></a><a class="pred" href="toplevel.html#abort/0">abort/0</a>
is executed. SWI-Prolog <a id="idx:abort0:1886"></a><a class="pred" href="toplevel.html#abort/0">abort/0</a>
is implemented using C setjmp()/longjmp() construct. The hooks are
executed in the reverse order of their registration after the longjmp()
took place and before the Prolog top level is reinvoked. The type
<code>PL_abort_hook_t</code> is defined as:
<pre class="code">
typedef void (*PL_abort_hook_t)(void);
</pre>
</dd>
<dt class="pubdef"><a id="PL_abort_unhook()"><var>int</var> <strong>PL_abort_unhook</strong>(<var>PL_abort_hook_t</var>)</a></dt>
<dd class="defbody">
Remove a hook installed with <a class="func" href="foreigninclude.html#PL_abort_hook()">PL_abort_hook()</a>.
Returns <code>FALSE</code> if no such hook is found, <code>TRUE</code>
otherwise.</dd>
<dt class="pubdef"><a id="PL_on_halt()"><var>void</var> <strong>PL_on_halt</strong>(<var>int
(*f)(int, void *), void *closure</var>)</a></dt>
<dd class="defbody">
Register the function <var>f</var> to be called if SWI-Prolog is halted.
The function is called with two arguments: the exit code of the process
(0 if this cannot be determined) and the <var>closure</var> argument
passed to the <a class="func" href="foreigninclude.html#PL_on_halt()">PL_on_halt()</a>
call. Handlers <em>must</em> return 0. Other return values are reserved
for future use. See also <a id="idx:athalt1:1887"></a><a class="pred" href="consulting.html#at_halt/1">at_halt/1</a>.<sup class="fn">bug<span class="fn-text">Although
both <a class="func" href="foreigninclude.html#PL_on_halt()">PL_on_halt()</a>
and <a id="idx:athalt1:1888"></a><a class="pred" href="consulting.html#at_halt/1">at_halt/1</a>
are called in FIFO order, <em>all</em> <a id="idx:athalt1:1889"></a><a class="pred" href="consulting.html#at_halt/1">at_halt/1</a>
handlers are called before <em>all</em> <a class="func" href="foreigninclude.html#PL_on_halt()">PL_on_halt()</a>
handlers.</span></sup> These handlers are called <em>before</em> system
cleanup and can therefore access all normal Prolog resources. See also <a class="func" href="foreigninclude.html#PL_exit_hook()">PL_exit_hook()</a>.</dd>
<dt class="pubdef"><a id="PL_exit_hook()"><var>void</var> <strong>PL_exit_hook</strong>(<var>int
(*f)(int, void *), void *closure</var>)</a></dt>
<dd class="defbody">
Similar to <a class="func" href="foreigninclude.html#PL_on_halt()">PL_on_halt()</a>,
but the hooks are executed by <a class="func" href="foreigninclude.html#PL_halt()">PL_halt()</a>
instead of <a class="func" href="foreigninclude.html#PL_cleanup()">PL_cleanup()</a>
just before calling exit().</dd>
<dt class="pubdef"><a id="PL_agc_hook()"><var>PL_agc_hook_t</var> <strong>PL_agc_hook</strong>(<var>PL_agc_hook_t
new</var>)</a></dt>
<dd class="defbody">
Register a hook with the atom-garbage collector (see
<a id="idx:garbagecollectatoms0:1890"></a><a class="pred" href="memory.html#garbage_collect_atoms/0">garbage_collect_atoms/0</a>)
that is called on any atom that is reclaimed. The old hook is returned.
If no hook is currently defined, <code>NULL</code> is returned. The
argument of the called hook is the atom that is to be garbage collected.
The return value is an <code>int</code>. If the return value is zero,
the atom is <b>not</b> reclaimed. The hook may invoke any Prolog
predicate.
<p>The example below defines a foreign library for printing the garbage
collected atoms for debugging purposes.
<pre class="code">
#include <SWI-Stream.h>
#include <SWI-Prolog.h>
static int
atom_hook(atom_t a)
{ Sdprintf("AGC: deleting %s\n", PL_atom_chars(a));
return TRUE;
}
static PL_agc_hook_t old;
install_t
install()
{ old = PL_agc_hook(atom_hook);
}
install_t
uninstall()
{ PL_agc_hook(old);
}
</pre>
<p></dd>
</dl>
<p><h3 id="sec:foreigndata"><a id="sec:10.4.20"><span class="sec-nr">10.4.20</span> <span class="sec-title">Storing
foreign data</span></a></h3>
<a id="sec:foreigndata"></a>
<p>When combining foreign code with Prolog, it can be necessary to make
data represented in the foreign language available to Prolog. For
example, to pass it to another foreign function. At the end of this
section, there is a partial implementation of using foreign functions to
manage bit-vectors. Another example is the SGML/XML library that manages
a `parser' object, an object that represents the current state of the
parser and that can be directed to perform actions such as parsing a
document or make queries about the document content.
<p>This section provides some hints for handling foreign data in Prolog.
There are four options for storing such data:
<p>
<ul class="latex">
<li><i>Natural Prolog data</i><br>
Uses the representation one would choose if no foreign interface was
required. For example, a bitvector representing a list of small integers
can be represented as a Prolog list of integers.
<p>
<li><i>Opaque packed data on the stacks</i><br>
It is possible to represent the raw binary representation of the foreign
object as a Prolog string (see <a class="sec" href="strings.html">section
5.2</a>). Strings may be created from foreign data using <a class="func" href="foreigninclude.html#PL_put_string_nchars()">PL_put_string_nchars()</a>
and retrieved using
<a class="func" href="foreigninclude.html#PL_get_string_chars()">PL_get_string_chars()</a>.
It is good practice to wrap the string in a compound term with arity 1,
so Prolog can identify the type. The hook
<a id="idx:portray1:1891"></a><a class="pred" href="termrw.html#portray/1">portray/1</a>
rules may be used to streamline printing such terms during development.
<p>
<li><i>Opaque packed data in a blob</i><br>
Similar to the above solution, binary data can be stored in an atom. The
blob interface (<a class="sec" href="foreigninclude.html">section 10.4.7</a>)
provides additional facilities to assign a type and hook-functions that
act on creation and destruction of the underlying atom.
<p>
<li><i>Natural foreign data, passed as a pointer</i><br>
An alternative is to pass a pointer to the foreign data. Again, the
pointer is often wrapped in a compound term.
</ul>
<p>The choice may be guided using the following distinctions
<p>
<ul class="latex">
<li><i>Is the data opaque to Prolog</i><br>
With `opaque' data, we refer to data handled in foreign functions,
passed around in Prolog, but where Prolog never examines the contents of
the data itself. If the data is opaque to Prolog, the selection will be
driven solely by simplicity of the interface and performance.
<p>
<li><i>What is the lifetime of the data</i><br>
With `lifetime' we refer to how it is decided that the object is (or can
be) destroyed. We can distinguish three cases:
<p>
<ol class="latex">
<li>The object must be destroyed on backtracking and normal Prolog
garbage collection (i.e., it acts as a normal Prolog term). In this
case, representing the object as a Prolog string (second option above)
is the only feasible solution.
<p>
<li>The data must survive Prolog backtracking. This leaves two options.
One is to represent the object using a pointer and use explicit creation
and destruction, making the programmer responsible. The alternative is
to use the blob-interface, leaving destruction to the (atom) garbage
collector.
<p>
<li>The data lives as during the lifetime of a foreign function that
implements a predicate. If the predicate is deterministic, foreign
automatic variables are suitable. If the predicate is non-deterministic,
the data may be allocated using malloc() and a pointer may be passed.
See <a class="sec" href="foreigninclude.html">section 10.4.1.1</a>.
</ol>
</ul>
<p><h4 id="sec:foreign-store-data"><a id="sec:10.4.20.1"><span class="sec-nr">10.4.20.1</span> <span class="sec-title">Examples
for storing foreign data</span></a></h4>
<a id="sec:foreign-store-data"></a>
<p>In this section, we outline some examples, covering typical cases. In
the first example, we will deal with extending Prolog's data
representation with integer sets, represented as bit-vectors. Then, we
discuss the outline of the DDE interface.
<p><b>Integer sets</b> with not-too-far-apart upper- and lower-bounds
can be represented using bit-vectors. Common set operations, such as
union, intersection, etc., are reduced to simple <em>and</em>'ing and
<em>or</em>'ing the bit-vectors. This can be done using Prolog's
unbounded integers.
<p>For really demanding applications, foreign representation will
perform better, especially time-wise. Bit-vectors are naturally
expressed using string objects. If the string is wrapped in <code>bitvector/1</code>,
the lower-bound of the vector is 0 and the upper-bound is not defined;
an implementation for getting and putting the sets as well as the union
predicate for it is below.
<pre class="code">
#include <SWI-Prolog.h>
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
static functor_t FUNCTOR_bitvector1;
static int
get_bitvector(term_t in, int *len, unsigned char **data)
{ if ( PL_is_functor(in, FUNCTOR_bitvector1) )
{ term_t a = PL_new_term_ref();
PL_get_arg(1, in, a);
return PL_get_string(a, (char **)data, len);
}
PL_fail;
}
static int
unify_bitvector(term_t out, int len, const unsigned char *data)
{ if ( PL_unify_functor(out, FUNCTOR_bitvector1) )
{ term_t a = PL_new_term_ref();
PL_get_arg(1, out, a);
return PL_unify_string_nchars(a, len, (const char *)data);
}
PL_fail;
}
static foreign_t
pl_bitvector_union(term_t t1, term_t t2, term_t u)
{ unsigned char *s1, *s2;
int l1, l2;
if ( get_bitvector(t1, &l1, &s1) &&
get_bitvector(t2, &l2, &s2) )
{ int l = max(l1, l2);
unsigned char *s3 = alloca(l);
if ( s3 )
{ int n;
int ml = min(l1, l2);
for(n=0; n<ml; n++)
s3[n] = s1[n] | s2[n];
for( ; n < l1; n++)
s3[n] = s1[n];
for( ; n < l2; n++)
s3[n] = s2[n];
return unify_bitvector(u, l, s3);
}
return PL_warning("Not enough memory");
}
PL_fail;
}
install_t
install()
{ PL_register_foreign("bitvector_union", 3, pl_bitvector_union, 0);
FUNCTOR_bitvector1 = PL_new_functor(PL_new_atom("bitvector"), 1);
}
</pre>
<p><b>The DDE interface</b> (see <a class="sec" href="DDE.html">section
4.41</a>) represents another common usage of the foreign interface:
providing communication to new operating system features. The DDE
interface requires knowledge about active DDE server and client
channels. These channels contains various foreign data types. Such an
interface is normally achieved using an open/close protocol that creates
and destroys a <em>handle</em>. The handle is a reference to a foreign
data structure containing the relevant information.
<p>There are a couple of possibilities for representing the handle. The
choice depends on responsibilities and debugging facilities. The
simplest approach is to use <a class="func" href="foreigninclude.html#PL_unify_pointer()">PL_unify_pointer()</a>
and <a class="func" href="foreigninclude.html#PL_get_pointer()">PL_get_pointer()</a>.
This approach is fast and easy, but has the drawbacks of (untyped)
pointers: there is no reliable way to detect the validity of the
pointer, nor to verify that it is pointing to a structure of the desired
type. The pointer may be wrapped into a compound term with arity 1
(i.e., <code>dde_channel(<<var>Pointer</var>>)</code>), making the
type-problem less serious.
<p>Alternatively (used in the DDE interface), the interface code can
maintain a (preferably variable length) array of pointers and return the
index in this array. This provides better protection. Especially for
debugging purposes, wrapping the handle in a compound is a good
suggestion.
<p><h3 id="sec:embedded"><a id="sec:10.4.21"><span class="sec-nr">10.4.21</span> <span class="sec-title">Embedding
SWI-Prolog in other applications</span></a></h3>
<a id="sec:embedded"></a>
<p>With embedded Prolog we refer to the situation where the `main'
program is not the Prolog application. Prolog is sometimes embedded in
C, C++, Java or other languages to provide logic based services in a
larger application. Embedding loads the Prolog engine as a library to
the external language. Prolog itself only provides for embedding in the
C language (compatible with C++). Embedding in Java is achieved using
JPL using a C-glue between the Java and Prolog C interfaces.
<p>The most simple embedded program is below. The interface function
<a class="func" href="foreigninclude.html#PL_initialise()">PL_initialise()</a> <b>must</b>
be called before any of the other SWI-Prolog foreign language functions
described in this chapter, except for
<b>PL_initialise_hook()</b>, <a class="func" href="foreigninclude.html#PL_new_atom()">PL_new_atom()</a>, <a class="func" href="foreigninclude.html#PL_new_functor()">PL_new_functor()</a>
and
<a class="func" href="foreigninclude.html#PL_register_foreign()">PL_register_foreign()</a>. <a class="func" href="foreigninclude.html#PL_initialise()">PL_initialise()</a>
interprets all the command line arguments, except for the <strong>-t</strong> <var>toplevel</var>
flag that is interpreted by <a class="func" href="foreigninclude.html#PL_toplevel()">PL_toplevel()</a>.
<pre class="code">
int
main(int argc, char **argv)
{
#ifdef READLINE /* Remove if you don't want readline */
PL_initialise_hook(install_readline);
#endif
if ( !PL_initialise(argc, argv) )
PL_halt(1);
PL_halt(PL_toplevel() ? 0 : 1);
}
</pre>
<dl class="latex">
<dt class="pubdef"><a id="PL_initialise()"><var>int</var> <strong>PL_initialise</strong>(<var>int
argc, char **argv</var>)</a></dt>
<dd class="defbody">
Initialises the SWI-Prolog heap and stacks, restores the Prolog state,
loads the system and personal initialisation files, runs the <a id="idx:initialization1:1892"></a><a class="pred" href="consulting.html#initialization/1">initialization/1</a>
hooks and finally runs the
<strong>-g</strong> <var>goal</var> hook.
<p>Special consideration is required for <code>argv[0]</code>. On <b>Unix</b>,
this argument passes the part of the command line that is used to locate
the executable. Prolog uses this to find the file holding the running
executable. The <b>Windows</b> version uses this to find a <em>module</em>
of the running executable. If the specified module cannot be found, it
tries the module <code>libpl.dll</code>, containing the Prolog runtime
kernel. In all these cases, the resulting file is used for two purposes:
<p>
<ul class="latex">
<li>See whether a Prolog saved state is appended to the file. If this is
the case, this state will be loaded instead of the default <code>boot.prc</code>
file from the SWI-Prolog home directory. See also <a id="idx:qsaveprogram12:1893"></a><span class="pred-ext">qsave_program/[1,2]</span>
and <a class="sec" href="plld.html">section 10.5</a>.
<li>Find the Prolog home directory. This process is described in detail
in <a class="sec" href="findhome.html">section 10.6</a>.
</ul>
<p><a class="func" href="foreigninclude.html#PL_initialise()">PL_initialise()</a>
returns 1 if all initialisation succeeded and 0 otherwise.<sup class="fn">bug<span class="fn-text">Various
fatal errors may cause <a class="func" href="foreigninclude.html#PL_initialise()">PL_initialise()</a>
to call <a class="func" href="foreigninclude.html#PL_halt()">PL_halt(1)</a>,
preventing it from returning at all.</span></sup>
<p>In most cases, <var>argc</var> and <var>argv</var> will be passed
from the main program. It is allowed to create your own argument vector,
provided
<code>argv[0]</code> is constructed according to the rules above. For
example:
<pre class="code">
int
main(int argc, char **argv)
{ char *av[10];
int ac = 0;
av[ac++] = argv[0];
av[ac++] = "-x";
av[ac++] = "mystate";
av[ac] = NULL;
if ( !PL_initialise(ac, av) )
PL_halt(1);
...
}
</pre>
<p>Please note that the passed argument vector may be referred from
Prolog at any time and should therefore be valid as long as the Prolog
engine is used.
<p>A good setup in Windows is to add SWI-Prolog's <code>bin</code>
directory to your <code>PATH</code> and either pass a module holding a
saved state, or
<code>"libpl.dll"</code> as <code>argv[0]</code>. If the Prolog state is
attached to a DLL (see the <strong>-dll</strong> option of <b>swipl-ld</b>),
pass the name of this DLL.</dd>
<dt class="pubdef"><a id="PL_is_initialised()"><var>int</var> <strong>PL_is_initialised</strong>(<var>int
*argc, char ***argv</var>)</a></dt>
<dd class="defbody">
Test whether the Prolog engine is already initialised. Returns
<code>FALSE</code> if Prolog is not initialised and <code>TRUE</code>
otherwise. If the engine is initialised and <var>argc</var> is not <code>NULL</code>,
the argument count used with <a class="func" href="foreigninclude.html#PL_initialise()">PL_initialise()</a>
is stored in <var>argc</var>. Same for the argument vector <var>argv</var>.</dd>
<dt class="pubdef"><a id="PL_install_readline()"><var>void</var> <strong>PL_install_readline</strong>(<var></var>)</a></dt>
<dd class="defbody">
Installs the GNU readline line editor. Embedded applications that do not
use the Prolog top level should normally delete this line, shrinking the
Prolog kernel significantly. Note that the Windows version does not use
GNU readline.</dd>
<dt class="pubdef"><a id="PL_toplevel()"><var>int</var> <strong>PL_toplevel</strong>(<var></var>)</a></dt>
<dd class="defbody">
Runs the goal of the <strong>-t</strong> <var>toplevel</var> switch
(default <a id="idx:prolog0:1894"></a><a class="pred" href="toplevel.html#prolog/0">prolog/0</a>)
and returns 1 if successful, 0 otherwise.</dd>
<dt class="pubdef"><a id="PL_cleanup()"><var>int</var> <strong>PL_cleanup</strong>(<var>int
status</var>)</a></dt>
<dd class="defbody">
This function performs the reverse of <a class="func" href="foreigninclude.html#PL_initialise()">PL_initialise()</a>.
It runs the
<a class="func" href="foreigninclude.html#PL_on_halt()">PL_on_halt()</a>
and <a id="idx:athalt1:1895"></a><a class="pred" href="consulting.html#at_halt/1">at_halt/1</a>
handlers, closes all streams (except for the `standard I/O' streams
which are flushed only), deallocates all memory and restores all signal
handlers. The <var>status</var> argument is passed to the various
termination hooks and indicates the <em>exit-status</em>.
<p>The function returns <code>TRUE</code> if successful and <code>FALSE</code>
otherwise. Currently, <code>FALSE</code> is returned when an attempt is
made to call <a class="func" href="foreigninclude.html#PL_cleanup()">PL_cleanup()</a>
recursively or if one of the exit handlers cancels the termination using <a id="idx:cancelhalt1:1896"></a><a class="pred" href="consulting.html#cancel_halt/1">cancel_halt/1</a>.
Exit handlers may only cancel termination if <var>status</var> is 0.
<p>In theory, this function allows deleting and restarting the Prolog
system in the same process. In practice, SWI-Prolog's cleanup process is
far from complete, and trying to revive the system using <a class="func" href="foreigninclude.html#PL_initialise()">PL_initialise()</a>
will leak memory in the best case. It can also crash the appliction.
<p>In this state, there is little practical use for this function. If
you want to use Prolog temporarily, consider running it in a separate
process. If you want to be able to reset Prolog, your options are
(again) a separate process, modules or threads.</dd>
<dt class="pubdef"><a id="PL_cleanup_fork()"><var>void</var> <strong>PL_cleanup_fork</strong>(<var></var>)</a></dt>
<dd class="defbody">
Stop intervaltimer that may be running on behalf of <a id="idx:profile1:1897"></a><a class="pred" href="profile.html#profile/1">profile/1</a>.
The call is intended to be used in combination with fork():
<pre class="code">
if ( (pid=fork()) == 0 )
{ PL_cleanup_fork();
<some exec variation>
}
</pre>
<p>The call behaves the same on Windows, though there is probably no
meaningful application.</dd>
<dt class="pubdef"><a id="PL_halt()"><var>int</var> <strong>PL_halt</strong>(<var>int
status</var>)</a></dt>
<dd class="defbody">
Clean up the Prolog environment using <a class="func" href="foreigninclude.html#PL_cleanup()">PL_cleanup()</a>
and if successful call exit() with the status argument. Returns <code>FALSE</code>
if exit was cancelled by <a class="func" href="foreigninclude.html#PL_cleanup()">PL_cleanup()</a>.
</dd>
</dl>
<p><h4 id="sec:sigembedded"><a id="sec:10.4.21.1"><span class="sec-nr">10.4.21.1</span> <span class="sec-title">Threading,
Signals and embedded Prolog</span></a></h4>
<a id="sec:sigembedded"></a>
<p>This section applies to Unix-based environments that have signals or
multithreading. The Windows version is compiled for multithreading, and
Windows lacks proper signals.
<p>We can distinguish two classes of embedded executables. There are
small C/C++ programs that act as an interfacing layer around Prolog.
Most of these programs can be replaced using the normal Prolog
executable extended with a dynamically loaded foreign extension and in
most cases this is the preferred route. In other cases, Prolog is
embedded in a complex application that---like Prolog---wants to control
the process environment. A good example is Java. Embedding Prolog is
generally the only way to get these environments together in one process
image. Java applications, however, are by nature multithreaded and
appear to do signal handling (software interrupts).
<p>On Unix systems, SWI-Prolog uses three signals:
<dl class="latex">
<dt><b>SIGUSR1</b></dt>
<dd>
is used to sychronise atom and clause garbage collection. The handler is
installed at the start of garbage collection and reverted to the old
setting after completion.</dd>
<dt><b>SIGUSR2</b></dt>
<dd>
has an empty signal handler. This signal is sent to a thread after
sending a thread-signal (see
<a id="idx:threadsignal2:1898"></a><a class="pred" href="threadcom.html#thread_signal/2">thread_signal/2</a>).
It causes blocking system calls to return with <code>EINTR</code>, which
gives them the opportunity to react to thread-signals.</dd>
<dt><b>SIGINT</b></dt>
<dd>
is used by the top level to activate the tracer (typically bound to
control-C). The first control-C posts a request for starting the tracer
in a safe, synchronous fashion. If control-C is hit again before the
safe route is executed, it prompts the user whether or not a forced
interrupt is desired.
</dd>
</dl>
<p>The <strong>--nosignals</strong> option can be used to inhibit
processing of <code>SIGINT</code>. The other signals are vital for the
functioning of SWI-Prolog. If they conflict with other applications,
signal handling of either component must be modified. The SWI-Prolog
signals are defined in
<code>pl-thread.h</code> of the source distribution.
<p></body></html>
|