File: foreign.doc

package info (click to toggle)
swi-prolog 5.10.1-1%2Bsqueeze1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 76,436 kB
  • ctags: 45,143
  • sloc: ansic: 290,417; perl: 215,108; sh: 5,411; java: 5,136; makefile: 5,021; cpp: 2,168; yacc: 843; xml: 77; sed: 12
file content (3416 lines) | stat: -rw-r--r-- 136,920 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
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
\chapter{Foreign Language Interface}		\label{sec:foreign}

\newlength{\tableft}
\settowidth{\tableft}{\const{PL_QUERY_ORGSYMBOLFILE}}

SWI-Prolog offers a powerful interface to C \cite{Kernighan:78}. The
main design objectives of the foreign language interface are flexibility
and performance. A foreign predicate is a C-function that has the same
number of arguments as the predicate represented. C-functions are
provided to analyse the passed terms, convert them to basic C-types as
well as to instantiate arguments using unification. Non-deterministic
foreign predicates are supported, providing the foreign function with a
handle to control backtracking.

C can call Prolog predicates, providing both an query interface and
an interface to extract multiple solutions from an non-deterministic
Prolog predicate.  There is no limit to the nesting of Prolog calling
C, calling Prolog, etc.  It is also possible to write the `main' in
C and use Prolog as an embedded logical engine.


\section{Overview of the Interface}		\label{sec:foreignoverview}

A special include file called \file{SWI-Prolog.h} should be included
with each C-source file that is to be loaded via the foreign interface.
The installation process installs this file in the directory
\file{include} in the SWI-Prolog home directory (\exam{?-
current_prolog_flag(home, Home).}). This C-header file defines various
data types, macros and functions that can be used to communicate with
SWI-Prolog. Functions and macros can be divided into the following
categories:

\begin{shortlist}
    \item Analysing Prolog terms
    \item Constructing new terms
    \item Unifying terms
    \item Returning control information to Prolog
    \item Registering foreign predicates with Prolog
    \item Calling Prolog from C
    \item Recorded database interactions
    \item Global actions on Prolog (halt, break, abort, etc.)
\end{shortlist}


\section{Linking Foreign Modules}		\label{sec:foreignlink}

Foreign modules may be linked to Prolog in two ways. Using
\jargon{static linking}, the extensions, a (short) file defining main()
which attaches the extensions calls Prolog and the SWI-Prolog kernel
distributed as a C-library are linked together to form a new executable.
Using \jargon{dynamic linking}, the extensions are linked to a shared
library (\fileext{so} file on most Unix systems) or dynamic-link library
(\fileext{DLL} file on Microsoft platforms) and loaded into the
running Prolog process.%
    \footnote{The system also contains code to load \fileext{o} files
              directly for some operating systems, notably Unix systems
              using the BSD \file{a.out} executable format. As the number of
              Unix platforms supporting this gets quickly smaller and
              this interface is difficult to port and slow, it is no
              longer described in this manual.  The best alternatively
              would be to use the \idx{dld} package on machines do
	      not have shared libraries}.

\subsection{What linking is provided?}

The \jargon{static linking} schema can be used on all versions of
SWI-Prolog. Whether or not dynamic linking is supported can be deduced
from the Prolog flag \prologflag{open_shared_object} (see
current_prolog_flag/2). If this Prolog flag yields true,
open_shared_object/2 and related predicates are defined. See
\secref{shlib} for a suitable high-level interface to these predicates.

\subsection{What kind of loading should I be using?}

All described approaches have their advantages and disadvantages. Static
linking is portable and allows for debugging on all platforms. It is
relatively cumbersome and the libraries you need to pass to the linker
may vary from system to system, though the utility program
\program{swipl-ld} described in \secref{plld} often hides these problems
from the user.

Loading shared objects (DLL files on Windows) provides sharing and
protection and is generally the best choice. If a saved-state is created
using qsave_program/[1,2], an initialization/1 directive may be used to
load the appropriate library at startup.

Note that the definition of the foreign predicates is the same, regardless
of the linking type used.

\input{lib/shlib}

\subsection{Low-level operations on shared libraries}
\label{sec:sharedobj}

The interface defined in this section allows the user to load shared
libraries (\fileext{so} files on most Unix systems, \fileext{dll} files
on Windows). This interface is portable to Windows as well as to Unix
machines providing \manref{dlopen}{2} (Solaris, Linux, FreeBSD, Irix and
many more) or \manref{shl_open}{2} (HP/UX). It is advised to use the
predicates from \secref{shlib} in your application.


\begin{description}
    \predicate{open_shared_object}{2}{+File, -Handle}
\arg{File} is the name of a shared object file (called dynamic load
library in MS-Windows). This file is attached to the current process and
\arg{Handle} is unified with a handle to the library. Equivalent to
\exam{open_shared_object(File, [], Handle)}. See also
load_foreign_library/[1,2].

On errors, an exception \term{shared_object}{Action, Message} is
raised. \arg{Message} is the return value from dlerror().

    \predicate{open_shared_object}{3}{+File, -Handle, +Options}
As open_shared_object/2, but allows for additional flags to be passed.
\arg{Options} is a list of atoms. \const{now} implies the symbols are
resolved immediately rather than lazy (default). \const{global} implies
symbols of the loaded object are visible while loading other shared
objects (by default they are local). Note that these flags may not be
supported by your operating system. Check the documentation of dlopen()
or equivalent on your operating system.  Unsupported flags are silently
ignored.

    \predicate{close_shared_object}{1}{+Handle}
Detach the shared object identified by \arg{Handle}.

    \predicate{call_shared_object_function}{2}{+Handle, +Function}
Call the named function in the loaded shared library.  The function
is called without arguments and the return-value is ignored.  Normally
this function installs foreign language predicates using calls to
PL_register_foreign().
\end{description}


\subsection{Static Linking} \label{sec:staticl}

Below is an outline of the files structure required for statically
linking SWI-Prolog with foreign extensions. \file{\ldots/pl} refers to
the SWI-Prolog home directory (see the Prolog flag \prologflag{home}).
\file{<arch>} refers to the architecture identifier that may be obtained
using the Prolog flag \prologflag{arch}.

\begin{center}
\begin{tabular}{ll}
\file{.../pl/runtime/<arch>/libswipl.a} & SWI-Library \\
\file{.../pl/include/SWI-Prolog.h}      & Include file \\
\file{.../pl/include/SWI-Stream.h}      & Stream I/O include file \\
\file{.../pl/include/SWI-Exports}       & Export declarations (AIX only) \\
\file{.../pl/include/stub.c}            & Extension stub
\end{tabular}
\end{center}

The definition of the foreign predicates is the same as for dynamic
linking.  Unlike with dynamic linking however, there is no
initialisation function.  Instead, the file \file{\ldots/pl/include/stub.c}
may be copied to your project and modified to define the foreign
extensions.  Below is stub.c, modified to link the lowercase example
described later in this chapter:

\begin{code}
#include <stdio.h>
#include <SWI-Prolog.h>

extern foreign_t pl_lowercase(term, term);

PL_extension predicates[] =
{
/*{ "name",      arity,  function,      PL_FA_<flags> },*/

  { "lowercase", 2       pl_lowercase,  0 },
  { NULL,        0,      NULL,          0 }     /* terminating line */
};


int
main(int argc, char **argv)
{ PL_register_extensions(predicates);

  if ( !PL_initialise(argc, argv) )
    PL_halt(1);

  PL_install_readline();                /* delete if not required */

  PL_halt(PL_toplevel() ? 0 : 1);
}
\end{code}

Now, a new executable may be created by compiling this file and linking
it to \file{libpl.a} from the runtime directory and the libraries
required by both the extensions and the SWI-Prolog kernel. This may be
done by hand, or using the \program{swipl-ld} utility described in
secref{plld}. If the linking is performed `by hand', the command-line
option \const{-dump-runtime-variables} (see \secref{cmdline}) can be
used to obtain the required paths, libraries and linking options to link
the new executable.

\section{Interface Data types}		\label{sec:foreigntypes}

\subsection{Type \ctype{term_t}: a reference to a Prolog term}

The principal data-type is \ctype{term_t}. Type \ctype{term_t} is what
Quintus calls \ctype{QP_term_ref}. This name indicates better what the
type represents: it is a \jargon{handle} for a term rather than the term
itself. Terms can only be represented and manipulated using this type,
as this is the only safe way to ensure the Prolog kernel is aware of all
terms referenced by foreign code and thus allows the kernel to perform
garbage-collection and/or stack-shifts while foreign code is active,
for example during a callback from C.

A term reference is a C unsigned long, representing the offset of a
variable on the Prolog environment-stack.  A foreign function is passed
term references for the predicate-arguments, one for each argument.  If
references for intermediate results are needed, such references may be
created using PL_new_term_ref() or PL_new_term_refs().  These references
normally live till the foreign function returns control back to Prolog.
Their scope can be explicitly limited using PL_open_foreign_frame()
and PL_close_foreign_frame()/PL_discard_foreign_frame().

A term_t always refers to a valid Prolog term (variable, atom, integer,
float or compound term). A term lives either until backtracking takes us
back to a point before the term was created, the garbage collector has
collected the term or the term was created after a
PL_open_foreign_frame() and PL_discard_foreign_frame() has been called.

The foreign-interface functions can either {\em read}, {\em unify} or
{\em write} to term-references.  In the this document we use the
following notation for arguments of type term_t:

\begin{quote}
\begin{tabular}{lp{3.5in}}
\tt term_t +t   & Accessed in read-mode.  The `+' indicates the
                  argument is `input'. \\
\tt term_t -t   & Accessed in write-mode. \\
\tt term_t ?t   & Accessed in unify-mode. \\
\end{tabular}
\end{quote}

\noindent
Term references are obtained in any of the following ways.

\begin{itemlist}
\item [Passed as argument]
    The C-functions implementing foreign predicates are passed their
    arguments as term-references.  These references may be read or
    unified.  Writing to these variables causes undefined behaviour.
\item [Created by PL_new_term_ref()]
    A term created by PL_new_term_ref() is normally used to build
    temporary terms or be written by one of the interface functions.
    For example, PL_get_arg() writes a reference to the term-argument
    in its last argument.
\item [Created by PL_new_term_refs(int n)]
    This function returns a set of term refs with the same characteristics
    as PL_new_term_ref().  See PL_open_query().
\item [Created by PL_copy_term_ref(term_t t)]
    Creates a new term-reference to the same term as the argument.  The
    term may be written to.  See \figref{pl-display}.
\end{itemlist}

Term-references can safely be copied to other C-variables of type
term_t, but all copies will always refer to the same term.

\begin{description}
\cfunction{term_t}{PL_new_term_ref}{}
Return a fresh reference to a term.  The reference is allocated on the
\jargon{local} stack.  Allocating a term-reference may trigger a stack-shift
on machines that cannot use sparse-memory management for allocation the
Prolog stacks.  The returned reference describes a variable.
\cfunction{term_t}{PL_new_term_refs}{int n}
Return \arg{n} new term references.  The first term-reference is returned.
The others are $\arg{t}+1$, $\arg{t}+2$, etc.  There are two reasons
for using this function.  PL_open_query() expects the arguments as a set
of consecutive term references and {\em very} time-critical code requiring
a number of term-references can be written as:

\begin{code}
pl_mypredicate(term_t a0, term_t a1)
{ term_t t0 = PL_new_term_refs(2);
  term_t t1 = t0+1;

  ...
}
\end{code}
\cfunction{term_t}{PL_copy_term_ref}{term_t from}
Create a new term reference and make it point initially to the same
term as \arg{from}.  This function is commonly used to copy a predicate
argument to a term reference that may be written.
\cfunction{void}{PL_reset_term_refs}{term_t after}
Destroy all term references that have been created after \arg{after},
including \arg{after} itself. Any reference to the invalidated  term
references after this call results in undefined behaviour.

Note that returning from the foreign context to Prolog will reclaim
all references used in the foreign context.  This call is only necessary
if references are created inside a loop that never exits back to Prolog.
See also PL_open_foreign_frame(), PL_close_foreign_frame() and
PL_discard_foreign_frame().
\end{description}


\subsubsection{Interaction with the garbage collector and stack-shifter}

Prolog implements two mechanisms for avoiding stack overflow: garbage
collection and stack expansion. On machines that allow for it, Prolog
will use virtual memory management to detect stack overflow and expand
the runtime stacks. On other machines Prolog will reallocate the stacks
and update all pointers to them. To do so, Prolog needs to know which
data is referenced by C-code. As all Prolog data known by C is
referenced through term references (\ctype{term_t}), Prolog has all
information necessary to perform its memory management without
special precautions from the C-programmer.


\subsection{Other foreign interface types}

\begin{description}
    \item[atom_t]
An atom in Prologs internal representation.  Atoms are pointers to an
opaque structure.  They are a unique representation for represented
text, which implies that atom $A$ represents the same text as
atom $B$ if-and-only-if $A$ and $B$ are the same pointer.

Atoms are the central representation for textual constants in Prolog
The transformation of C a character string to an atom implies a
hash-table lookup.  If the same atom is needed often, it is advised
to store its reference in a global variable to avoid repeated lookup.
    \item[functor_t]
A functor is the internal representation of a name/arity pair. They are
used to find the name and arity of a compound term as well as to
construct new compound terms. Like atoms they live for the whole Prolog
session and are unique.
    \item[predicate_t]
Handle to a Prolog predicate. Predicate handles live forever (although
they can loose their definition).
    \item[qid_t]
Query Identifier. Used by
PL_open_query()/PL_next_solution()/PL_close_query() to handle
backtracking from C.
    \item[fid_t]
Frame Identifier. Used by
PL_open_foreign_frame()/PL_close_foreign_frame().
    \item[module_t]
A module is a unique handle to a Prolog module. Modules are used only
to call predicates in a specific module.
    \item[foreign_t]
Return type for a C-function implementing a Prolog predicate.
    \item[control_t]
Passed as additional argument to non-deterministic foreign functions.
See PL_retry*() and PL_foreign_context*().
    \item[install_t]
Type for the install() and uninstall() functions of shared
or dynamic link libraries.  See secref{shlib}.
    \item[int64_t]
Actually part of the C99 standard rather than Prolog.  As of version
5.5.6, Prolog integers are 64-bit on all hardware.  The C99 type
int64_t is defined in the \file{stdint.h} standard header and provides
platform independent 64-bit integers.  Portable code accessing Prolog
should use this type to exchange integer values.  Please note that
PL_get_long() can return \const{FALSE} on Prolog integers outside
the long domain.  Robust code should not assume any of the integer
fetching functions to succeed if the Prolog term is know to be an
integer.
\end{description}

\section{The Foreign Include File}	\label{sec:foreigninclude}

\subsection{Argument Passing and Control}

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 $1, \ldots, <arity>$ pass the Prolog arguments to the goal
as Prolog terms. Foreign functions should be declared of type
\ctype{foreign_t}. Deterministic foreign functions have two alternatives
to return control back to Prolog:

\begin{description}
    \cmacro{(return) foreign_t}{PL_succeed}{}
Succeed deterministically. PL_succeed is defined as
\exam{return \const{TRUE}}.
    \cmacro{(return) foreign_t}{PL_fail}{}
Fail and start Prolog backtracking.  PL_fail is defined as \exam{return
\const{FALSE}}.
\end{description}

\subsubsection{Non-deterministic Foreign Predicates}	\label{sec:foreignnondet}

By default foreign predicates are deterministic. Using the
\const{PL_FA_NONDETERMINISTIC} attribute (see PL_register_foreign()) 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:

\begin{code}
quotient_below_n(Q, N) :-
        natural_number_below_n(N, N1),
        natural_number_below_n(N, N2),
        Q =:= N1 / N2, !.
\end{code}

In this predicate the function {natural_number_below_n}/2 simultaneously
generates solutions for both its invocations.

Non-deterministic foreign functions should be prepared to handle three
different calls from Prolog:

\begin{itemlist}
    \item [Initial call (\const{PL_FIRST_CALL})]
Prolog has just created a frame for the foreign function and asks it to
produce the first answer.
    \item [Redo call (\const{PL_REDO})]
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.
    \item [Terminate call (\const{PL_PRUNED})]
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.
\end{itemlist}

Both the context information and the type of call is provided by an
argument of type \ctype{control_t} appended to the argument list for
deterministic foreign functions.  The macro PL_foreign_control()
extracts the type of call from the control argument.  The foreign
function can pass a context handle using the {\tt PL_retry*()} macros and
extract the handle from the extra argument using the
{\tt PL_foreign_context*()} macro.

\begin{description}
    \cmacro{(return) foreign_t}{PL_retry}{long}
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 PL_foreign_context() returns the handle passed via
PL_retry(). This handle is a 30 bits signed value (two bits are used
for status indication).  Defined as \exam{return _PL_retry(n)}.
See also PL_succeed().

    \cmacro{(return) foreign_t}{PL_retry_address}{void *}
As PL_retry(), but ensures an address as returned by malloc() is
correctly recovered by PL_foreign_context_address().
Defined as \exam{return _PL_retry_address(n)}. See also
PL_succeed().

    \cmacro{int}{PL_foreign_control}{control_t}
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 \const{PL_PRUNED} case and should be aware that the other
arguments are not valid in this case.

    \cmacro{long}{PL_foreign_context}{control_t}
Extracts the context from the context argument.  In the call type is
\const{PL_FIRST_CALL} the context value is 0L.  Otherwise it is the value
returned by the last PL_retry() associated with this goal (both if the
call type is \const{PL_REDO} as \const{PL_PRUNED}).

    \cmacro{void *}{PL_foreign_context_address}{control_t}
Extracts an address as passed in by PL_retry_address().
\end{description}

Note: If a non-deterministic foreign function returns using PL_succeed
or PL_fail, Prolog assumes the foreign function has cleaned its
environment. {\bf No} call with control argument \const{PL_PRUNED} will
follow.

The code of \figref{nondetermf} shows a skeleton for a
non-deterministic foreign predicate definition.

\begin{figure}
\begin{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;
  }
}
\end{code}
    \caption{Skeleton for non-deterministic foreign functions}
    \label{fig:nondetermf}
\end{figure}


\subsection{Atoms and functors}

The following functions provide for communication using atoms and
functors.

\begin{description}
    \cfunction{atom_t}{PL_new_atom}{const char *}
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 \secref{atomgc}).

    \cfunction{const char*}{PL_atom_chars}{atom_t atom}
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 \secref{atomgc}).  Foreign functions that require
the text from an atom passed in a \ctype{term_t} normally use
PL_get_atom_chars() or PL_get_atom_nchars().

    \cfunction{functor_t}{PL_new_functor}{atom_t name, int arity}
Returns a {\em functor identifier}, a handle for the name/arity
pair.  The returned handle is valid for the entire Prolog session.
\cfunction{atom_t}{PL_functor_name}{functor_t f}
Return an atom representing the name of the given functor.
\cfunction{int}{PL_functor_arity}{functor_t f}
Return the arity of the given functor.
\end{description}


\subsubsection{Atoms and atom-garbage collection}	\label{sec:atomgc}

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
\jargon{call-port}. In the multi-threaded version (see \secref{threads}),
they appear asynchronously, except for the invoking thread.

For dealing with atom garbage collection, two additional functions are
provided:

\begin{description}
    \cfunction{void}{PL_register_atom}{atom_t atom}
Increment the reference count of the atom by one. PL_new_atom() performs
this automatically, returning an atom with a reference count of at least
one.%
	\footnote{Otherwise asynchronous atom garbage collection might
		  destroy the atom before it is used.}

    \cfunction{void}{PL_unregister_atom}{atom_t atom}
Decrement the reference count of the atom.  If the reference-count
drops below zero, an assertion error is raised.
\end{description}

Please note that the following two calls are different with respect to
atom garbage collection:

\begin{code}
PL_unify_atom_chars(t, "text");
PL_unify_atom(t, PL_new_atom("text"));
\end{code}

The latter increments the reference count of the atom \const{text},
which effectively ensures the atom will never be collected.  It is
advised to use the *_chars() or *_nchars() functions whenever
applicable.


\subsection{Analysing Terms via the Foreign Interface}

Each argument of a foreign function (except for the control argument) is
of type \ctype{term_t}, 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 var/1, atom/1, etc and
are called {\tt PL_is_*()}. The second group attempts to translate the
argument into a C primitive type. These predicates take a \ctype{term_t}
and a pointer to the appropriate C-type and return \const{TRUE} or
\const{FALSE} depending on successful or unsuccessful translation. If the
translation fails, the pointed-to data is never modified.

\subsubsection{Testing the type of a term}

\begin{description}
\cfunction{int}{PL_term_type}{term_t}
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 {\tt PL_ge_t*()} also
validate the type and thus the two sections below are equivalent.

\begin{code}
        if ( PL_is_atom(t) )
        { char *s;

          PL_get_atom_chars(t, &s);
          ...;
        }

or

        char *s;
        if ( PL_get_atom_chars(t, &s) )
        { ...;
        }
\end{code}

\begin{tabular}{|p{\tableft}|p{3.5in}|}
\hline
\const{PL_VARIABLE} & An unbound variable. The value of term as such
		      is a unique identifier for the variable. \\
\const{PL_ATOM}     & A Prolog atom. \\
\const{PL_STRING}   & A Prolog string. \\
\const{PL_INTEGER}  & A Prolog integer. \\
\const{PL_FLOAT}    & A Prolog floating point number. \\
\const{PL_TERM}     & A compound term. Note that a list is a
		      compound term \functor{.}{2}. \\
\hline
\end{tabular}
\end{description}

The functions PL_is_<type> are an alternative to PL_term_type(). The
test \exam{PL_is_variable(term)} is equivalent to
\exam{PL_term_type(term) == PL_VARIABLE}, but the first is considerably
faster. On the other hand, using a switch over PL_term_type() is faster
and more readable then using an if-then-else using the functions below.
All these functions return either \const{TRUE} or \const{FALSE}.

\begin{description}
\cfunction{int}{PL_is_variable}{term_t}
Returns non-zero if \arg{term} is a variable.
\cfunction{int}{PL_is_ground}{term_t}
Returns non-zero if \arg{term} is a ground term.  See also ground/1.
This function is cycle-safe.
\cfunction{int}{PL_is_atom}{term_t}
Returns non-zero if \arg{term} is an atom.
\cfunction{int}{PL_is_string}{term_t}
Returns non-zero if \arg{term} is a string.
\cfunction{int}{PL_is_integer}{term_t}
Returns non-zero if \arg{term} is an integer.
\cfunction{int}{PL_is_float}{term_t}
Returns non-zero if \arg{term} is a float.
\cfunction{int}{PL_is_compound}{term_t}
Returns non-zero if \arg{term} is a compound term.
\cfunction{int}{PL_is_functor}{term_t, functor_t}
Returns non-zero if \arg{term} is compound and its functor is \arg{functor}.
This test is equivalent to PL_get_functor(), followed by testing the
functor, but easier to write and faster.
\cfunction{int}{PL_is_list}{term_t}
Returns non-zero if \arg{term} is a compound term with functor ./2 or
the atom \const{[]}.
\cfunction{int}{PL_is_atomic}{term_t}
Returns non-zero if \arg{term} is atomic (not variable or compound).
\cfunction{int}{PL_is_number}{term_t}
Returns non-zero if \arg{term} is an integer or float.
\cfunction{int}{PL_is_acyclic}{term_t}
Returns non-zero if \arg{term} is acyclic (i.e.\ a finite tree).
\end{description}


\subsubsection{Reading data from a term}

The functions {\tt PL_get_*()} 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.

\begin{description}
    \cfunction{int}{PL_get_atom}{term_t +t, atom_t *a}
If \arg{t} is an atom, store the unique atom identifier over \arg{a}.
See also PL_atom_chars() and PL_new_atom(). 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 \arg{t}, it
will live at least as long as \arg{t} does.  If longer live-time is
required, the atom should be locked using PL_register_atom().

    \cfunction{int}{PL_get_atom_chars}{term_t +t, char **s}
If \arg{t} is an atom, store a pointer to a 0-terminated C-string in
\arg{s}.  It is explicitly \strong{not} 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.

    \cfunction{int}{PL_get_string_chars}{term_t +t, char **s, int *len}
If \arg{t} is a string object, store a pointer to a 0-terminated
C-string in \arg{s} and the length of the string in \arg{len}.  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.

    \cfunction{int}{PL_get_chars}{term_t +t, char **s, unsigned flags}
Convert the argument term \arg{t} to a 0-terminated C-string.  {\em
flags} is a bitwise disjunction from two groups of constants.  The
first specifies which term-types should converted and the second
how the argument is stored.  Below is a specification of these
constants.  \const{BUF_RING} implies, if the data is not static
(as from an atom), 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 PL_free() when not
needed any longer.

With the introduction of wide-characters (see \secref{encoding}), not
all atoms can be converted into a \ctype{char*}.  This function fails
if \arg{t} is of the wrong type, but also if the text cannot be
represented.  See the \const{REP_*} flags below for details.

\begin{tabular}{|p{\tableft}|p{3.5in}|}
\hline
\const{CVT_ATOM}    & Convert if term is an atom \\
\const{CVT_STRING}  & Convert if term is a string \\
\const{CVT_LIST}    & Convert if term is a list of integers between
		      1 and 255 \\
\const{CVT_INTEGER} & Convert if term is an integer (using \const{\%d}) \\
\const{CVT_FLOAT}   & Convert if term is a float (using \const{\%f}) \\
\const{CVT_NUMBER}  & Convert if term is a integer or float \\
\const{CVT_ATOMIC}  & Convert if term is atomic \\
\const{CVT_VARIABLE}& Convert variable to print-name \\
\const{CVT_WRITE}   & Convert any term that is not converted by
		      any of the other flags using write/1.  If
		      no \const{BUF_*} is provided, \const{BUF_RING}
		      is implied. \\
\const{CVT_WRITE_CANINICAL} & As CVT_WRITE, but use write_canonical/2. \\
\const{CVT_ALL}     & Convert if term is any of the above, except for
                      \const{CVT_VARIABLE} and \const{CVT_WRITE} \\
\hline
\const{CVT_EXCEPTION}&If conversion fails due to a type error, raise
		      a Prolog type error exception in addition to
		      failure \\
\hline
\const{BUF_DISCARDABLE}     & Data must copied immediately \\
\const{BUF_RING}    & Data is stored in a ring of buffers \\
\const{BUF_MALLOC}  & Data is copied to a new buffer returned by
		      \manref{PL_malloc}{3}.  When no longer needed
		      the user must call PL_free() on the data. \\
\hline
\const{REP_ISO_LATIN_1}	& (0, default).  Text is in ISO Latin-1 encoding
		      and the call fails if text cannot be represented. \\
\const{REP_UTF8}	& Convert the text to a UTF-8 string.  This works
		      for all text. \\
\const{REP_MB}		& Convert to default locale-defined 8-bit string.
		      Success depends on the locale.  Conversion is done
		      using the wcrtomb() C-library function. \\
\hline
\end{tabular}

\cfunction{int}{PL_get_list_chars}{+term_t l, char **s, unsigned flags}
Same as \exam{PL_get_chars(\arg{l}, \arg{s}, CVT_LIST|\arg{flags})},
provided \arg{flags} contains no of the {\tt CVT_*} flags.
\cfunction{int}{PL_get_integer}{+term_t t, int *i}
If \arg{t} is a Prolog integer, assign its value over \arg{i}.  On
32-bit machines, this is the same as PL_get_long(), but avoids a
warning from the compiler.  See also PL_get_long().

\cfunction{int}{PL_get_long}{term_t +t, long *i}
If \arg{t} is a Prolog integer that can be represented as a long, assign
its value over \arg{i}. If \arg{t} is an integer that cannot be
represented by a C long, this function returns \const{FALSE}. If \arg{t}
is a floating point number that can be represented as a long, this
function succeeds as well.  See also PL_get_int64()

\cfunction{int}{PL_get_int64}{term_t +t, int64_t *i}
If \arg{t} is a Prolog integer or float that can be represented as a
\ctype{int64_t}, assign its value over \arg{i}.  Currently all Prolog
integers can be represented using this type, but this might change if
SWI-Prolog introduces unbounded integers.

\cfunction{int}{PL_get_intptr}{term_t +t, intptr_t *i}
Get an integer that is at least as wide a as a pointer. On most
platforms this is the same as PL_get_long(), but on Win64 pointers are 8
bytes and longs only 4. Unlike PL_get_pointer(), the value is not
modified.

\cfunction{int}{PL_get_bool}{term_t +t, int *val}
If \arg{t} has the value \const{true} or \const{false}, set \arg{val}
to the C constant \const{TRUE} or \const{FALSE} and return success.
otherwise return failure.
\cfunction{int}{PL_get_pointer}{term_t +t, void **ptr}
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.  PL_put_pointer()/PL_get_pointer()
guarantees pointers in the range of malloc() are handled without
truncating.
\cfunction{int}{PL_get_float}{term_t +t, double *f}
If \arg{t} is a float or integer, its value is assigned over \arg{f}.
\cfunction{int}{PL_get_functor}{term_t +t, functor_t *f}
If \arg{t} is compound or an atom, the Prolog representation of the
name-arity pair will be assigned over \arg{f}. See also
PL_get_name_arity() and PL_is_functor().
\cfunction{int}{PL_get_name_arity}{term_t +t, atom_t *name, int *arity}
If \arg{t} is compound or an atom, the functor-name will be assigned
over \arg{name} and the arity over \arg{arity}. See also
PL_get_functor() and PL_is_functor().
\cfunction{int}{PL_get_module}{term_t +t, module_t *module}
If \arg{t} is an atom, the system will lookup or create the
corresponding module and assign an opaque pointer to it over {\em
module},.
\cfunction{int}{PL_get_arg}{int index, term_t +t, term_t -a}
If \arg{t} is compound and index is between 1 and arity (including),
assign \arg{a} with a term-reference to the argument.
\cfunction{int}{_PL_get_arg}{int index, term_t +t, term_t -a}
Same as PL_get_arg(), but no checking is performed, nor whether \arg{t}
is actually a term, nor whether \arg{index} is a valid argument-index.
\end{description}


\subsubsection{Exchanging text using length and string}

All internal text-representation of SWI-Prolog is represented using
\type{char *} plus length and allow for \jargon{0-bytes} 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.

\begin{description}
    \cfunction{int}{PL_get_atom_nchars}{term_t t, size_t *len, char **s}
See PL_get_atom_chars().
    \cfunction{int}{PL_get_list_nchars}{term_t t, size_t *len, char **s}
See PL_get_list_chars().
    \cfunction{int}{PL_get_nchars}{term_t t, size_t *len, char **s,
				   unsigned int flags}
See PL_get_chars().
    \cfunction{int}{PL_put_atom_nchars}{term_t t, size_t len, const char *s}
See PL_put_atom_chars().
    \cfunction{int}{PL_put_string_nchars}{term_t t, size_t len, const char *s}
See PL_put_string_chars().
    \cfunction{int}{PL_put_list_ncodes}{term_t t, size_t len, const char *s}
See PL_put_list_codes().
    \cfunction{int}{PL_put_list_nchars}{term_t t, size_t len, const char *s}
See PL_put_list_chars().
    \cfunction{int}{PL_unify_atom_nchars}{term_t t, size_t len, const char *s}
See PL_unify_atom_chars().
    \cfunction{int}{PL_unify_string_nchars}{term_t t, size_t len, const char *s}
See PL_unify_string_chars().
    \cfunction{int}{PL_unify_list_ncodes}{term_t t, size_t len, const char *s}
See PL_unify_codes().
    \cfunction{int}{PL_unify_list_nchars}{term_t t, size_t len, const char *s}
See PL_unify_list_chars().
\end{description}

In addition, the following functions are available for creating and
inspecting atoms:

\begin{description}
    \cfunction{atom_t}{PL_new_atom_nchars}{size_t len, const char *s}
Create a new atom as PL_new_atom(), but from length and characters.
    \cfunction{const char *}{PL_atom_nchars}{atom_t a, size_t *len}
Extract text and length of an atom.
\end{description}


\subsubsection{Wide character versions}

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 \ctype{pl_wchar_t}, which is guaranteed to
be the same as \ctype{wchar_t} 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.

\begin{description}
    \cfunction{atom_t}{PL_new_atom_wchars}{size_t len, const pl_wchar_t *s}
Create atom from wide-character string as PL_new_atom_nchars() does for
ISO-Latin-1 strings. If \arg{s} only contains ISO-Latin-1 characters a
normal byte-array atom is created.

    \cfunction{pl_wchar_t*}{PL_atom_wchars}{atom_t atom, int *len}
Extract characters from a wide-character atom. Fails (returns
\const{NULL}) if \arg{atom} is not a wide-character atom.  This is
the wide-character version of PL_atom_nchars().  Note that only one
of these functions succeeds on a particular atom.  Especially, after
creating an atom with PL_new_atom_wchars(), extracting the text using
PL_atom_wchars() will fail if the atom only contains ISO-Latin-1
characters.

    \cfunction{int}{PL_get_wchars}{term_t t, size_t *len,
				   pl_wchar_t **s, unsigned flags}
Wide-character version of PL_get_chars().  The \arg{flags} argument
is the same as for PL_get_chars().

    \cfunction{int}{PL_unify_wchars}{term_t t, int type,
				     size_t len,
				     const pl_wchar_t *s}
Unify \arg{t} with a textual representation of the C wide character
array \arg{s}.  The \arg{arg}{type} argument defines the Prolog
representation and is one of \const{PL_ATOM}, \const{PL_STRING},
\const{PL_CODE_LIST} or \const{PL_CHAR_LIST}.
    \cfunction{int}{PL_unify_wchars_diff}{term_t +t, term_t -tail, int type,
					  size_t len,
					  const pl_wchar_t *s}
Difference list version of PL_unify_wchars(), only supporting the
types \const{PL_CODE_LIST} and \const{PL_CHAR_LIST}.  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 \file{packages/clib/readutil.c} from the
source distribution.
\end{description}


\subsubsection{Reading a list}

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:

\begin{code}
foreign_t
pl_write_atoms(term_t l)
{ term_t head = PL_new_term_ref();      /* variable for the elements */
  term_t list = PL_copy_term_ref(l);    /* copy as we need to write */

  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 [] */
}
\end{code}


\begin{description}
\cfunction{int}{PL_get_list}{term_t +l, term_t -h, term_t -t}
If \arg{l} is a list and not \const{[]} assign a term-reference to the
head to \arg{h} and to the tail to \arg{t}.
\cfunction{int}{PL_get_head}{term_t +l, term_t -h}
If \arg{l} is a list and not \const{[]} assign a term-reference to the
head to \arg{h}.
\cfunction{int}{PL_get_tail}{term_t +l, term_t -t}
If \arg{l} is a list and not \const{[]} assign a term-reference to the
tail to \arg{t}.
\cfunction{int}{PL_get_nil}{term_t +l}
Succeeds if {\em} represents the atom \const{[]}.

\cfunction{int}{PL_skip_list}{term_t +list, term_t -tail, size_t *len}
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 \arg{tail} is set to point to the end of the list,
\arg{len} is filled with the number of list-cells skipped and the
return-value indicates the status of the list:

    \begin{description}
	\constitem{PL_LIST}
    The list is a `proper' list: one that ends in \const{[]} and
    \arg{tail} is filled with \const{[]}

	\constitem{PL_PARTIAL_LIST}
    The list is `partial' list: one that ends in a variable and
    \arg{tail} is a reference to this variable.

	\constitem{PL_CYCLIC_TERM}
    The list is cyclic (e.g. X = [a|X]).  \arg{tail} points to
    an arbitrary cell of the list and \arg{len} is at most twice
    the cycle-length of the list.

	\constitem{PL_NOT_A_LIST}
    The term \arg{list} is not a list at all.  \arg{tail} is
    bound to the non-list term and \arg{len} is set to the number
    of list-cells skipped.
    \end{description}

It is allowed to pass 0 for \arg{tail} and \const{NULL} for \arg{len}.
\end{description}


\subsubsection{An example: defining write/1 in C}

\Figref{pl-display} shows a simplified definition of write/1 to
illustrate the described functions.  This simplified version does not
deal with operators.  It is called display/1, because it mimics closely
the behaviour of this Edinburgh predicate.

\begin{figure}
\begin{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;
}
\end{code}

    \caption{A Foreign definition of display/1}
    \label{fig:pl-display}
\end{figure}


\subsection{Constructing Terms}

Terms can be constructed using functions from the {\tt PL_put_*()} and
{\tt PL_cons_*()} 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 PL_call() and
PL_open_query.

\begin{description}
\cfunction{void}{PL_put_variable}{term_t -t}
Put a fresh variable in the term, resetting the term-reference to its
initial state.\footnote{Older versions created a variable on the global
stack.}
\cfunction{void}{PL_put_atom}{term_t -t, atom_t a}
Put an atom in the term reference from a handle.  See also
PL_new_atom() and PL_atom_chars().
\cfunction{int}{PL_put_atom_chars}{term_t -t, const char *chars}
Put an atom in the term-reference constructed from the 0-terminated
string.  The string itself will never be referenced by Prolog after this
function.
\cfunction{int}{PL_put_string_chars}{term_t -t, const char *chars}
Put a zero-terminated string in the term-reference. The data will be
copied.  See also PL_put_string_nchars().
\cfunction{int}{PL_put_string_nchars}{term_t -t,
				       size_t len,
				       const char *chars}

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 \secref{foreigndata}.
\cfunction{int}{PL_put_list_chars}{term_t -t, const char *chars}
Put a list of ASCII values in the term-reference.
\cfunction{int}{PL_put_integer}{term_t -t, long i}
Put a Prolog integer in the term reference.
\cfunction{int}{PL_put_int64}{term_t -t, int64_t i}
Put a Prolog integer in the term reference.
\cfunction{int}{PL_put_pointer}{term_t -t, void *ptr}
Put a Prolog integer in the term-reference.  Provided ptr is in the
`malloc()-area', PL_get_pointer() will get the pointer back.
\cfunction{int}{PL_put_float}{term_t -t, double f}
Put a floating-point value in the term-reference.
\cfunction{int}{PL_put_functor}{term_t -t, functor_t functor}
Create a new compound term from \arg{functor} and bind \arg{t} to
this term. All arguments of the term will be variables. To create
a term with instantiated arguments, either instantiate the arguments
using the {\tt PL_unify_*()} functions or use PL_cons_functor().
\cfunction{int}{PL_put_list}{term_t -l}
Same as \exam{PL_put_functor(l, PL_new_functor(PL_new_atom("."), 2))}.
\cfunction{void}{PL_put_nil}{term_t -l}
Same as \exam{PL_put_atom_chars("[]")}.
\cfunction{void}{PL_put_term}{term_t -t1, term_t +t2}
Make \arg{t1} point to the same term as \arg{t2}.
\cfunction{int}{PL_cons_functor}{term_t -h, functor_t f, \ldots}
Create a term, whose arguments are filled from variable argument list
holding the same number of term_t objects as the arity of the functor.
To create the term \exam{animal(gnu, 50)}, use:

\begin{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);
}
\end{code}


After this sequence, the term-references \arg{a1} and \arg{a2} may
be used for other purposes.
\cfunction{int}{PL_cons_functor_v}{term_t -h, functor_t f, term_t a0}
Creates a compound term like PL_cons_functor(), but \arg{a0} is an
array of term references as returned by PL_new_term_refs().  The length
of this array should match the number of arguments required by the
functor.
\cfunction{int}{PL_cons_list}{term_t -l, term_t +h, term_t +t}
Create a list (cons-) cell in \arg{l} from the head and tail.  The
code below creates a list of atoms from a \ctype{char **}.  The list
is built tail-to-head.  The {\tt PL_unify_*()} functions can be used
to build a list head-to-tail.

\begin{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);
  }
}
\end{code}
Note that \arg{l} can be redefined within a {\tt PL_cons_list} call as
shown here because operationally its old value is consumed before its
new value is set.
\end{description}


\subsection{Unifying data}

The functions of this sections \jargon{unify} terms with other terms or
translated C-data structures. Except for PL_unify(), the functions of
this section are specific to SWI-Prolog. They have been introduced to
make translation of old code easier, but also because they provide for
a faster mechanism for returning data to Prolog that requires less
term-references.  Consider the case where we want a foreign function
to return the host name of the machine Prolog is running on.  Using
the {\tt PL_get_*()} and {\tt PL_put_*()} functions, the code becomes:

\begin{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;
}
\end{code}

Using PL_unify_atom_chars(), this becomes:

\begin{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;
}
\end{code}


\begin{description}
    \cfunction{int}{PL_unify}{term_t ?t1, term_t ?t2}
Unify two Prolog terms and return non-zero on success.

    \cfunction{int}{PL_unify_atom}{term_t ?t, atom_t a}
Unify \arg{t} with the atom \arg{a} and return non-zero on success.

    \cfunction{int}{PL_unify_bool}{term_t ?t, int a}
Unify \arg{t} with either \const{true} or \const{false}.

    \cfunction{int}{PL_unify_chars}{term_t ?t, int flags,
				    size_t len,
				    const char *chars}
New function to deal with unification of \ctype{char*} with various
encodings to a Prolog representation. The \arg{flags} argument is a
bitwise \emph{or} specifying the Prolog target type and the encoding of
\arg{chars}. Prolog types is one of \const{PL_ATOM}, \const{PL_STRING},
\const{PL_CODE_LIST} or \const{PL_CHAR_LIST}. Representations is one of
\const{REP_ISO_LATIN_1}, \const{REP_UTF8} or \const{REP_MB}. See
PL_get_chars() for a definition of the representation types. If
\arg{len} is \const{-1} \arg{chars} must be 0-terminated and the length
is computed from \arg{chars} using strlen().

If \arg{flags} includes \const{PL_DIFF_LIST} and type is one of
\const{PL_CODE_LIST} or \const{PL_CHAR_LIST}, the text is converted
to a \jargon{difference list}.  The tail of the difference list is
$t+1$.

    \cfunction{int}{PL_unify_atom_chars}{term_t ?t, const char *chars}
Unify \arg{t} with an atom created from \arg{chars}  and return non-zero
on success.

    \cfunction{int}{PL_unify_list_chars}{term_t ?t, const char *chars}
Unify \arg{t} with a list of ASCII characters constructed from
\arg{chars}.

    \cfunction{void}{PL_unify_string_chars}{term_t ?t, const char *chars}
Unify \arg{t} with a Prolog string object created from the
zero-terminated string \arg{chars}. The data will be copied.
See also PL_unify_string_nchars().
    \cfunction{void}{PL_unify_string_nchars}{term_t ?t,
					     size_t len,
					     const char *chars}
Unify \arg{t} with a Prolog string object created from the string
created from the \arg{len}/\arg{chars} pair. The data will be copied.
This interface can deal with 0-bytes in the string. See also
\secref{foreigndata}.

    \cfunction{int}{PL_unify_integer}{term_t ?t, long n}
Unify \arg{t} with a Prolog integer from \arg{n}.
    \cfunction{int}{PL_unify_int64}{term_t ?t, int64_t n}
Unify \arg{t} with a Prolog integer from \arg{n}.
    \cfunction{int}{PL_unify_float}{term_t ?t, double f}
Unify \arg{t} with a Prolog float from \arg{f}.
    \cfunction{int}{PL_unify_pointer}{term_t ?t, void *ptr}
Unify \arg{t} with a Prolog integer describing the pointer. See also
PL_put_pointer() and PL_get_pointer().
    \cfunction{int}{PL_unify_functor}{term_t ?t, functor_t f}
If \arg{t} is a compound term with the given functor, just succeed.
If it is unbound, create a term and bind the variable, else fails.
Note that this function does not create a term if the argument is
already instantiated.
    \cfunction{int}{PL_unify_list}{term_t ?l, term_t -h, term_t -t}
Unify \arg{l} with a list-cell ({\tt ./2}). If successful, write a
reference to the head of the list to \arg{h} and a reference
to the tail of the list into \arg{t}. This reference may be used for
subsequent calls to this function. Suppose we want to return a list of
atoms from a \ctype{char **}. We could use the example described by
PL_put_list(), followed by a call to PL_unify(), or we can use the code
below. If the predicate argument is unbound, the difference is minimal
(the code based on PL_put_list() 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.

\begin{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);
}
\end{code}
\cfunction{int}{PL_unify_nil}{term_t ?l}
Unify \arg{l} with the atom \const{[]}.
\cfunction{int}{PL_unify_arg}{int index, term_t ?t, term_t ?a}
Unifies the {\em index-th} argument (1-based) of \arg{t} with
\arg{a}.
\cfunction{int}{PL_unify_term}{term_t ?t, \ldots}
Unify \arg{t} with a (normally) compound term.  The remaining arguments
is 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.

Special attention is required when passing numbers. C `promotes' any
integral smaller than \type{int} to \type{int}. I.e.\ the types
\type{char}, \type{short} and \type{int} are all passed as \type{int}.
In addition, on most 32-bit platforms \type{int} and \type{long} are the
same. Up-to version 4.0.5, only \const{PL_INTEGER} could be specified
which was taken from the stack as \type{long}. Such code fails when
passing small integral types on machines where \type{int} is smaller
than \type{long}. It is advised to use \const{PL_SHORT}, \const{PL_INT}
or \const{PL_LONG} as appropriate. Similar, C compilers promote
\type{float} to \type{double} and therefore \const{PL_FLOAT} and
\const{PL_DOUBLE} are synonyms.

The type identifiers are:

\begin{description}
   \definition{\const{PL_VARIABLE} \arg{none}}
No op.  Used in arguments of \const{PL_FUNCTOR}.
   \definition{\const{PL_BOOL} \arg{int}}
Unify the argument with \const{true} or \const{false}.
   \definition{\const{PL_ATOM} \arg{atom_t}}
Unify the argument with an atom, as in PL_unify_atom().
   \definition{\const{PL_CHARS} \arg{const char *}}
Unify the argument with an atom, constructed from the C \ctype{char *},
as in PL_unify_atom_chars().
   \definition{\const{PL_NCHARS} \arg{size_t, const char *}}
Unify the argument with an atom, constructed from length and
\ctype{char*} as in PL_unify_atom_nchars().
   \definition{\const{PL_UTF8_CHARS} \arg{const char *}}
Create an atom from a UTF-8 string.
   \definition{\const{PL_UTF8_STRING} \arg{const char *}}
Create a packed string object from a UTF-8 string.
   \definition{\const{PL_MBCHARS} \arg{const char *}}
Create an atom from a multi-byte string in the current locale.
   \definition{\const{PL_MBCODES} \arg{const char *}}
Create a list of character codes from a multi-byte string in the current
locale.
   \definition{\const{PL_MBSTRING} \arg{const char *}}
Create a packed string object from a multi-byte string in the
current locale.
   \definition{\const{PL_NWCHARS} \arg{size_t, const wchar_t *}}
Create an atom from a length and a wide character pointer.
   \definition{\const{PL_NWCODES} \arg{size_t, const wchar_t *}}
Create an list of character codes from a length and a wide character pointer.
   \definition{\const{PL_NWSTRING} \arg{size_t, const wchar_t *}}
Create a packed string object from a length and a wide character pointer.
   \definition{\const{PL_SHORT} \arg{short}}
Unify the argument with an integer, as in PL_unify_integer(). As
\type{short} is promoted to \type{int}, \const{PL_SHORT} is a
synonym for \type{PL_INT}.
   \definition{\const{PL_INTEGER} \arg{long}}
Unify the argument with an integer, as in PL_unify_integer().
   \definition{\const{PL_INT} \arg{int}}
Unify the argument with an integer, as in PL_unify_integer().
   \definition{\const{PL_LONG} \arg{long}}
Unify the argument with an integer, as in PL_unify_integer().
   \definition{\const{PL_INT64} \arg{int64_t}}
Unify the argument with a 64-bit integer, as in PL_unify_int64().
   \definition{\const{PL_INTPTR} \arg{intptr_t}}
Unify the argument with an integer with the same width as a pointer.
On most machines this is the same as \const{PL_LONG}. but on 64-bit
MS-Windows pointers are 64-bit while longs are only 32-bits.
   \definition{\const{PL_DOUBLE} \arg{double}}
Unify the argument with a float, as in PL_unify_float(). Note that,
as the argument is passed using the C vararg conventions, a float must
be casted to a double explicitly.
   \definition{\const{PL_FLOAT} \arg{double}}
Unify the argument with a float, as in PL_unify_float().
   \definition{\const{PL_POINTER} \arg{void *}}
Unify the argument with a pointer, as in PL_unify_pointer().
   \definition{\const{PL_STRING} \arg{const char *}}
Unify the argument with a string object, as in PL_unify_string_chars().
   \definition{\const{PL_TERM} \arg{term_t}}
Unify a subterm.  Note this may the return value of a PL_new_term_ref()
call to get access to a variable.
   \definition{\const{PL_FUNCTOR} \arg{functor_t, \ldots}}
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.
   \definition{\const{PL_FUNCTOR_CHARS}
	       \arg{const char *name, int arity, \ldots}}
Create a functor from the given name and arity and then behave as
\const{PL_FUNCTOR}.
   \definition{\const{PL_LIST} \arg{int length, \ldots}}
Create a list of the indicated length.  The following arguments contain
the elements of the list.
\end{description}

For example, to unify an argument with the term \exam{language(dutch)},
the following skeleton may be used:


\begin{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();
}
\end{code}

\cfunction{int}{PL_chars_to_term}{const char *chars, term_t -t}
Parse the string \arg{chars} and put the resulting Prolog term into
\arg{t}. \arg{chars} may or may not be closed using a Prolog full-stop
(i.e., a dot followed by a blank). Returns \const{FALSE} if a syntax
error was encountered and \const{TRUE} after successful completion.
In addition to returning \const{FALSE}, the exception-term is
returned in \arg{t} on a syntax error.
See also term_to_atom/2.

The following example build a goal-term from a string and calls it.

\begin{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)");
  ...
\end{code}

\cfunction{char *}{PL_quote}{int chr, const char *string}
    Return a quoted version of \arg{string}.  If \arg{chr} is
    \verb$'\''$, the result is a quoted atom.  If \arg{chr} is
    \verb$'"'$, the result is a string.  The result string is stored
    in the same ring of buffers as described with the \const{BUF_RING}
    argument of PL_get_chars();

    In the current implementation, the string is surrounded by
    \arg{chr} and any occurrence of \arg{chr} is doubled.  In the
    future the behaviour will depend on the
    \prologflag{character_escapes} Prolog flag.
\end{description}


\subsection{BLOBS: Using atoms to store arbitrary binary data}
\label{sec:blob}

\index{Java}\index{COM}
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.

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
\funcref{compare}{} function.  Rank numbers are assigned when the
type is registered.


\subsubsection{Defining a BLOB type}
\label{sec:blobtype}

The type \ctype{PL_blob_t} represents a structure with the layout
displayed above. The structure contains additional fields at the
\ldots for internal bookkeeping as well as future extension.

\begin{code}
typedef struct PL_blob_t
{ unsigned long		magic;		/* PL_BLOB_MAGIC */
  unsigned long		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;
\end{code}

For each type exactly one such structure should be allocated.  Its
first field must be initialised to \const{PL_BLOB_MAGIC}.  The
\arg{flags} is a bitwise or of the following constants:

\begin{description}
    \constitem{PL_BLOB_TEXT}
If specified the blob is assumed to contain text and is considered
a normal Prolog atom.

    \constitem{PL_BLOB_UNIQUE}
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.

    \constitem{PL_BLOB_NOCOPY}
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 \const{PL_BLOB_UNIQUE}
is also specified uniqueness is determined by comparing the pointer
rather than the data pointed at.
\end{description}

The \arg{name} field represents the type name as available to Prolog.
See also current_blob/2. The other field are function pointers that must
be initialised to proper functions or \const{NULL} to get the default
behaviour of built-in atoms. Below are the defined member functions:

\begin{description}
    \cfunction{void}{acquire}{atom_t a}
Called if a new blob of this type is created through PL_put_blob()
or PL_unify_blob().  This callback may be used together with the
release hook to deal with reference counted external objects.

    \cfunction{int}{release}{atom_t a}
The blob (atom) \arg{a} is about to be released.  This function
can retrieve the data of the blob using PL_blob_data().  If it
returns \const{FALSE} the atom garbage collector will \emph{not}
reclaim the atom.

    \cfunction{int}{compare}{atom_t a, atom_t b}
Compare the blobs \arg{a} and \arg{b}, both of which are of the
type associated to this blob-type.  Return values are, as memcmp(),
$< 0$ if \arg{a} is less then \arg{b}, $= 0$ if both are equal and
$> 0$ otherwise.

    \cfunction{int}{write}{IOSTREAM *s, atom_t a, int flags}
Write the content of the blob \arg{a} to the stream \arg{s}
and respecting the \arg{flags}.  The \arg{flags} are a bitwise
or of zero or more of the \const{PL_WRT_*} flags defined in
\file{SWI-Prolog.h}. This prototype is available if the
undocumented \file{SWI-Stream.h} is included \emph{before}
\file{SWI-Prolog.h}.

If this function is not provided, write/1 emits the content
of the blob for blobs of type \const{PL_BLOB_TEXT} or a
string of the format \verb$<#$\textit{hex data}\verb$>$
for binary blobs.
\end{description}


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.

\begin{description}
    \cfunction{int}{PL_unregister_blob_type}{PL_blob_t *type}
Unlink the blob type from the registered type and transform the type of
possible living blobs to \const{unregistered}, avoiding further
reference to the type structure, functions referred by it as well as the
data. This function returns \const{TRUE} if no blobs of this type
existed and \const{FALSE} otherwise. PL_unregister_blob_type() is
intended for the uninstall() hook of foreign modules, avoiding further
references to the module.
\end{description}


\subsubsection{Accessing blobs}
\label{sec:blobaccess}

The blob access functions are similar to the atom accessing functions.
Blobs being atoms, the atom functions operate on blobs and visa versa.
For clarity and possible future compatibility issues however it is not
advised to rely on this.

\begin{description}
    \cfunction{int}{PL_is_blob}{term_t t, PL_blob_t **type}
Succeeds if \arg{t} refers to a blob, in which case \arg{type} is
filled with the type of the blob.

    \cfunction{int}{PL_unify_blob}{term_t t, void *blob, size_t len,
				   PL_blob_t *type}
Unify \arg{t} to a new blob constructed from the given data and
associated to the given type.  See also PL_unify_atom_nchars().

    \cfunction{int}{PL_put_blob}{term_t t, void *blob, size_t len,
				 PL_blob_t *type}
Store the described blob in \arg{t}.  The return value indicates whether
a new blob was allocated (\const{FALSE}) or the blob is a reference to
an existing blob (\const{TRUE}).  Reporting new/existing can be used to
deal with external objects having their own reference counts.  If the
return is \const{TRUE} this reference count must be incremented and it
must be decremented on blob destruction callback.  See also
PL_put_atom_nchars().

    \cfunction{int}{PL_get_blob}{term_t t, void **blob, size_t *len,
				 PL_blob_t **type}
If \arg{t} holds a blob or atom get the data and type and return
\const{TRUE}.  Otherwise return \const{FALSE}.  Each result pointer
may be \const{NULL}, in which case the requested information is
ignored.

    \cfunction{void *}{PL_blob_data}{atom_t a,
				     size_t *len,
				     PL_blob_t **type}
Get the data and type associated to a blob.  This function is mainly
used from the callback functions described in \secref{blobtype}.
\end{description}


\subsection{Exchanging GMP numbers}
\label{sec:gmpforeign}

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 \verb$<gmp.h>$ must be included \emph{before}
\verb$<SWI-Prolog.h>$. Foreign code using GMP linked to SWI-Prolog asks
for some considerations.

\begin{itemize}
    \item 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
    \verb$PL_action(PL_GMP_SET_ALLOC_FUNCTIONS, TRUE)$ 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 \verb$PL_action(PL_GMP_SET_ALLOC_FUNCTIONS, FALSE)$
    \emph{before} initializing Prolog.

    \item 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.
\end{itemize}

Here is an example exploiting the function mpz_nextprime():

\begin{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);
}
\end{code}

\begin{description}
    \cfunction{int}{PL_get_mpz}{term_t t, mpz_t mpz}
If \arg{t} represents an integer \arg{mpz} is filled with the value and
the function returns \const{TRUE}. Otherwise \arg{mpz} is untouched and
the function returns \const{FALSE}.  Note that \arg{mpz} must have been
initialised before calling this function and must be cleared using
mpz_clear() to reclaim any storage associated with it.

    \cfunction{int}{PL_get_mpq}{term_t t, mpq_t mpq}
If \arg{t} is an integer or rational number (term \functor{rdiv}{2})
\arg{mpq} is filled with the \emph{normalise} rational number and the
function returns \const{TRUE}.  Otherwise \arg{mpq} is untouched and
the function returns \const{FALSE}.  Note that \arg{mpq} must have been
initialised before calling this function and must be cleared using
mpq_clear() to reclaim any storage associated with it.

    \cfunction{int}{PL_unify_mpz}{term_t t, mpz_t mpz}
Unify \arg{t} with the integer value represented by \arg{mpz} and return
\arg{TRUE} on success.  The \arg{mpz} argument is not changed.

    \cfunction{int}{PL_unify_mpq}{term_t t, mpq_t mpq}
Unify \arg{t} with a rational number represented by \arg{mpq} and return
\arg{TRUE} on success.  Note that \arg{t} is unified with an integer if
the denominator is 1.  The \arg{mpq} argument is not changed.
\end{description}


\subsection{Calling Prolog from C}

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 call/1 and next PL_call() 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
PL_open_query(), PL_next_solution() and PL_cut_query() or
PL_close_query(). This mechanism is more powerful, but also more
complicated to use.


\subsubsection{Predicate references}

This section discusses the functions used to communicate about
predicates. Though a Prolog predicate may defined or not, redefined,
etc., a Prolog predicate has a handle that is not destroyed, nor moved.
This handle is known by the type \ctype{predicate_t}.

\begin{description}
    \cfunction{predicate_t}{PL_pred}{functor_t f, module_t m}
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
\arg{m} is \const{NULL}, the current context module is used.

    \cfunction{predicate_t}{PL_predicate}{const char *name, int arity,
					  const char* module}
Same a PL_pred(), but provides a more convenient interface to
the C-programmer.

    \cfunction{void}{PL_predicate_info}{predicate_t p, atom_t *n,
					int *a, module_t *m}
Return information on the predicate \arg{p}.  The name is stored
over \arg{n}, the arity over \arg{a}, while \arg{m} receives the
definition module.  Note that the latter need not be the same as
specified with PL_predicate().  If the predicate is imported into
the module given to PL_predicate(), this function will return the
module where the predicate is defined.
\end{description}


\subsubsection{Initiating a query from C}

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 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} allowed to open multiple queries and start
generating solutions for each of them by calling PL_next_solution().
Be sure to call PL_cut_query() or PL_close_query() on any query you
opened before opening the next or returning control back to Prolog.


\begin{description}
\cfunction{qid_t}{PL_open_query}{module_t ctx, int flags,
				 predicate_t p, term_t +t0}

Opens a query and returns an identifier for it. \arg{ctx} is the {\em
context module} of the goal. When \const{NULL}, the context module of
the calling context will be used, or \const{user} if there is no calling
context (as may happen in embedded systems). Note that the context
module only matters for \jargon{meta-predicates}. See meta_predicate/1,
context_module/1 and module_transparent/1. The \arg{p} argument
specifies the predicate, and should be the result of a call to PL_pred()
or PL_predicate(). Note that it is allowed to store this handle as
global data and reuse it for future queries. The term-reference \arg{t0}
is the first of a vector of term-references as returned by
PL_new_term_refs(n).

The \arg{flags} arguments provides some additional options concerning
debugging and exception handling.  It is a bitwise or of the following
values:

\begin{description}
    \definition{\const{PL_Q_NORMAL}}
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.%
	\footnote{Do not pass the integer 0 for normal operation, as
		  this is interpreted as \const{PL_Q_NODEBUG} for
		  backward compatibility reasons.}
    \definition{\const{PL_Q_NODEBUG}}
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 print/1 calling portray/1 from foreign code.
    \definition{\const{PL_Q_CATCH_EXCEPTION}}
If an exception is raised while executing the goal, do not report it, but
make it available for PL_exception().
    \definition{\const{PL_Q_PASS_EXCEPTION}}
As \const{PL_Q_CATCH_EXCEPTION}, but do not invalidate the exception-term
while calling PL_close_query().  This option is experimental.
\end{description}

PL_open_query() can return a 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 PL_next_solution() will return an existence_error. See
PL_exception().

The example below opens a query to the predicate {is_a}/2 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.

\begin{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);
  ...
}
\end{code}

\cfunction{int}{PL_next_solution}{qid_t qid}
Generate the first (next) solution for the given query.  The return
value is \const{TRUE} if a solution was found, or \const{FALSE} to indicate
the query could not be proven.  This function may be called repeatedly
until it fails to generate all solutions to the query.
\cfunction{void}{PL_cut_query}{qid}
Discards the query, but does not delete any of the data created by the
query.  It just invalidate \arg{qid}, allowing for a new call to
PL_open_query() in this context.
    \cfunction{void}{PL_close_query}{qid}
As PL_cut_query(), but all data and bindings created by the query are
destroyed.
    \cfunction{int}{PL_call_predicate}{module_t m, int flags,
				       predicate_t pred, term_t +t0}
Shorthand for PL_open_query(), PL_next_solution(), PL_cut_query(),
generating a single solution.  The arguments are the same as for
PL_open_query(), the return value is the same as PL_next_solution().
    \cfunction{int}{PL_call}{term_t, module_t}
Call term just like the Prolog predicate once/1. \arg{Term} is called
in the specified module, or in the context module if module_t = NULL.
Returns \const{TRUE} if the call succeeds, \const{FALSE} otherwise.
\Figref{calling} shows an example to obtain the number of
defined atoms. All checks are omitted to improve readability.
\end{description}

\subsection{Discarding Data}

The Prolog data created and term-references needed to setup the call
and/or analyse the result can in most cases be discarded right after the
call. PL_close_query() allows for destructing the data, while leaving
the term-references. The calls below may be used to destroy
term-references and data. See \figref{calling} for an example.

\begin{description}
\cfunction{fid_t}{PL_open_foreign_frame}{}
Created 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.
\cfunction{void}{PL_close_foreign_frame}{fid_t id}
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.
\cfunction{void}{PL_discard_foreign_frame}{fid_t id}
Same as PL_close_foreign_frame(), but also undo all bindings made since
the open and destroy all Prolog data.
\cfunction{void}{PL_rewind_foreign_frame}{fid_t id}
Undo all bindings and discard all term-references created since the
frame was created, but does not pop the frame.  I.e.\ the same frame
can be rewinded multiple times, and must eventually be closed or
discarded.
\end{description}

It is obligatory to call either of the two closing functions to discard
a foreign frame.  Foreign frames may be nested.


\begin{figure}

\begin{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;
}
\end{code}

     \caption{Calling Prolog}
     \label{fig:calling}
\end{figure}


\subsection{Foreign Code and Modules}

Modules are identified via a unique handle.  The following functions
are available to query and manipulate modules.

\begin{description}
\cfunction{module_t}{PL_context}{}
Return the module identifier of the context module of the currently
active foreign predicate.
\cfunction{int}{PL_strip_module}{term_t +raw, module_t *m, term_t -plain}
Utility function. If \arg{raw} is a term, possibly holding the module
construct \mbox{<module>{\tt :}<rest>} this function will make
\arg{plain} a reference to <rest> and fill \arg{module *} with <module>.
For further nested module constructs the inner most module is returned
via \arg{module *}. If \arg{raw} is not a module construct \arg{arg}
will simply be put in \arg{plain}. If \arg{module *} is \const{NULL} it
will be set to the context module. Otherwise it will be left untouched.
The following example shows how to obtain the plain term and module if
the default module is the user module:


\begin{code}
{ module m = PL_new_module(PL_new_atom("user"));
  term_t plain = PL_new_term_ref();

  PL_strip_module(term, &m, plain);
  ...
}
\end{code}


\cfunction{atom_t}{PL_module_name}{module_t}
Return the name of \arg{module} as an atom.
\cfunction{module_t}{PL_new_module}{atom_t name}
Find an existing or create a new module with name specified by the atom
\arg{name}.
\end{description}


\subsection{Prolog exceptions in foreign code}

This section discusses PL_exception(), PL_throw() and
PL_raise_exception(), the interface functions to detect and generate
Prolog exceptions from C-code. PL_throw() and PL_raise_exception() from
the C-interface to raise an exception from foreign code. PL_throw()
exploits the C-function longjmp() to return immediately to the innermost
PL_next_solution(). PL_raise_exception() registers the exception term
and returns \const{FALSE}. If a foreign predicate returns FALSE, while
and exception-term is registered a Prolog exception will be raised by
the virtual machine.

Calling these functions outside the context of a function implementing a
foreign predicate results in undefined behaviour.

PL_exception() may be used after a call to PL_next_solution() fails,
and returns a term reference to an exception term if an exception
was raised, and 0 otherwise.

If a C-function, implementing a predicate calls Prolog and detects
an exception using PL_exception(), it can handle this exception, or
return with the exception.  Some caution is required though.  It is
\strong{not} allowed to call PL_close_query() or
PL_discard_foreign_frame() afterwards, as this will invalidate the
exception term.  Below is the code that calls a Prolog defined
arithmetic function (see arithmetic_function/1).

If PL_next_solution() succeeds, the result is analysed and translated to
a number, after which the query is closed and all Prolog data created
after PL_open_foreign_frame() is destroyed. On the other hand, if
PL_next_solution() fails and if an exception was raised, just pass it.
Otherwise generate an exception (PL_error() is an internal call for
building the standard error terms and calling PL_raise_exception()).
After this, the Prolog environment should be discarded using
PL_cut_query() and PL_close_foreign_frame() to avoid invalidating the
exception term.

\begin{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;
}
\end{code}


\begin{description}
    \cfunction{int}{PL_raise_exception}{term_t exception}
Generate an exception (as throw/1) and return \const{FALSE}.  Below is
an example returning an exception from foreign predicate:

\begin{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);
  }
}
\end{code}
    \cfunction{int}{PL_throw}{term_t exception}
Similar to PL_raise_exception(), but returns using the C longjmp()
function to the innermost PL_next_solution().

    \cfunction{term_t}{PL_exception}{qid_t qid}
If PL_next_solution() fails, this can be due to normal failure of the
Prolog call, or because an exception was raised using throw/1.  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,
PL_exception() allocates a term-handle using PL_new_term_ref() that is
used to return the exception term.%
    \footnote{This interface differs in two ways from Quintus.  The
	      calling predicates simply signal failure if an exception
	      was raised, and a term referenced is returned, rather
	      passed and filled with the error term.   Exceptions
	      can only be handled using the PL_next_solution() interface,
	      as a handle to the query is required.}

Additionally, \verb$PL_exception(0)$ 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.
\end{description}


\subsection{Catching Signals (Software Interrupts)}	\label{sec:csignal}

SWI-Prolog offers both a C and Prolog interface to deal with software
interrupts (signals). The Prolog mapping is defined in
\secref{signal}. This subsection deals with handling signals from C.

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.

Some versions of SWI-Prolog, notably running on popular Unix platforms,
handle \const{SIG_SEGV} for guarding the Prolog stacks. If the
application wishes to handle this signal too, it should use PL_signal()
to install its handler after initialising Prolog. SWI-Prolog will pass
\const{SIG_SEGV} to the user code if it detected the signal is not
related to a Prolog stack overflow.

Any handler that wishes to call one of the Prolog interface functions
should call PL_signal() for its installation.

\begin{description}
    \cfunction{void (*)()}{PL_signal}{sig, func}
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.

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.

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 \jargon{synchronous} handling of signals. In this
case the native OS handler just schedules the signal using PL_raise(),
which is checked by PL_handle_signals() at the call- and redo-port. This
behaviour is realised by or-ing \arg{sig} with the constant
\const{PL_SIGSYNC}.%
    \footnote{A better default would be to use synchronous handling,
	      but this interface preserves backward compatibility.}

Signal handling routines may raise exceptions using
PL_raise_exception().  The use of PL_throw() is not safe.  If a synchronous
handler raises an exception, the exception is delayed to the next call
to PL_handle_signals();

    \cfunction{int}{PL_raise}{int sig}
Register \arg{sig} for \emph{synchronous} handling by Prolog.
Synchronous signals are handled at the call-port or if foreign code
calls PL_handle_signals().  See also thread_signal/2.

    \cfunction{int}{PL_handle_signals}{void}
Handle any signals pending from PL_raise(). PL_handle_signals() is
called at each pass through the call- and redo-port at a safe point.
Exceptions raised by the handler using PL_raise_exception() are properly
passed to the environment.

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 \const{FALSE} as
soon as possible.

    \cfunction{int}{PL_get_signum_ex}{term_t t, int *sig}
Extract a signal specification from a Prolog term and store as integer
signal number in \arg{sig}.  The specification is an integer, lowercase
signal name without \const{SIG} or the full signal name.  These refer
to the same: \verb$9$, \verb$kill$ and \verb$SIGKILL$. Leaves a typed,
domain or instantiation error if the conversion fails.
\end{description}


\subsection{Miscellaneous}

\subsubsection{Term Comparison}

\begin{description}
\cfunction{int}{PL_compare}{term_t t1, term_t t2}
    Compares two terms using the standard order of terms and returns -1,
    0 or 1. See also compare/3.
\cfunction{int}{PL_same_compound}{term_t t1, term_t t2}
    Yields \const{TRUE} if \arg{t1} and \arg{t2} refer to physically
    the same compound term and \const{FALSE} otherwise.
\end{description}

\subsubsection{Recorded database}

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.

Please note that the returned handles have no meaning at the Prolog
level and the recorded terms are not visible from Prolog. The functions
PL_recorded() and PL_erase() are the only functions that can operate on
the stored term.

Two groups of functions are provided.  The first group (PL_record() and
friends) store Prolog terms on the Prolog heap for retrieval during the
same session. These functions are also used by recorda/3 and friends.
The recorded database may be used to communicate Prolog terms between
threads.

\begin{description}
\cfunction{record_t}{PL_record}{term_t +t}
    Record the term \arg{t} into the Prolog database as recorda/3 and
    return an opaque handle to the term.  The returned handle remains
    valid until PL_erase() is called on it.  PL_recorded() is used to
    copy recorded terms back to the Prolog stack.

\cfunction{int}{PL_recorded}{record_t record, term_t -t}
    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 \const{TRUE} on success, and \const{FALSE} if
    there is not enough space on the stack to accomodate the term.
    See also PL_record() and PL_erase().

\cfunction{void}{PL_erase}{record_t record}
    Remove the recorded term from the Prolog database, reclaiming all
    associated memory resources.
\end{description}

The second group (headed by PL_record_external()) 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 an compact in an external database.	Here are
the main features:

\begin{itemlist}
    \item [Independent of session]
Records can be communicated to another Prolog session and made visible
using PL_recorded_external().
    \item [Binary]
The representation is binary for maximum performance.  The returned data
may contain 0-bytes.
    \item [Byte-order independent]
The representation can be transferred between machines with different
byte-order.
    \item [No alignment restrictions]
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.
    \item [Compact]
It is assumed that a smaller memory footprint will eventually outperform
slightly faster representations.
    \item [Stable]
The format is designed for future enhancements without breaking
compatibility with older records.
\end{itemlist}

\begin{description}
\cfunction{char *}{PL_record_external}{term_t +t, size_t *len}
    Record the term \arg{t} into the Prolog database as recorda/3 and
    return an opaque handle to the term.  The returned handle remains
    valid until PL_erase_external() is called on it.

    It is allowed to copy the data and use PL_recorded_external() on
    the copy.  The user is responsible for the memory management of
    the copy.  After copying, the original may be discarded using
    PL_erase_external().

    PL_recorded_external() is used to copy such recorded terms back to
    the Prolog stack.
\cfunction{int}{PL_recorded_external}{const char *record, term_t -t}
    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 PL_record_external() and PL_erase_external().
\cfunction{int}{PL_erase_external}{char *record}
    Remove the recorded term from the Prolog database, reclaiming all
    associated memory resources.
\end{description}


\subsubsection{Getting file names}		\label{sec:cfilenames}

The function PL_get_file_name() provides access to Prolog filenames and
its file-search mechanism described with absolute_file_name/3. Its
existence is motivated to realise a uniform interface to deal with
file-properties, search, naming conventions etc.\ from foreign code.

\begin{description}
    \cfunction{int}{PL_get_file_name}{term_t spec, char **name, int flags}
Translate a Prolog term into a file name. The name is stored in the
static buffer ring described with PL_get_chars() option
\const{BUF_RING}. Conversion from the internal UNICODE encoding is done
using standard C library functions. \arg{flags} is a bit-mask
controlling the conversion process. Options are:

\begin{description}
    \definition{\const{PL_FILE_ABSOLUTE}}
Return an absolute path to the requested file.
    \definition{\const{PL_FILE_OSPATH}}
Return a the name using the hosting OS conventions.  On MS-Windows,
\chr{\} is used to separate directories rather than the canonical
\chr{/}.
    \definition{\const{PL_FILE_SEARCH}}
Invoke absolute_file_name/3.  This implies rules from file_search_path/2
are used.
    \definition{\const{PL_FILE_EXIST}}
Demand the path to refer to an existing entity.
    \definition{\const{PL_FILE_READ}}
Demand read-access on the result.
    \definition{\const{PL_FILE_WRITE}}
Demand write-access on the result.
    \definition{\const{PL_FILE_EXECUTE}}
Demand execute-access on the result.
    \definition{\const{PL_FILE_NOERRORS}}
Do not raise any exceptions.
\end{description}
\end{description}


\subsection{Errors and warnings}

PL_warning() prints a standard Prolog warning message to the standard
error (\const{user_error}) stream. Please note that new code should
consider using PL_raise_exception() to raise a Prolog exception. See
also \secref{exception}.

\begin{description}
\cfunction{int}{PL_warning}{format, a1, \ldots}
Print an error message starting with `{\tt [WARNING: }', followed
by the output from \arg{format}, followed by a `\chr{]}' and a newline.
Then start the tracer. \arg{format} and the arguments are the same as
for \manref{printf}{2}. Always returns \const{FALSE}.
\end{description}

\subsection{Environment Control from Foreign Code}

\begin{description}
\cfunction{int}{PL_action}{int, ...}
Perform some action on the Prolog system. \arg{int} describes the
action, Remaining arguments depend on the requested action. The actions
are listed in \tabref{action}.

\begin{table}
\begin{quote}\begin{tabular}{|p{\tableft}|p{3.5in}|}
\hline
\const{PL_ACTION_TRACE}     & Start Prolog tracer (trace/0).
			      Requires no arguments. \\
\const{PL_ACTION_DEBUG}     & Switch on Prolog debug mode (debug/0).
			      Requires no arguments. \\
\const{PL_ACTION_BACKTRACE} & Print backtrace on current output stream.
                              The argument (an int) is the number of frames
			      printed. \\
\const{PL_ACTION_HALT}      & 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 int) is the
			      exit code. See halt/1. \\
\const{PL_ACTION_ABORT}     & Generate a Prolog abort (abort/0).
			      This call does not return.
			      Requires no arguments. \\
\const{PL_ACTION_BREAK}     & Create a standard Prolog break environment
			      (break/0). Returns after the user types
			      the end-of-file character.
			      Requires no arguments. \\
\const{PL_ACTION_GUIAPP}    & Win32: Used to indicate 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 simply prints the error
			      and exits otherwise. \\
\const{PL_ACTION_WRITE}	    & Write the argument, a \ctype{char *} to the
			      current output stream. \\
\const{PL_ACTION_FLUSH}	    & Flush the current output stream.
			      Requires no arguments. \\
\const{PL_ACTION_ATTACH_CONSOLE} &
			      Attach a console to a thread if it does
			      not have one.  See attach_console/0. \\
\const{PL_GMP_SET_ALLOC_FUNCTIONS} &
			      Takes and integer argument. If
			      \const{TRUE}, the GMP allocation are
			      immediately bound to the Prolog
			      functions.  If \const{FALSE}, SWI-Prolog
			      will never rebind the GMP allocation
			      functions.  See mp_set_memory_functions()
			      in the GMP documentation.
			      The action returns \const{FALSE} if there
			      is no GMP support or GMP is already
			      initialised. \\
\hline
\end{tabular}\end{quote}

    \caption{PL_action() options}
    \label{tab:action}
\end{table}
\end{description}

\subsection{Querying Prolog}

\begin{description}
\cfunction{long}{PL_query}{int}
Obtain status information on the Prolog system. The actual argument
type depends on the information required. \arg{int} describes what
information is wanted.%
	\footnote{Returning pointers and integers as a long is bad
		  style.  The signature of this function should be
		  changed.}
The  options are given in \tabref{query}.


\begin{table}
\begin{quote}\begin{tabular}{|p{\tableft}|p{3.5in}|}
\hline
\const{PL_QUERY_ARGC}       & Return an integer holding the number of
                              arguments given to Prolog from Unix. \\
\const{PL_QUERY_ARGV}       & Return a char ** holding the argument vector
                              given to Prolog from Unix. \\
\const{PL_QUERY_SYMBOLFILE} & Return a char * holding the current symbol
                              file of the running process. \\
\const{PL_MAX_INTEGER}      & Return a long, representing the maximal integer
                              value represented by a Prolog integer. \\
\const{PL_MIN_INTEGER}      & Return a long, representing the minimal integer
                              value. \\
\const{PL_QUERY_VERSION}    & Return a long, representing the version as
                              $10,000 \times M + 100 \times m + p$, where
                              $M$ is the major, $m$ the minor version number
                              and $p$ the patch-level.  For example,
                              \exam{20717} means \exam{2.7.17}. \\
\const{PL_QUERY_ENCODING}    & Return the default stream encoding of
			       Prolog (of type \ctype{IOENC}). \\
\const{PL_QUERY_USER_CPU}    & Get amount of user CPU time of the
			       process in milliseconds. \\
\hline
\end{tabular}\end{quote}

    \caption{PL_query() options}
    \label{tab:query}
\end{table}
\end{description}


\subsection{Registering Foreign Predicates}

\begin{description}
\cfunction{int}{PL_register_foreign_in_module}{const char *module,
					       const char *name, int arity,
					       foreign_t (*function)(),
					       int flags}
Register a C-function to implement a Prolog predicate. After this call
returns successfully a predicate with name \arg{name} (a char *) and
arity \arg{arity} (a C int) is created in module \arg{module}.  If
\arg{module} is \const{NULL}, the predicate is created in the module
of the calling context or if no context is present in the module
\const{user}.

When called in Prolog, Prolog will call \arg{function}. \arg{flags}
forms bitwise or'ed list of options for the installation. These are:

\begin{tabular}{|p{\tableft}|p{3.5in}|}
\hline
\const{PL_FA_NOTRACE}          & Predicate cannot be seen in the tracer \\
\const{PL_FA_TRANSPARENT}      & Predicate is module transparent \\
\const{PL_FA_NONDETERMINISTIC} & Predicate is non-deterministic.
                                 See also PL_retry(). \\
\const{PL_FA_VARARGS}	       & Use alternative calling convention. \\
\hline
\end{tabular}

Predicates may be registered either before or after PL_initialise().
When registered before initialisation the registration is recorded and
executed after installing the system predicates and before loading the
saved state.

Default calling (i.e.\ without \const{PL_FA_VARARGS}) \arg{function} is
passed the same number of term_t arguments as the arity of the predicate
and, if the predicate is non-deterministic, an extra argument of type
\ctype{control_t} (see \secref{foreignnondet}). If \const{PL_FA_VARARGS}
is provided, \arg{function} is called with three arguments. The first
argument is a \ctype{term_t} handle to the first argument. Further
arguments can be reached by adding the offset (see also
PL_new_term_refs()). 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 \ctype{void*}.  Here is an example:

\begin{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);
}
\end{code}

\cfunction{int}{PL_register_foreign}{const char *name, int arity,
				     foreign_t (*function)(), int flags}
Same as PL_register_foreign_in_module(), passing \const{NULL} for the
\arg{module}.

    \cfunction{void}{PL_register_extensions_in_module}{const char *module,
						       PL_extension *e}
Register a series of predicates from an array of definitions of the type
\ctype{PL_extension} in the given \arg{module}. If \arg{module} is
\const{NULL}, the predicate is created in the module of the calling
context or if no context is present in the module \const{user}.
The \ctype{PL_extension} type is defined as

\begin{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;
\end{code}

For details, see PL_register_foreign_in_module(). Here is an example of
its usage:

\begin{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);

  ...
}
\end{code}

    \cfunction{void}{PL_register_extensions}{ PL_extension *e}
Same as PL_register_extensions_in_module() using \const{NULL} for
the \arg{module} argument.
\end{description}


\subsection{Foreign Code Hooks}

For various specific applications some hooks re provided.

\begin{description}
\cfunction{PL_dispatch_hook_t}{PL_dispatch_hook}{PL_dispatch_hook_t}
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:
\const{PL_DISPATCH_INPUT} indicates Prolog input is available on file
descriptor 0 or \const{PL_DISPATCH_TIMEOUT} to indicate a timeout. The old
hook is returned. The type \ctype{PL_dispatch_hook_t} is defined as:

\begin{code}
typedef int  (*PL_dispatch_hook_t)(void);
\end{code}
    \cfunction{void}{PL_abort_hook}{PL_abort_hook_t}
Install a hook when abort/0 is executed. SWI-Prolog abort/0 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
    \ctype{PL_abort_hook_t} is defined as:
\begin{code}
typedef void (*PL_abort_hook_t)(void);
\end{code}
    \cfunction{int}{PL_abort_unhook}{PL_abort_hook_t}
Remove a hook installed with PL_abort_hook(). Returns \const{FALSE} if no
such hook is found, \const{TRUE} otherwise.
    \cfunction{void}{PL_on_halt}{void (*f)(int, void *), void *closure}
Register the function \arg{f} 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 on your operating system) and the
\arg{closure} argument passed to the PL_on_halt() call.  See also
at_halt/1.
    \cfunction{PL_agc_hook_t}{PL_agc_hook}{PL_agc_hook_t new}
Register a hook with the atom-garbage collector (see
garbage_collect_atoms/0 that is called on any atom that is reclaimed.
The old hook is returned.  If no hook is currently defined, \const{NULL}
is returned. The argument of the called hook is the atom that is to be
garbage collected.  The return value is an \ctype{int}.  If the return
value is zero, the atom is {\bf not} reclaimed.
The hook may invoke any Prolog predicate.

The example below defines a foreign library for printing the garbage
collected atoms for debugging purposes.

\begin{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);
}
\end{code}
\end{description}


\subsection{Storing foreign data}		\label{sec:foreigndata}

This section provides some hints for handling foreign data in Prolog.
With foreign data, we refer to data that is used by foreign language
predicates and needs to be passed around in Prolog. Excluding
combinations, there are three principal options for storing such data

\begin{itemlist}
    \item[Natural Prolog data]
E.i.\ using the representation one would choose if there was no foreign
interface required.
    \item[Opaque packed Prolog data]
Data can also be represented in a foreign structure and stored on the
Prolog stacks using PL_put_string_nchars() and retrieved using
PL_get_string_chars().  It is generally good practice to wrap the
string in a compound term with arity 1, so Prolog can identify the
type.  portray/1 rules may be used to streamline printing such terms
during development.
    \item[Natural foreign data, passing a pointer]
An alternative is to pass a pointer to the foreign data. Again, this
functor may be wrapped in a compound term.
\end{itemlist}

\noindent
The choice may be guided using the following distinctions

\begin{itemlist}
    \item[Is the data opaque to Prolog]
With `opaque' data, we refer to data handled in foreign functions,
passed around in Prolog, but of which Prolog never examines the contents
of the data itself. If the data is opaque to Prolog, the chosen
representation does not depend on simple analysis by Prolog, and the
selection will be driven solely by simplicity of the interface and
performance (both in time and space).
    \item[How big is the data]
Is efficient encoding required?  For examine, a boolean array may be
expressed as a compound term, holding integers each of which contains
a number of bits, or as a list of \const{true} and \const{false}.
    \item[What is the nature of the data]
For examples in C, constants are often expressed using `enum' or
\#define'd integer values. If prolog needs to handle this data, atoms
are a more logical choice.   Whether or not this mapping is used depends
on whether Prolog needs to interpret the data, how important debugging is
and how important performance is.
    \item[What is the lifetime of the data]
We can distinguish three cases.
    \begin{enumerate}
	\item
The lifetime is dictated by the accessibility of the data on the Prolog
stacks. Their is no way by which the foreign code when the data becomes
`garbage', and the data thus needs to be represented on the Prolog
stacks using Prolog data-types. (2),
        \item
The data lives on the `heap' and is explicitly allocated and
deallocated. In this case, representing the data using native foreign
representation and passing a pointer to it is a sensible choice.
	\item
The data lives as during the lifetime of a foreign 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 \secref{foreignnondet}.
    \end{enumerate}
\end{itemlist}


\subsubsection{Examples for storing foreign data}

In this section, we will 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. Finally,
we discuss the outline of the DDE interface.

\paragraph{Integer sets} 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 and'ing and or'ing the
bit-vectors. This can be done using Prolog's unbounded integers.

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 \functor{bitvector}{1},
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.

\begin{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);
}
\end{code}

\paragraph{The DDE interface} (see \secref{DDE}) 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 \jargon{handle}.  The
handle is a reference to a foreign data-structure containing the
relevant information.

There are a couple of possibilities for representing the handle.  The
choice depends on responsibilities and debugging facilities.  The
simplest approach is to using PL_unify_pointer() and PL_get_pointer().
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, not to verify it is pointing to a structure of the desired
type.  The pointer may be wrapped into a compound term with arity
1 (i.e., \exam{dde_channel(<Pointer>)}), making the type-problem
less serious.

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.


\subsection{Embedding SWI-Prolog in other applications}	\label{sec:embedded}

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.

The most simple embedded program is below. The interface function
PL_initialise() {\bf must} be called before any of the other SWI-Prolog
foreign language functions described in this chapter, except for
PL_initialise_hook(), PL_new_atom(), PL_new_functor() and
PL_register_foreign(). PL_initialise() interprets all the command-line
arguments, except for the \argoption{-t}{toplevel} flag that is
interpreted by PL_toplevel().

\begin{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);
}
\end{code}

\begin{description}
\cfunction{int}{PL_initialise}{int argc, char **argv}
Initialises the SWI-Prolog heap and stacks, restores the Prolog
state, loads the system and personal initialisation files,
runs the at_initialization/1 hooks and finally runs the
\argoption{-g}{goal} hook.

Special consideration is required for \verb$argv[0]$. On {\bf Unix},
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 {\bf Windows} version uses this to find
a \jargon{module} of the running executable.  If the specified module
cannot be found, it tries the module \const{libpl.dll}, containing
the Prolog runtime kernel. In all these cases, the resulting file is
used for two purposes

\begin{itemize}
    \item 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 \file{boot.prc} file from the SWI-Prolog home
	  directory.  See also qsave_program/[1,2] and \secref{plld}.
    \item Find the Prolog home directory.  This process is described
          in detail in \secref{findhome}.
\end{itemize}

PL_initialise() returns 1 if all initialisation succeeded and 0
otherwise.%
    \bug{Various fatal errors may cause PL_initialise to call
	 PL_halt(1), preventing it from returning at all.}

In most cases, \arg{argc} and \arg{argv} will be passed from the main
program.  It is allowed to create your own argument vector, provided
\verb$argv[0]$ is constructed according to the rules above.   For
example:

\begin{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);
  ...
}
\end{code}

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.

A good setup in Windows is to add SWI-Prolog's \file{bin} directory
to your \env{PATH} and either pass a module holding a saved-state, or
\verb$"libpl.dll"$ as \verb$argv[0]$.  If the Prolog state is attached
to a DLL (see the \cmdlineoption{-dll} option of \program{swipl-ld}, pass
the name of this DLL.

    \cfunction{int}{PL_is_initialised}{int *argc, char ***argv}
Test whether the Prolog engine is already initialised. Returns
\const{FALSE} if Prolog is not initialised and \const{TRUE} otherwise.
If the engine is initialised and \arg{argc} is not \const{NULL}, the
argument count used with PL_initialise() is stored in \arg{argc}.  Same
for the argument vector \arg{argv}.

    \cfunction{void}{PL_install_readline}{}
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.

    \cfunction{int}{PL_toplevel}{}
Runs the goal of the \argoption{-t}{toplevel} switch (default prolog/0) and
returns 1 if successful, 0 otherwise.

    \cfunction{int}{PL_cleanup}{int status}
This function performs the reverse of PL_initialise(). It runs the
PL_on_halt() and at_halt/1 handlers, closes all streams (except for the
`standard I/O' streams which are flushed only), deallocates all memory
and restores all signal handlers. The \arg{status} argument is passed to
the various termination hooks and indicates the \jargon{exit-status}.

The function returns \const{TRUE} if successful and \const{FALSE}
otherwise. Currently, \const{FALSE} is returned when an attempt is made
to call PL_cleanup() recursively or if PL_cleanup() is not called from
the main-thread.

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 PL_initialise()
will leak memory in the best case. It can also crash the appliction.

In this state, there is little practical use for this function. If you
want to use Prolog temporary 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.

    \cfunction{void}{PL_cleanup_fork}{}
Close file descriptors associated to Prolog streams except for 0,1~and~2.
Stop intervaltimer that may be running on behalf of profile/1.  The call
is intended to be used in combination with fork():

\begin{code}
    if ( (pid=fork()) == 0 )
    { PL_cleanup_fork();
      <some exec variation>
    }
\end{code}

The call behaves the same  on  Windows,   though  there  is  probably no
meaningful application.

    \cfunction{int}{PL_halt}{int status}
Cleanup the Prolog environment using PL_cleanup() and calls exit() with
the status argument.  As PL_cleanup() can only be called from the main
thread, this function returns \const{FALSE} when called from another
thread as the main one.%
	\bug{Eventually it may become possible to call
	     PL_halt() from any thread.}
\end{description}


\subsubsection{Threading, Signals and embedded Prolog}
\label{sec:sigembedded}

This section applies to Unix-based environments that have signals or
multi-threading.  The Windows version is compiled for multi-threading
and Windows lacks proper signals.

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 multi-threaded and appear to do
signal-handling (software interrupts).

On Unix systems, SWI-Prolog uses three signals:

\begin{description}
    \item[SIGUSR1] is used to sychronise atom- and clause garbage
    collection.  The handler is installed at the start of GC and
    reverted to the old setting after completing.

    \item[SIGUSR2] has an empty signal handler.   This signal is
    sent to a thread after sending a thread-signal (see
    thread_signal/2).  It causes blocking system calls to return
    with \const{EINTR}, which gives them to opportunity to react
    on thread-signals.

    \item[SIGINT] is used by the toplevel 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.
\end{description}

The \cmdlineoption{--nosignals} option can be used to inhibit processing
of \const{SIGINT}. 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
\file{pl-thread.h} of the source-distribution.


\section{Linking embedded applications using swipl-ld}	\label{sec:plld}

The utility program \program{swipl-ld} (Win32: swipl-ld.exe) may be used to link
a combination of C-files and Prolog files into a stand-alone executable.
\program{swipl-ld} automates most of what is described in the previous
sections.

In the normal usage, a copy is made of the default embedding template
\file{\ldots/pl/include/stub.c}. The main() routine is modified to suit
your application. PL_initialise() \strong{must} be passed the
program-name (\arg{argv[0]}) (Win32: the executing program can be
obtained using GetModuleFileName()). The other elements of the
command-line may be modified. Next, \program{swipl-ld} is typically invoked
as:

\begin{code}
swipl-ld -o output stubfile.c [other-c-or-o-files] [plfiles]
\end{code}

\program{swipl-ld} will first split the options into various groups for both
the C-compiler and the Prolog compiler. Next, it will add various
default options to the C-compiler and call it to create an executable
holding the user's C-code and the Prolog kernel. Then, it will call the
SWI-Prolog compiler to create a saved state from the provided Prolog
files and finally, it will attach this saved state to the created
emulator to create the requested executable.

Below, it is described how the options are split and which additional
options are passed.

\begin{description}
    \cmdlineoptionitem{-help}{}
Print brief synopsis.
    \cmdlineoptionitem{-pl}{prolog}
Select the prolog to use.  This prolog is used for two purposes: get the
home-directory as well as the compiler/linker options and create a saved
state of the Prolog code.
    \cmdlineoptionitem{-ld}{linker}
Linker used to link the raw executable.  Default is to use the C-compiler
(Win32: \program{link.exe}).
    \cmdlineoptionitem{-cc}{C-compiler}
Compiler for \fileext{c} files found on the command-line.  Default is the
compiler used to build SWI-Prolog accessible through the Prolog flag
\prologflag{c_cc} (Win32: \program{cl.exe})..
    \cmdlineoptionitem{-c++}{C++-compiler}
Compiler for C++ sources (extensions \fileext{cpp}, \fileext{cxx},
\fileext{cc} or \fileext{C}) files found on the command-line.  Default is
\program{c++} or \program{g++} if the C-compiler is \program{gcc})
(Win32: cl.exe).

    \cmdlineoptionitem{-nostate}{}
Just relink the kernel, do not add any Prolog code to the new kernel.
This is used to create a new kernel holding additional foreign predicates
on machines that do not support the shared-library (DLL) interface, or if
building the state cannot be handled by the default procedure used by
\program{swipl-ld}.  In the latter case the state is created separately and
appended to the kernel using \exam{cat <kernel> <state> > <out>}
(Win32: \exam{copy /b <kernel>+<state> <out>})

    \cmdlineoptionitem{-shared}{}
Link C, C++ or object files into a shared object (DLL) that can be
loaded by the load_foreign_library/1 predicate. If used with
\cmdlineoption{-c}{} it sets the proper options to compile a C or C++
file ready for linking into a shared object

    \cmdlineoptionitem{-dll}{}
\emph{Windows only}. Embed SWI-Prolog into a DLL rather than an
executable.

    \cmdlineoptionitem{-c}{}
Compile C or C++ source-files into object files. This turns
\program{swipl-ld} into a replacement for the C or C++ compiler where proper
options such as the location of the include directory are passed
automatically to the compiler.

    \cmdlineoptionitem{-E}{}
Invoke the C preprocessor. Used to make \program{swipl-ld} a replacement for
the C or C++ compiler.

    \cmdlineoptionitem{-pl-options}{,\ldots}
Additional options passed to Prolog when creating the saved state.  The
first character immediately following \const{pl-options} is used as
separator and translated to spaces when the argument is built.
Example: \exam{-pl-options,-F,xpce} passed \exam{-F xpce} as additional
flags to Prolog.
    \cmdlineoptionitem{-ld-options}{,\ldots}
Passes options to the linker, similar to \cmdlineoption{-pl-options}.
    \cmdlineoptionitem{-cc-options}{,\ldots}
Passes options to the C/C++ compiler, similar to \cmdlineoption{-pl-options}.
    \cmdlineoptionitem{-v}{}
Select verbose operation, showing the various programs and their options.
    \cmdlineoptionitem{-o}{outfile}
Reserved to specify the final output file.
    \cmdlineoptionitem*{-l}{library}
Specifies a library for the C-compiler.  By default, \clib{-lswipl}
(Win32: libpl.lib) and the libraries needed by the Prolog kernel are given.
    \cmdlineoptionitem*{-L}{library-directory}
Specifies a library directory for the C-compiler.  By default the
directory containing the Prolog C-library for the current architecture
is passed.
    \cmdlineoptionitem{\cmdlineoption{-g} \bnfor{}
		       \cmdlineoption{-I\arg{include-directory}} \bnfor{}
		       \cmdlineoption{-D\arg{definition}}}{}
These options are passed to the C-compiler.  By default, the include
directory containing \file{SWI-Prolog.h} is passed.  \program{swipl-ld} adds
two additional \argoption*{-D}{def} flags:
\begin{description}
\cmdlineoptionitem*{-D}{\const{__SWI_PROLOG__}}
Indicates the code is to be connected to SWI-Prolog.
\cmdlineoptionitem*{-D}{\const{__SWI_EMBEDDED__}}
Indicates the creation of an embedded program.
\end{description}
    \cmdlineoptionitem{}{*.o \bnfor{}
			 *.c \bnfor{}
			 *.C \bnfor{}
			 *.cxx \bnfor{}
			 *.cpp}
Passed as input files to the C-compiler
    \cmdlineoptionitem{}{*.pl \bnfor *.qlf}
Passed as input files to the Prolog compiler to create the saved-state.
    \cmdlineoptionitem{}{*}
I.e.\ all other options. These are passed as linker options to the
C-compiler.
\end{description}


\subsection{A simple example}

The following is a very simple example going through all the steps
outlined above. It provides an arithmetic expression evaluator. We will
call the application \program{calc} and define it in the files \file{calc.c}
and \file{calc.pl}.  The Prolog file is simple:

\begin{code}
calc(Atom) :-
        term_to_atom(Expr, Atom),
        A is Expr,
        write(A),
        nl.
\end{code}

The C-part of the application parses the command-line options,
initialises the Prolog engine, locates the {calc}/1 predicate and calls
it.  The coder is in \figref{calc}.

\begin{figure}
\begin{code}
#include <stdio.h>
#include <SWI-Prolog.h>

#define MAXLINE 1024

int
main(int argc, char **argv)
{ char expression[MAXLINE];
  char *e = expression;
  char *program = argv[0];
  char *plav[2];
  int n;

  /* combine all the arguments in a single string */

  for(n=1; n<argc; n++)
  { if ( n != 1 )
      *e++ = ' ';
    strcpy(e, argv[n]);
    e += strlen(e);
  }

  /* make the argument vector for Prolog */

  plav[0] = program;
  plav[1] = NULL;

  /* initialise Prolog */

  if ( !PL_initialise(1, plav) )
    PL_halt(1);

  /* Lookup calc/1 and make the arguments and call */

  { predicate_t pred = PL_predicate("calc", 1, "user");
    term_t h0 = PL_new_term_refs(1);
    int rval;

    PL_put_atom_chars(h0, expression);
    rval = PL_call_predicate(NULL, PL_Q_NORMAL, pred, h0);

    PL_halt(rval ? 0 : 1);
  }

  return 0;
}
\end{code}
\caption{C-source for the calc application}
\label{fig:calc}
\end{figure}

\noindent
The application is now created using the following command-line:

\begin{code}
% swipl-ld -o calc calc.c calc.pl
\end{code}

\noindent
The following indicates the usage of the application:

\begin{code}
% calc pi/2
1.5708
\end{code}


\section{The Prolog `home' directory}		\label{sec:findhome}

Executables embedding SWI-Prolog should be able to find the `home'
directory of the development environment unless a self-contained
saved-state has been added to the executable (see qsave_program/[1,2]
and \secref{plld}).

If Prolog starts up, it will try to locate the development environment.
To do so, it will try the following steps until one succeeds.

\begin{enumerate}
    \item If the \cmdlineoption{--home=DIR} is provided, use this.
    \item If the environment variable \env{SWI_HOME_DIR} is defined and
          points to an existing directory, use this.
    \item If the environment variable \env{SWIPL} is defined and
          points to an existing directory, use this.
    \item Locate the primary executable or (Windows only) a component
          (\jargon{module}) thereof and check whether the parent
	  directory of the directory holding this file contains the
	  file \file{swipl}.  If so, this file contains the (relative)
	  path to the home directory. If this directory exists, use
	  this.  This is the normal mechanism used by the binary
	  distribution.
    \item If the precompiled path exists, use it.  This is only useful
          for a source installation.
\end{enumerate}

If all fails and there is no state attached to the executable or
provided Windows module (see PL_initialise()), SWI-Prolog gives up.  If
a state is attached, the current working directory is used.

The file_search_path/2 alias \const{swi} is set to point to the home
directory located.


\section{Example of Using the Foreign Interface} \label{sec:foreignxmp}

Below is an example showing all stages of the declaration of a foreign
predicate that transforms atoms possibly holding uppercase letters into
an atom only holding lower case letters. \Figref{lowercase-c} shows the
C-source file, \figref{load-foreign} illustrates compiling and loading
of foreign code.

\begin{figure}[htb]

\begin{code}
/*  Include file depends on local installation */
#include <SWI-Prolog.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

foreign_t
pl_lowercase(term_t u, term_t l)
{ char *copy;
  char *s, *q;
  int rval;

  if ( !PL_get_atom_chars(u, &s) )
    return PL_warning("lowercase/2: instantiation fault");
  copy = malloc(strlen(s)+1);

  for( q=copy; *s; q++, s++)
    *q = (isupper(*s) ? tolower(*s) : *s);
  *q = '\0';

  rval = PL_unify_atom_chars(l, copy);
  free(copy);

  return rval;
}

install_t
install()
{ PL_register_foreign("lowercase", 2, pl_lowercase, 0);
}
\end{code}

    \caption{Lowercase source file}
    \label{fig:lowercase-c}
\end{figure}


\begin{figure}[htb]
\begin{code}
% gcc -I/usr/local/lib/pl-\plversion/include -fpic -c lowercase.c
% gcc -shared -o lowercase.so lowercase.o
% swipl
Welcome to SWI-Prolog (Version \plversion)
...

1 ?- load_foreign_library(lowercase).

Yes
2 ?- lowercase('Hello World!', L).

L = 'hello world!'

Yes
\end{code}
    \caption{Compiling the C-source and loading the object file}
    \label{fig:load-foreign}
\end{figure}
\clearpage


\section{Notes on Using Foreign Code}	\label{sec:foreignnotes}

\subsection{Memory Allocation}

SWI-Prolog's heap memory allocation is based on the \manref{malloc}{3}
library routines.  The stacks are allocated using mmap() on most Unix
machines and using VirtualAlloc() on windows.  SWI-Prolog provides the
functions below as a wrapper around malloc().  Allocation errors in
these functions trap SWI-Prolog's fatal-error handler, in which case
PL_malloc() or PL_realloc() do not return.

Portable applications must use PL_free() to release strings returned
by PL_get_chars() using the \const{BUF_MALLOC} argument.  Portable
applications may use both PL_malloc() and friends or malloc() and
friends but should not mix these two sets of functions on the same
memory.%
    \footnote{These functions were introduced in SWI-Prolog 5.0.9 to
	      realise guaranteed portability.  Foreign code that must
	      be compatible with older versions can check
	      the \const{PLVERSION} macro.}

\begin{description}
    \cfunction{void *}{PL_malloc}{size_t bytes}
Allocate \arg{bytes} of memory.  On failure SWI-Prolog's fatal error
handler is called and PL_malloc() does not return.  Memory allocated
using these functions must use PL_realloc() and PL_free() rather than
realloc() and free().

    \cfunction{void *}{PL_realloc}{void *mem, size_t size}
Change the size of the allocated chunk, possibly moving it.  The
\arg{mem} argument must be obtained from a previous PL_malloc() or
PL_realloc() call.

    \cfunction{void}{PL_free}{void *mem}
Release memory.  The \arg{mem} argument must be obtained from a
previous PL_malloc() or PL_realloc() call.
\end{description}


\subsection{Compatibility between Prolog versions}

Great care is taken to ensure binary compatibility of foreign extensions
between different Prolog versions. Only much less frequently used stream
interface has been responsible for binary incompatibilities.

\index{PLVERSION}%
Source-code that relies on new features of the foreign interface can
use the macro \const{PLVERSION} to find the version of
\file{SWI-Prolog.h} and PL_query() using the option
\const{PL_QUERY_VERSION} to find the version of the attached Prolog
system. Both follow the same numbering schema explained with PL_query().


\subsection{Debugging and profiling foreign code (valgrind)}

\index{valgrind}\index{profiling,foreign code}%
This section is only relevant for Unix users on platforms supported by
\url[valgrind]{http://valgrind.org/}. Valgrind is an excellent binary
intrumentation platform.  Unlike many other instrumentation platforms,
valgrind can deal with code loaded through dlopen().

The \program{callgrind} tool can be used to profile foreign code loaded
under SWI-Prolog. Compile the foreign library adding \cmdlineoption{-g}
option to \program{gcc} or \program{swipl-ld}. By setting the environment
variable \env{VALGRIND} to \const{yes}, SWI-Prolog will \emph{not}
release loaded shared objects using dlclose(). This trick is required to
get source information on the loaded library. Without, valgrind claims
that the shared object has no debugging information.\footnote{Tested
using valgrind version 3.2.3 on x64.} Here is the complete sequence
using \program{bash} as login shell:

\begin{code}
% VALGRIND=yes valgrind --tool=callgrind pl <args>
<prolog interaction>
% kcachegrind callgrind.out.<pid>
\end{code}


\subsection{Name Conflicts in C modules}

In the current version of the system all public C functions of
SWI-Prolog are in the symbol table.  This can lead to name clashes with
foreign code.  Someday I should write a program to strip all these
symbols from the symbol table (why does Unix not have that?).  For now
I can only suggest to give your function another name.  You can do this
using the C preprocessor.  If---for example---your foreign package uses
a function warning(), which happens to exist in SWI-Prolog as well, the
following macro should fix the problem.

\begin{code}
#define warning warning_
\end{code}

Note that shared libraries do not have this problem as the shared
library loader will only look for symbols in the main executable for
symbols that are not defined in the library itself.


\subsection{Compatibility of the Foreign Interface}

The term-reference mechanism was first used by Quintus Prolog version 3.
SICStus Prolog version 3 is strongly based on the Quintus interface. The
described SWI-Prolog interface is similar to using the Quintus or
SICStus interfaces, defining all foreign-predicate arguments of type
\const{+term}.  SWI-Prolog explicitly uses type \ctype{functor_t}, while
Quintus and SICStus uses <name> and <arity>.  As the names of the functions
differ from Prolog to Prolog, a simple macro layer dealing with the
names can also deal with this detail.  For example:

\begin{code}
#define QP_put_functor(t, n, a) PL_put_functor(t, PL_new_functor(n, a))
\end{code}

The {\tt PL_unify_*()} functions are lacking from the Quintus and
SICStus interface.  They can easily be emulated or the put/unify
approach should be used to write compatible code.

The PL_open_foreign_frame()/PL_close_foreign_frame() combination is
lacking from both other Prologs.  SICStus has PL_new_term_refs(0),
followed by PL_reset_term_refs() that allows for discarding
term references.

The Prolog interface for the graphical user interface package XPCE
shares about 90\% of the code using a simple macro layer to deal
with different naming and calling conventions of the interfaces.