File: c-interface.tex

package info (click to toggle)
gprolog 1.4.5.0-3
  • links: PTS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 7,924 kB
  • sloc: ansic: 55,584; perl: 18,501; sh: 3,401; makefile: 1,114; asm: 20
file content (1961 lines) | stat: -rw-r--r-- 70,746 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
\newpage
\section{Interfacing Prolog and C}
\label{Interfacing-Prolog-and-C}
%HEVEA\cutdef[1]{subsection}

\subsection{Introduction}

The foreign code interface allows the use to link Prolog and C in both
directions.

A Prolog predicate can call a C function passing different kinds of arguments
(input, output or input/output). The interface performs implicit Prolog
$\leftrightarrow$ C data conversions for simple types (for instance a Prolog
integer is automatically converted into a C integer) and provides a set of
API (Application Programming Interface) functions to convert more complex
types (lists or structures). The interface also performs automatic error
detection depending on the actual type of the passed argument. An important
feature is the ability to write non-deterministic code in C.

It is also possible to call (or callback) a Prolog predicate from a C
function and to manage Prolog non-determinism: the C code can ask for next
solutions, remove all remaining solutions or terminate and keep
alternatives for the calling Prolog predicate).

\subsection{Including and using \texttt{gprolog.h}}

The C code should include \texttt{gprolog.h} which provides a set of C
definitions (types, macros, prototypes) associated to the API. Include this
files as follows:

\begin{Indentation}
\begin{verbatim}
#include <gprolog.h>
\end{verbatim}
\end{Indentation}

If the installation has been correctly done nothing else is needed. If the C
compiler/preprocessor cannot locate \texttt{gprolog.h} pass the C compiler
option required to specify an additional include directory
(e.g.\texttt{-I}\texttt{include\_dir}) to \texttt{gplc} as follows
\RefSP{Using-the-compiler}:

\OneLine{\% gplc -C -I\textrm{include\_dir ...}}

The file \texttt{gprolog.h} declares the following C types:

\begin{itemize}

\item \texttt{PlBool} as an integer and the constants \texttt{PL\_FALSE} (i.e. 0) and \texttt{PL\_TRUE}
(i.e. 1).

\item \texttt{PlLong} as an integer able to store a pointer (equivalent to
  \texttt{intptr\_t}). This type appeared in GNU Prolog 1.4.0 in replacement
  of \texttt{long} to support Windows 64 bits (where the \texttt{long} type is only
  32 bits). This type is used to handle integer types.

\item \texttt{PlULong} same as \texttt{PlLong} but unsigned (same as \texttt{uintptr\_t}).

\item \texttt{PlTerm} same as \texttt{intptr\_t}. This type is used to store general Prolog terms.

\end{itemize}


\textbf{New in GNU Prolog 1.3.1 and backward compatibility issues}: in
GNU Prolog 1.3.1 the API has been modified to protect namespace. The name of
public functions, macros, variables and types are now prefixed
with \texttt{Pl\_}, \texttt{PL\_} or \texttt{pl\_}. All these prefixes should
be avoided by the foreign C-code to prevent name clashes. To ensure a
backward compatibility, the names used by the old API are available thanks to
a set of \texttt{\#define}. However, this deprecated API should not be used
by recent code. It is also possible to prevent the definition of the
compatibility macros using:

\begin{Indentation}
\begin{verbatim}
#define __GPROLOG_FOREIGN_STRICT__
#include <gprolog.h>
\end{verbatim}
\end{Indentation}

In addition, \texttt{gprolog.h} defines a set of macros:

\begin{itemize}

\item \texttt{ \_\_GNU\_PROLOG\_\_} (as the major version).

\item \texttt{ \_\_GPROLOG\_\_}, \texttt{\_\_GPROLOG\_MINOR\_\_} and
  \texttt{\_\_GPROLOG\_PATCHLEVEL\_\_}. Their values are the major version,
  minor version, and patch level of GNU Prolog, as integer constants. For
  example, GNU Prolog 1.3.2 will define \texttt{\_\_\_\_GPROLOG\_\_} to 1,
  \texttt{\_\_\_\_GPROLOG\_MINOR\_\_} to 3, and
  \texttt{\_\_\_\_GPROLOG\_PATCHLEVEL\_\_} to 2.

  If you need to write code which depends on a specific version, you must be
  more careful. Recall these macros appeared in GNU Prolog 1.3.1 (undefined
  before), each time the minor version is increased, the patch level is reset
  to zero; each time the major version is increased (which happens rarely),
  the minor version and patch level are reset.

\item \texttt{\_\_GPROLOG\_VERSION\_\_}: the version as an integer defined as
  follows: $major * 10000 + minor * 100 + patch level$. For example: version
  1.3.2 will result in the value 10302.

\item \texttt{PL\_PROLOG\_DIALECT}: a C constant string (generally
  \texttt{"gprolog"}). Appeared in 1.3.2.

\item \texttt{PL\_PROLOG\_NAME}: a C constant string (generally
  \texttt{"GNU Prolog"}).

\item \texttt{PL\_PROLOG\_VERSION}: a C constant string associated to the
  version (e.g. \texttt{"1.4.0"}).

\item \texttt{PL\_PROLOG\_DATE}: a C constant string associated with the date
  of this version (e.g. \texttt{"Mar 29 2011"}.

\item \texttt{PL\_PROLOG\_COPYRIGHT}: a C constant string associated with the
  copyright of this version (e.g. \texttt{"Copyright (C) 1999-2018 Daniel Diaz"}.

\end{itemize}

Note the above \texttt{PL\_PROLOG\_}... macros are also accessible via Prolog
flags thanks to the built-in predicate \texttt{current\_prolog\_flag/2}
\RefSP{current-prolog-flag/2}


\subsection{Calling C from Prolog}
\label{Calling-C-from-Prolog}

\subsubsection{Introduction}

This interface can then be used to write both simple and complex C routines.
A simple routine uses either input or output arguments which type is simple.
In that case the user does not need any knowledge of Prolog data structures
since all Prolog $\leftrightarrow$ C data conversions are implicitly
achieved. To manipulate complex terms (lists, structures) a set of functions
is provided. Finally it is also possible to write non-deterministic C code.

\subsubsection{\AddDiD{foreign/1}%
\IdxDiD{foreign/2} directive \label{foreign/2-directive}}

\texttt{foreign/2} directive \RefSP{foreign/2} declares a C function interface.
The general form is \texttt{foreign(Template, Options)} which defines an
interface predicate whose prototype is \texttt{Template} according to the
options given by \texttt{Options}. \texttt{Template} is a callable term
specifying the type/mode of each argument of the associated Prolog predicate.

\SPart{Foreign options}: \texttt{Options} is a list of foreign options. If
this list contains contradictory options, the rightmost option is the one
which applies. Possible options are:

\begin{itemize}

\item \AddPOD{fct\_name}\texttt{fct\_name(F)}: \texttt{F} is an atom representing
the name of the C function to call. By default the name of the C function is
the same as the principal functor of \texttt{Template}. In any case, the atom
associated with the name of the function must conforms to the syntax of C
identifiers.

\item \AddPOD{return}\texttt{return(boolean}/\texttt{none}/\texttt{jump)}:
specifies the value returned by the C function:

\begin{itemize}

\item \IdxPOD{boolean}: the type of the function is \texttt{PlBool} (returns
\texttt{PL\_TRUE} on success, \texttt{PL\_FALSE} otherwise).

\item \IdxPOD{none}: the type of the function is \texttt{void} (no returned
value).

\item \IdxPOD{jump}: the type of the function is \texttt{void(*)()} (returns
the address of a Prolog code to execute).

\end{itemize}

The default value is \texttt{boolean}.

\item \AddPOD{bip\_name}\texttt{bip\_name(Name, Arity)}: initializes the error
context with \texttt{Name} and \texttt{Arity}. If an error occurs this
information is used to indicate from which predicate the error occurred
\RefSP{General-format-and-error-context}. It is also possible to prevent the
initialization of the error context using \texttt{bip\_name(none)}. By
default \texttt{Name} and \texttt{Arity} are set to the functor and arity of
\texttt{Template}.

\item \AddPOD{choice\_size}\texttt{choice\_size(N)}: this option specifies that the
function implements a non-deterministic code. \texttt{N} is an integer
specifying the size needed by the non-deterministic C function. This facility
is explained later \RefSP{Writing-non-deterministic-C-code}. By default a
foreign function is deterministic.

\end{itemize}

\texttt{foreign(Template)} is equivalent to
\texttt{foreign(Template, [])}.

\SPart{Foreign modes and types}: each argument of \texttt{Template}
specifies the foreign mode and type of the corresponding argument. This
information is used to check the type of effective arguments at run-time and
to perform Prolog $\leftrightarrow$ C data conversions. Each argument of
\texttt{Template} is formed with a mode symbol followed by a type name.
Possible foreign modes are:

\begin{itemize}

\item \texttt{+}: input argument.

\item \texttt{-}: output argument.

\item \texttt{?}: input/output argument.

\end{itemize}

Possible foreign types are:

\begin{tabular}{|l|l|l|l|}
\hline

Foreign type & Prolog type & C type & Description of the C type \\

\hline\hline

\texttt{integer} & integer & \texttt{PlLong} & value of the integer \\

\hline

\texttt{positive} & positive integer & \texttt{PlLong} & value of the integer
\\

\hline

\texttt{float} & floating point number & \texttt{double} & value of the
floating point number \\

\hline

\texttt{number} & number & \texttt{double} & value of the number \\

\hline

\texttt{atom} & atom & \texttt{PlLong} & internal key of the atom \\

\hline

\texttt{boolean} & boolean & \texttt{PlLong} & value of the boolean
(0=\texttt{false}, 1=\texttt{true}) \\

\hline

\texttt{char} & character & \texttt{PlLong} & value of (the code of) the
character \\

\hline

\texttt{code} & character code & \texttt{PlLong} & value of the character-code
\\

\hline

\texttt{byte} & byte & \texttt{PlLong} & value of the byte \\

\hline

\texttt{in\_char} & in-character & \texttt{PlLong} & value of the character or
\texttt{-1} for end-of-file \\

\hline

\texttt{in\_code} & in-character code & \texttt{PlLong} & value of the
character-code or \texttt{-1} for end-of-file \\

\hline

\texttt{in\_byte} & in-byte & \texttt{PlLong} & value of the byte or
\texttt{-1} for the end-of-file \\

\hline

\texttt{string} & atom & \texttt{char *} & C string containing the name of
the atom \\

\hline

\texttt{chars} & character list & \texttt{char *} & C string containing the
characters of the list \\

\hline

\texttt{codes} & character-code list & \texttt{char *} & C string containing
the characters of the list \\

\hline

\texttt{term} & Prolog term & \texttt{PlTerm} & generic Prolog term \\

\hline
\end{tabular}

\SPart{Simple foreign type}: a simple type is any foreign type listed in
the above tabled except \texttt{term}. A simple foreign type is an atomic
term (character and character-code lists are in fact lists of constants).
Each simple foreign type is converted to/from a C type to simplify the
writing of the C function.

\SPart{Complex foreign type}: type foreign type \texttt{term} refers to any
Prolog term (e.g. lists, structures\ldots). When such an type is
specified the argument is passed to the C function as a \texttt{PlTerm}
(GNU Prolog C type equivalent to a \texttt{PlLong}). Several functions are
provided to manipulate \texttt{PlTerm} variables \RefSP{Manipulating-Prolog-terms}. 
Since the original term is passed to the function it is
possible to read its value or to unify it. So the meaning of the mode symbol
is less significant. For this reason it is possible to omit the mode symbol.
In that case \texttt{term} is equivalent to \texttt{+term}.

\subsubsection{The C function}

The type returned by the C function depends on the value of the
\IdxPO{return} foreign option \RefSP{foreign/2-directive}. If it is
\IdxPO{boolean} then the C function is of type \texttt{PlBool} and shall
return \texttt{PL\_TRUE} in case of success and \texttt{PL\_FALSE}
otherwise. If the \texttt{return} option is \IdxPO{none} the C function is of
type \texttt{void}. Finally if it is \IdxPO{jump}, the function shall return
the address of a Prolog predicate and, at the exit of the function, the
control is given to that predicate.

The type of the arguments of the C function depends on the mode and type
declaration specified in \texttt{Template} for the corresponding argument as
explained in the following sections.

\subsubsection{Input arguments}
\label{Input-arguments}
An input argument is tested at run-time to check if its type conforms to the
foreign type and then it is passed to the C function. The type of the
associated C argument is given by the above table \RefSP{foreign/2-directive}. For instance, the effective argument \texttt{Arg} associated with
\texttt{+positive} foreign declaration is submitted to the following
process:

\begin{itemize}

\item if \texttt{Arg} is a variable an \texttt{instantiation\_error} is
raised.

\item if \texttt{Arg} is neither a variable nor an integer a
\texttt{type\_error(integer, Arg)} is raised.

\item if \texttt{Arg} is an integer $<$ 0 a
\texttt{domain\_error(not\_less\_than\_zero, Arg)} is raised.

\item otherwise the value of \texttt{Arg} is passed to the C is passed to
the C function as an integer (\texttt{PlLong}).

\end{itemize}

When \texttt{+string} is specified the string passed to the function is the
internal string of the corresponding atom and should not be modified.

When \texttt{+term} is specified the term passed to the function is the
original Prolog term. It can be read and/or unified. It is also the case
when \texttt{term} is specified without any mode symbol.

\subsubsection{Output arguments}
\label{Output-arguments}
An output argument is tested at run-time to check if its type conforms to
the foreign type and it is unified with the value set by the C function. The
type of the associated C argument is a pointer to the type given by the
above table \RefSP{foreign/2-directive}. For instance, the effective
argument \texttt{Arg} associated with \texttt{-positive} foreign declaration
is handled as follows:

\begin{itemize}

\item if \texttt{Arg} is neither a variable nor an integer a
\texttt{type\_error(integer, Arg)} is raised.

\item if \texttt{Arg} is an integer $<$ 0 a
\texttt{domain\_error(not\_less\_than\_zero, Arg)} is raised.

\item otherwise a pointer to an integer (\texttt{PlLong} \texttt{*}) is passed
to the C function. If the function returns \texttt{PL\_TRUE} the integer stored
at this location is unified with \texttt{Arg}.

\end{itemize}

When \texttt{-term} is specified, the function must construct a term into
the its corresponding argument (which is of type \texttt{PlTerm *}). At the
exit of the function this term will be unified with the actual predicate
argument.

\subsubsection{Input/output arguments}
\label{Input/output-arguments}
Basically an input/output argument is treated as in input argument if it is
not a variable, as an output argument otherwise. The type of the associated
C argument is a pointer to a \texttt{PlFIOArg} (GNU Prolog C type) defined as
follows:

\begin{Indentation}
\begin{verbatim}
typedef struct
    {
     PlBool is_var;
     PlBool unify;
     union
        {
         PlLong l;
         char  *s;
         double d;
        }value;
    }PlFIOArg;
\end{verbatim}
\end{Indentation}

The field \texttt{is\_var} is set to \texttt{PL\_TRUE} if the argument is a
variable and \texttt{PL\_FALSE} otherwise. This value can be tested by the C
function to determine which treatment to perform. The field \texttt{unify}
controls whether the effective argument must be unified at the exit of the C
function. Initially \texttt{unify} is set to the same value as
\texttt{is\_var} (i.e. a variable argument will be unified while a
non-variable argument will not) but it can be modified by the C function.
The field \texttt{value} stores the value of the argument. It is declared as
a C \texttt{union} since there are several kinds of value types. The field
\texttt{s} is used for C strings, \texttt{d} for C doubles and \texttt{l}
otherwise (\texttt{int}, \texttt{PlLong}, \texttt{PlTerm}). if \texttt{is\_var}
is \texttt{PL\_FALSE} then \texttt{value} contains the input value of the
argument with the same conventions as for input arguments
\RefSP{Input-arguments}.  At the exit of the function, if unify is
\texttt{PL\_TRUE} \texttt{value} must contain the value to unify with the same
conventions as for output arguments
\RefSP{Output-arguments}.

For instance, the effective argument \texttt{Arg} associated with
\texttt{?positive} foreign declaration is handled as follows:

\begin{itemize}

\item if \texttt{Arg} is a variable \texttt{is\_var} and \texttt{unify} are
set to \texttt{PL\_TRUE} else to \texttt{PL\_FALSE} and its value is copied in
\texttt{value.l}.

\item if \texttt{Arg} is neither a variable nor an integer a
\texttt{type\_error(integer, Arg)} is raised.

\item if \texttt{Arg} is an integer $<$ 0 a
\texttt{domain\_error(not\_less\_than\_zero, Arg)} is raised.

\item otherwise a pointer to the \texttt{PlFIOArg} (\texttt{PlFIOArg}
\texttt{*}) is passed to the C function. If the function returns
\texttt{PL\_TRUE} and if \texttt{unify} is \texttt{PL\_TRUE} the value stored in
\texttt{value.l} is unified with \texttt{Arg}.

\end{itemize}

\subsubsection{Writing non-deterministic C code}
\label{Writing-non-deterministic-C-code}
The interface allows the user to write non-deterministic C code. When a C
function is non-deterministic, a choice-point is created for this function.
When a failure occurs, if all more recent non-deterministic code are
finished, the function is re-invoked. It is then important to inform Prolog
when there is no more solution (i.e. no more choice) for a non-deterministic
code. So, when no more choices remains the function must remove the
choice-point. The interface increments a counter each time the function is
re-invoked. At the first call this counter is equal to 0. This information
allows the function to detect its first call. When writing non-deterministic
code, it is often useful to record data between consecutive re-invocations of
the function. The interface maintains a buffer to record such an
information. The size of this buffer is given by
\AddPO{choice\_size}\texttt{choice\_size(N)} when using \texttt{foreign/2}
\RefSP{foreign/2-directive}. This size is the number of (consecutive)
\texttt{PlLong}\emph{s} needed by the C function. Inside the function it is
possible to call the following functions/macros:

\begin{Indentation}
\begin{verbatim}
int  Pl_Get_Choice_Counter(void)
TYPE Pl_Get_Choice_Buffer (TYPE)
void Pl_No_More_Choice    (void)
\end{verbatim}
\end{Indentation}

The macro \texttt{Pl\_Get\_Choice\_Counter()} returns the value of the
invocation counter (0 at the first call).

The macro \texttt{Pl\_Get\_Choice\_Buffer(\Param{TYPE})} returns a
pointer to the buffer (casted to \Param{TYPE}).

The function \texttt{Pl\_No\_More\_Choice()} deletes the choice point
associated with the function.

\subsubsection{Example: input and output arguments}
All examples presented here can be found in the \texttt{ExamplesC}
sub-directory of the distribution, in the files \texttt{examp.pl} (Prolog
part) and \texttt{examp\_c.c} (C part).

Let us define a predicate \texttt{first\_occurrence(A, C, P)} which unifies
\texttt{P} with the position (from 0) of the first occurrence of the
character \texttt{C} in the atom \texttt{A}. The predicate must fail if
\texttt{C} does not appear in \texttt{A}.

In the prolog file \texttt{examp.pl}:

\OneLine{:- foreign(first\_occurrence(+string, +char, -positive)).}

In the C file \texttt{examp\_c.c}:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include <gprolog.h>

PlBool
first_occurrence(char *str, PlLong c, PlLong *pos)
{
  char *p;

  p = strchr(str, c);
  if (p == NULL)                    /* C does not appear in A */
    return PL_FALSE;                /* fail */

  *pos = p - str;                   /* set the output argument */
  return PL_TRUE;                   /* succeed */
}
\end{verbatim}
\end{Indentation}

The compilation produces an executable called \texttt{examp}:

\OneLine{\% gplc examp.pl examp\_c.c}

Examples of use:

\begin{Indentation}
\begin{verbatim}
| ?- first_occurrence(prolog, p, X).

X = 0

| ?- first_occurrence(prolog, k, X).

no

| ?- first_occurrence(prolog, A, X).
{exception: error(instantiation_error,first_occurrence/3)}

| ?- first_occurrence(prolog, 1 ,X).
{exception: error(type_error(character,1),first_occurrence/3)}
\end{verbatim}
\end{Indentation}

\subsubsection{Example: non-deterministic code}
We here define a predicate \texttt{occurrence(A, C, P)} which unifies
\texttt{P} with the position (from 0) of one occurrence of the character
\texttt{C} in the atom \texttt{A}. The predicate will fail if \texttt{C}
does not appear in \texttt{A}. The predicate is re-executable on
backtracking. The information that must be recorded between two invocations
of the function is the next starting position in \texttt{A} to search for
\texttt{C}.

In the prolog file \texttt{examp.pl}:

\OneLine{:- foreign(occurrence(+string, +char, -positive),
[choice\_size(1)]).}

In the C file \texttt{examp\_c.c}:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include <gprolog.h>

PlBool
occurrence(char *str, PlLong c, PlLong *pos)
{
  char **info_pos;
  char *p;

  info_pos = Pl_Get_Choice_Buffer(char **); /* recover the buffer */

  if (Pl_Get_Choice_Counter() == 0) /* first invocation ? */
    *info_pos = str;

  p = strchr(*info_pos, c);
  if (p == NULL)                    /* c does not appear */
    {
      Pl_No_More_Choice();          /* remove choice-point */
      return PL_FALSE;              /* fail */
    }

  *pos = p - str;                   /* set the output argument */
  *info_pos = p + 1;                /* update next starting pos */
  return PL_TRUE;                   /* succeed */
}
\end{verbatim}
\end{Indentation}

The compilation produces an executable called \texttt{examp}:

\OneLine{\% gplc examp.pl examp\_c.c}

Examples of use:

\begin{CodeTwoCols}
\One{| ?- occurrence(prolog, o, X).}
\SkipLine
\Two{X = 2 ?}{(here the user presses \texttt{;} to compute another solution)}
\SkipLine
\Two{X = 4 ?}{(here the user presses \texttt{;} to compute another solution)}
\SkipLine
\Two{no}     {(no more solution)}
\SkipLine
\One{| ?- occurrence(prolog, k, X).}
\SkipLine
\One{no}
\end{CodeTwoCols}

In the first example when the second (the last) occurrence is found
(\texttt{X=4}) the choice-point remains and the failure is detected only when
another solution is requested (by pressing \texttt{;}). It is possible to
improve this behavior by deleting the choice-point when there is no more
occurrence. To do this it is necessary to do one search ahead. The
information stored is the position of the next occurrence. Let us define such
a behavior for the predicate \texttt{occurrence2/3}.

In the prolog file \texttt{examp.pl}:

\OneLine{:- foreign(occurrence2(+string, +char, -positive),
[choice\_size(1)]).}

In the C file \texttt{examp\_c.c}:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include <gprolog.h>

PlBool
occurrence2(char *str, PlLong c, PlLong *pos)
{
  char **info_pos;
  char *p;

  info_pos = Pl_Get_Choice_Buffer(char **); /* recover the buffer */

  if (Pl_Get_Choice_Counter() == 0) /* first invocation ? */
    {
      p = strchr(str, c);
      if (p == NULL)                /* C does not appear at all */
        {
          Pl_No_More_Choice();      /* remove choice-point */
          return PL_FALSE;          /* fail */
        }

      *info_pos = p;
    }
                                    /* info_pos = an occurrence */
  *pos = *info_pos - str;           /* set the output argument */

  p = strchr(*info_pos + 1, c);
  if (p == NULL)                    /* no more occurrence */
    Pl_No_More_Choice();            /* remove choice-point */
  else
    *info_pos = p;                  /* else update next solution */

  return PL_TRUE;                   /* succeed */
}
\end{verbatim}
\end{Indentation}

Examples of use:

\begin{CodeTwoCols}
\One{| ?- occurrence2(prolog, l, X).}
\SkipLine
\Two{X = 3}{(here the user is not prompted since there is no more alternative)}
\SkipLine
\One{| ?- occurrence2(prolog, o, X).}
\SkipLine
\Two{X = 2 ?}{(here the user presses \texttt{;} to compute another solution)}
\SkipLine
\Two{X = 4}{(here the user is not prompted since there is no more alternative)}
\end{CodeTwoCols}

\subsubsection{Example: input/output arguments}
We here define a predicate \texttt{char\_ascii(Char, Code}) which converts
in both directions the character \texttt{Char} and its character-code
\texttt{Code}. This predicate is then similar to \IdxPB{char\_code/2}
\RefSP{char-code/2}.

In the prolog file \texttt{examp.pl}:

\OneLine{:- foreign(char\_ascii(?char, ?code)).}

In the C file \texttt{examp\_c.c}:

\begin{Indentation}
\begin{verbatim}
#include <gprolog.h>

PlBool
char_ascii(PlFIOArg *c, PlFIOArg *ascii)
{
  if (!c->is_var)                  /* Char is not a variable */
    {
      ascii->unify = PL_TRUE;      /* enforce unif. of Code */
      ascii->value.l = c->value.l; /* set Code */
      return PL_TRUE;              /* succeed */
    }

  if (ascii->is_var)               /* Code is also a variable */
    Pl_Err_Instantiation();        /* emit instantiation_error */

  c->value.l = ascii->value.l;     /* set Char */
  return PL_TRUE;                  /* succeed */
}
\end{verbatim}
\end{Indentation}

If \texttt{Char} is instantiated it is necessary to enforce the unification
of \texttt{Code} since it could be instantiated. Recall that by default if
an input/output argument is instantiated it will not be unified at the exit
of the function \RefSP{Input/output-arguments}. If both \texttt{Char} and
\texttt{Code} are variables the function raises an
\texttt{instantiation\_error}. The way to raise Prolog errors is described
later \RefSP{Raising-Prolog-errors}.

The compilation produces an executable called \texttt{examp}:

\OneLine{\% gplc examp.pl examp\_c.c}

Examples of use:

\begin{Indentation}
\begin{verbatim}
| ?- char_ascii(a, X).

X = 97

| ?- char_ascii(X, 65).

X = 'A'

| ?- char_ascii(a, 12).

no

| ?- char_ascii(X, X).
{exception: error(instantiation_error,char_ascii/2)}

| ?- char_ascii(1, 12).
{exception: error(type_error(character,1),char_ascii/2)}
\end{verbatim}
\end{Indentation}

\subsection{Manipulating Prolog terms}
\label{Manipulating-Prolog-terms}

\subsubsection{Introduction}
\label{Introduction:(Manipulating-Prolog-terms)}
In the following we presents a set of functions to manipulate Prolog terms.
For simple foreign terms the functions manipulate simple C types
\RefSP{foreign/2-directive}.

Functions managing lists handle an array of 2 elements (of type
\texttt{PlTerm}) containing the terms corresponding to the head and the tail
of the list. For the empty list \texttt{NULL} is passed as the array. These
functions require to flatten a list in each sub-list. To simplify the
management of proper lists (i.e. lists terminated by \texttt{[]}) a set of
functions is provided that handle the number of elements of the list (an
integer) and an array whose elements (of type \texttt{PlTerm}) are the
elements of the list. The caller of these functions must provide the array.

Functions managing compound terms handle a functor (the principal functor of
the term), an arity \Param{N} $\geq$ 0 and an array of \Param{N} elements
(of type \texttt{PlTerm}) containing the sub-terms of the compound term.
Since a list is a special case of compound term (functor = \texttt{'.'} and
arity=2) it is possible to use any function managing compound terms to deal
with a list but the error detection is not the same. Indeed many functions
check if the Prolog argument is correct. The name of a read or unify
function checking the Prolog arguments is of the form
\texttt{\Param{Name}\_Check()}. For each of these functions there is a also
check-free version called \texttt{\Param{Name}()}. We then only present the
name of checking functions.

\subsubsection{Managing Prolog atoms}

Each atom has a unique internal key (an integer) which corresponds to its index in the
GNU Prolog atom table. It is possible to obtain the information about an atom
and to create new atoms using:

\begin{Indentation}
\begin{verbatim}
char   *Pl_Atom_Name           (int atom)
int     Pl_Atom_Length         (int atom)
PlBool  Pl_Atom_Needs_Quote    (int atom)
PlBool  Pl_Atom_Needs_Scan     (int atom)
PlBool  Pl_Is_Valid_Atom       (int atom)
int     Pl_Create_Atom         (const char *str)
int     Pl_Create_Allocate_Atom(const char *str)
int     Pl_Find_Atom           (const char *str)
int     Pl_Atom_Char           (char c)
int     Pl_Atom_Nil            (void)
int     Pl_Atom_False          (void)
int     Pl_Atom_True           (void)
int     Pl_Atom_End_Of_File    (void)
\end{verbatim}
\end{Indentation}

The function \texttt{Pl\_Atom\_Name(atom)} returns the internal string of
\texttt{atom} (this string should not be modified). The function
\texttt{Pl\_Atom\_Length(atom)} returns the length (of the name) of
\texttt{atom}.

The function \texttt{Pl\_Atom\_Needs\_Scan(atom)} indicates if the canonical
form of \texttt{atom} needs to be quoted as done by \IdxPB{writeq/2}
\RefSP{write-term/3}. In that case \texttt{Pl\_Atom\_Needs\_Scan(atom)}
indicates if this simply comes down to write quotes around the name of
\texttt{atom} or if it necessary to scan each character of the name because
there are some non-printable characters (or included quote characters). The
function \texttt{Pl\_Is\_Valid\_Atom(atom)} is true only if \texttt{atom} is the
internal key of an existing atom.

The function \texttt{Pl\_Create\_Atom(str)} adds a new atom whose name is the
content of \texttt{str} to the system and returns its internal key. If the
atom already exists its key is simply returned. The string \texttt{str}
passed to the function should not be modified later. The function
\texttt{Pl\_Create\_Allocate\_Atom(str)} is provided when this condition cannot
be ensured. It simply makes a dynamic copy of \texttt{str}
(using \texttt{strdup(3)}).

The function \texttt{Pl\_Find\_Atom(str)} returns the internal key of the
atom whose name is \texttt{str} or \texttt{-1} if it does not exist.

All atoms corresponding to a single character already exist and their
key can be obtained via the function \texttt{Pl\_Atom\_Char}.  For
instance \texttt{Pl\_Atom\_Char('.')} is the atom associated with
\texttt{'.'} (this atom is the functor of lists). The other functions return
the internal key of frequently used atoms: \texttt{[]},
\texttt{false}, \texttt{true} and \texttt{end\_of\_file}.

\subsubsection{Reading Prolog terms}
\label{Reading-Prolog-terms}
The name of all functions presented here are of the form
\texttt{Pl\_Rd\_\Param{Name}\_Check()}. They all check the validity of the
Prolog term to read emitting appropriate errors if necessary. Each function
has a check-free version called \texttt{Pl\_Rd\_\Param{Name}()}.

\SPart{Simple foreign types}: for each simple foreign type
\RefSP{foreign/2-directive} there is a read function (used by the
interface when an input argument is provided):

\begin{Indentation}
\begin{verbatim}
PlLong  Pl_Rd_Integer_Check  (PlTerm term)
PlLong  Pl_Rd_Positive_Check (PlTerm term)
double  Pl_Rd_Float_Check    (PlTerm term)
double  Pl_Rd_Number_Check   (PlTerm term)
int     Pl_Rd_Atom_Check     (PlTerm term)
int     Pl_Rd_Boolean_Check  (PlTerm term)
int     Pl_Rd_Char_Check     (PlTerm term)
int     Pl_Rd_In_Char_Check  (PlTerm term)
int     Pl_Rd_Code_Check     (PlTerm term)
int     Pl_Rd_In_Code_Check  (PlTerm term)
int     Pl_Rd_Byte_Check     (PlTerm term)
int     Pl_Rd_In_Byte_Check  (PlTerm term)
char   *Pl_Rd_String_Check   (PlTerm term)
char   *Pl_Rd_Chars_Check    (PlTerm term)
char   *Pl_Rd_Codes_Check    (PlTerm term)
int     Pl_Rd_Chars_Str_Check(PlTerm term, char *str)
int     Pl_Rd_Codes_Str_Check(PlTerm term, char *str)
\end{verbatim}
\end{Indentation}

All functions returning a C string (\texttt{char *}) use a same buffer. The
function \texttt{Pl\_Rd\_Chars\_Str\_Check()} is similar to
\texttt{Pl\_Rd\_Chars\_Check()} but accepts as argument a string to store the
result and returns the length of that string (which is also the length of
the Prolog list). Similarly for \texttt{Pl\_Rd\_Codes\_Str\_Check()}.

\SPart{Complex terms}: the following functions return the sub-arguments
(terms) of complex terms as an array of \texttt{PlTerm} except
\texttt{Pl\_Rd\_Proper\_List\_Check()} which returns the size of the list read
(and initializes the array \texttt{element}). Refer to the introduction of
this section for more information about the arguments of complex functions
\RefSP{Introduction:(Manipulating-Prolog-terms)}.

\begin{Indentation}
\begin{verbatim}
int     Pl_Rd_Proper_List_Check(PlTerm term, PlTerm *arg)
PlTerm *Pl_Rd_List_Check       (PlTerm term)
PlTerm *Pl_Rd_Compound_Check   (PlTerm term, int *functor, int *arity)
PlTerm *Pl_Rd_Callable_Check   (PlTerm term, int *functor, int *arity)
\end{verbatim}
\end{Indentation}

\subsubsection{Unifying Prolog terms}
The name of all functions presented here are of the form
\texttt{Pl\_Un\_\Param{Name}\_Check()}. They all check the validity of the
Prolog term to unify emitting appropriate errors if necessary. Each function
has a check-free version called \texttt{Pl\_Un\_\Param{Name}()}.

\SPart{Simple foreign types}: for each simple foreign type
\RefSP{foreign/2-directive} there is an unify function (used by the
interface when an output argument is provided):

\begin{Indentation}
\begin{verbatim}
PlBool Pl_Un_Integer_Check (PlLong n,        PlTerm term)
PlBool Pl_Un_Positive_Check(PlLong n,        PlTerm term)
PlBool Pl_Un_Float_Check   (double n,        PlTerm term)
PlBool Pl_Un_Number_Check  (double n,        PlTerm term)
PlBool Pl_Un_Atom_Check    (int atom,        PlTerm term)
PlBool Pl_Un_Boolean_Check (int b,           PlTerm term)
PlBool Pl_Un_Char_Check    (int c,           PlTerm term)
PlBool Pl_Un_In_Char_Check (int c,           PlTerm term)
PlBool Pl_Un_Code_Check    (int c,           PlTerm term)
PlBool Pl_Un_In_Code_Check (int c,           PlTerm term)
PlBool Pl_Un_Byte_Check    (int b,           PlTerm term)
PlBool Pl_Un_In_Byte_Check (int b,           PlTerm term)
PlBool Pl_Un_String_Check  (const char *str, PlTerm term)
PlBool Pl_Un_Chars_Check   (const char *str, PlTerm term)
PlBool Pl_Un_Codes_Check   (const char *str, PlTerm term)
\end{verbatim}
\end{Indentation}

The function \texttt{Pl\_Un\_Number\_Check(n, term)} unifies \texttt{term} with
an integer if \texttt{n} is an integer, with a floating point number
otherwise. The function \texttt{Pl\_Un\_String\_Check(str, term)} creates the
atom corresponding to \texttt{str} and then unifies term with it (same as
\texttt{Pl\_Un\_Atom\_Check(Pl\_Create\_Allocate\_Atom(str), term)}).

The following functions perform a general unification (between 2 terms). The
second one performs a occurs-check test (while the first one does not).

\begin{Indentation}
\begin{verbatim}
PlBool Pl_Unif(PlTerm term1, PlTerm term2)
PlBool Pl_Unif_With_Occurs_Check(PlTerm term1, PlTerm term2)
\end{verbatim}
\end{Indentation}

\SPart{Complex terms}: the following functions accept the sub-arguments
(terms) of complex terms as an array of \texttt{PlTerm}. Refer to the
introduction of this section for more information about the arguments of
complex functions \RefSP{Introduction:(Manipulating-Prolog-terms)}.

\begin{Indentation}
\begin{verbatim}
PlBool Pl_Un_Proper_List_Check(int size, PlTerm *arg, PlTerm term)
PlBool Pl_Un_List_Check       (PlTerm *arg, PlTerm term)
PlBool Pl_Un_Compound_Check   (int functor, int arity, PlTerm *arg,
                               PlTerm term)
PlBool Pl_Un_Callable_Check   (int functor, int arity, PlTerm *arg,
                               PlTerm term)
\end{verbatim}
\end{Indentation}

All these functions check the type of the term to unify and return the
result of the unification. Generally if an unification fails the C function
returns \texttt{PL\_FALSE} to enforce a failure. However if there are several
arguments to unify and if an unification fails then the C function returns
\texttt{PL\_FALSE} and the type of other arguments has not been checked.
Normally all error cases are tested before doing any work to be sure that
the predicate fails/succeeds only if no error condition is satisfied. So a
good method is to check the validity of all arguments to unify and later
to do the unification (using check-free functions). Obviously if there is
only one to unify it is more efficient to use a unify function checking the
argument. For the other cases the interface provides a set of functions to
check the type of a term.

\SPart{Simple foreign types}: for each simple foreign type
\RefSP{foreign/2-directive} there is check-for-unification function (used
by the interface when an output argument is provided):

\begin{Indentation}
\begin{verbatim}
void Pl_Check_For_Un_Integer (PlTerm term)
void Pl_Check_For_Un_Positive(PlTerm term)
void Pl_Check_For_Un_Float   (PlTerm term)
void Pl_Check_For_Un_Number  (PlTerm term)
void Pl_Check_For_Un_Atom    (PlTerm term)
void Pl_Check_For_Un_Boolean (PlTerm term)
void Pl_Check_For_Un_Char    (PlTerm term)
void Pl_Check_For_Un_In_Char (PlTerm term)
void Pl_Check_For_Un_Code    (PlTerm term)
void Pl_Check_For_Un_In_Code (PlTerm term)
void Pl_Check_For_Un_Byte    (PlTerm term)
void Pl_Check_For_Un_In_Byte (PlTerm term)
void Pl_Check_For_Un_String  (PlTerm term)
void Pl_Check_For_Un_Chars   (PlTerm term)
void Pl_Check_For_Un_Codes   (PlTerm term)
\end{verbatim}
\end{Indentation}

\SPart{Complex terms}: the following functions check the validity of
complex terms:

\begin{Indentation}
\begin{verbatim}
void Pl_Check_For_Un_List    (PlTerm term)
void Pl_Check_For_Un_Compound(PlTerm term)
void Pl_Check_For_Un_Callable(PlTerm term)
void Pl_Check_For_Un_Variable(PlTerm term)
\end{verbatim}
\end{Indentation}

The function \texttt{Pl\_Check\_For\_Un\_List(term)} checks if \texttt{term} can
be unified with a list. This test is done for the entire list (not only for
the functor/arity of \texttt{term} but also recursively on the tail of the
list). The function \texttt{Pl\_Check\_For\_Un\_Variable(term)} ensures that
\texttt{term} is not currently instantiated. These functions can be defined
using functions to test the type of a Prolog term \RefSP{Testing-the-type-of-Prolog-terms} and functions to raise Prolog errors \RefSP{Raising-Prolog-errors}. For instance \texttt{Pl\_Check\_For\_Un\_List(term)} is defined
as follows:

\begin{Indentation}
\begin{verbatim}
void Pl_Check_For_Un_List(PlTerm term)
{
 if (!Pl_Builtin_List_Or_Partial_List(term))
     Pl_Err_Type(type_list, term);
}
\end{verbatim}
\end{Indentation}

\subsubsection{Creating Prolog terms}
\label{Creating-Prolog-terms}
These functions are provided to creates Prolog terms. Each function returns
a \texttt{PlTerm} containing the created term.

\SPart{Simple foreign types}: for each simple foreign type
\RefSP{foreign/2-directive} there is a creation function:

\begin{Indentation}
\begin{verbatim}
PlTerm Pl_Mk_Integer (PlLong n)
PlTerm Pl_Mk_Positive(PlLong n)
PlTerm Pl_Mk_Float   (double n)
PlTerm Pl_Mk_Number  (double n)
PlTerm Pl_Mk_Atom    (int atom)
PlTerm Pl_Mk_Boolean (int b)
PlTerm Pl_Mk_Char    (int c)
PlTerm Pl_Mk_In_Char (int c)
PlTerm Pl_Mk_Code    (int c)
PlTerm Pl_Mk_In_Code (int c)
PlTerm Pl_Mk_Byte    (int b)
PlTerm Pl_Mk_In_Byte (int b)
PlTerm Pl_Mk_String  (const char *str)
PlTerm Pl_Mk_Chars   (const char *str)
PlTerm Pl_Mk_Codes   (const char *str)
\end{verbatim}
\end{Indentation}

The function \texttt{Pl\_Mk\_Number(n, term)} initializes \texttt{term} with an
integer if \texttt{n} is an integer, with a floating point number otherwise.
The function \texttt{Pl\_Mk\_String(str)} first creates an atom corresponding to
\texttt{str} and then returns that Prolog atom (i.e. equivalent to
\texttt{Pl\_Mk\_Atom(Pl\_Create\_Allocate\_Atom(str))}).

\SPart{Complex terms}: the following functions accept the sub-arguments
(terms) of complex terms as an array of \texttt{PlTerm}. Refer to the
introduction of this section for more information about the arguments of
complex functions \RefSP{Introduction:(Manipulating-Prolog-terms)}.

\begin{Indentation}
\begin{verbatim}
PlTerm Pl_Mk_Proper_List(int size, const PlTerm *arg)
PlTerm Pl_Mk_List       (PlTerm *arg)
PlTerm Pl_Mk_Compound   (int functor, int arity, const PlTerm *arg)
PlTerm Pl_Mk_Callable   (int functor, int arity, const PlTerm *arg)
\end{verbatim}
\end{Indentation}

\subsubsection{Testing the type of Prolog terms}
\label{Testing-the-type-of-Prolog-terms}
The following functions test the type of a Prolog term. Each function
corresponds to a type testing built-in predicate \RefSP{var/1}.

\begin{Indentation}
\begin{verbatim}
PlBool Pl_Builtin_Var                 (PlTerm term)
PlBool Pl_Builtin_Non_Var             (PlTerm term)
PlBool Pl_Builtin_Atom                (PlTerm term)
PlBool Pl_Builtin_Integer             (PlTerm term)
PlBool Pl_Builtin_Float               (PlTerm term)
PlBool Pl_Builtin_Number              (PlTerm term)
PlBool Pl_Builtin_Atomic              (PlTerm term)
PlBool Pl_Builtin_Compound            (PlTerm term)
PlBool Pl_Builtin_Callable            (PlTerm term)
PlBool Pl_Builtin_List                (PlTerm term)
PlBool Pl_Builtin_Partial_List        (PlTerm term)
PlBool Pl_Builtin_List_Or_Partial_List(PlTerm term)
PlBool Pl_Builtin_Fd_Var              (PlTerm term)
PlBool Pl_Builtin_Non_Fd_Var          (PlTerm term)
PlBool Pl_Builtin_Generic_Var         (PlTerm term)
PlBool Pl_Builtin_Non_Generic_Var     (PlTerm term)
int    Pl_Type_Of_Term                (PlTerm term)
PlLong   Pl_List_Length                 (PlTerm list)
\end{verbatim}
\end{Indentation}

The function \texttt{Pl\_Type\_Of\_Term(term)} returns the type of
\texttt{term}, the following constants can be used to test this type (e.g.
in a \texttt{switch} instruction):

\begin{itemize}
\item \texttt{PL\_PLV}: Prolog variable.

\item \texttt{PL\_FDV}: finite domain variable.

\item \texttt{PL\_INT}: integer.

\item \texttt{PL\_FLT}: floating point number.

\item \texttt{PL\_ATM}: atom.

\item \texttt{PL\_LST}: list.

\item \texttt{PL\_STC}: structure
\end{itemize}

The tag \texttt{PL\_LST} means a term whose principal functor is \texttt{'.'}
and whose arity is 2 (recall that the empty list is the atom \texttt{[]}).
The tag \texttt{PL\_STC} means any other compound term.

The function \texttt{Pl\_List\_Length(list)} returns the number of elements of
the \texttt{list} (\texttt{0} for the empty list). If list is not a list
this function returns \texttt{-1}.

\subsubsection{Comparing Prolog terms}

The following functions compares Prolog terms. Each function corresponds to
a comparison built-in predicate \RefSP{(==)/2}.

\begin{Indentation}
\begin{verbatim}
PlBool Pl_Builtin_Term_Eq (PlTerm term1, PlTerm term2)
PlBool Pl_Builtin_Term_Neq(PlTerm term1, PlTerm term2)
PlBool Pl_Builtin_Term_Lt (PlTerm term1, PlTerm term2)
PlBool Pl_Builtin_Term_Lte(PlTerm term1, PlTerm term2)
PlBool Pl_Builtin_Term_Gt (PlTerm term1, PlTerm term2)
PlBool Pl_Builtin_Term_Gte(PlTerm term1, PlTerm term2)
\end{verbatim}
\end{Indentation}

All these functions are based on a general comparison function returning a
negative integer if \texttt{term1} is less than \texttt{term2}, 0 if they
are equal and a positive integer otherwise:

\begin{Indentation}
\begin{verbatim}
PlLong Term_Compare(PlTerm term1, PlTerm term2)
\end{verbatim}
\end{Indentation}

Finally, the following function gives an access to the \texttt{compare/3}
built-in \RefSP{compare/3} unifying \texttt{cmp} with the
atom \texttt{{\lt}}, \texttt{=} or \texttt{{\gt}} depending on the result of
the comparison of \texttt{term1} and \texttt{term2}.

\begin{Indentation}
\begin{verbatim}
PlBool Pl_Builtin_Compare(PlTerm cmp, PlTerm term1, PlTerm term2)
\end{verbatim}
\end{Indentation}


\subsubsection{Term processing}

The following functions give access to the built-in predicates:
\texttt{functor/3} \RefSP{functor/3}, \texttt{arg/3} \RefSP{arg/3}
and \texttt{(=..)/2} \RefSP{(=..)/2}.


\begin{Indentation}
\begin{verbatim}
PlBool Pl_Builtin_Functor(PlTerm term, PlTerm functor, PlTerm arity)

PlBool Pl_Builtin_Arg(PlTerm arg_no, PlTerm term, PlTerm sub_term)

PlBool Pl_Builtin_Univ(PlTerm term, PlTerm list)
\end{verbatim}
\end{Indentation}

The following functions make a copy of a Prolog term:

\begin{Indentation}
\begin{verbatim}
void Pl_Copy_Term           (PlTerm *dst_term, const PlTerm *src_term)
void Pl_Copy_Contiguous_Term(PlTerm *dst_term, const PlTerm *src_term)
int  Pl_Term_Size           (PlTerm term)
\end{verbatim}
\end{Indentation}

The function \texttt{Pl\_Copy\_Term(dst\_term, src\_term)} makes a copy of the
term located at \texttt{src\_term} and stores it from the address given by
\texttt{dst\_term}. The result is a contiguous term. If it can be ensured
that the source term is a contiguous term (i.e. result of a previous copy)
the function \texttt{Pl\_Copy\_Contiguous\_Term()} can be used instead (it is
faster). In any case, sufficient space should be available for the copy
(i.e. from \texttt{dst\_term}). The function \texttt{Pl\_Term\_Size(term)}
returns the number of \texttt{PlTerm} needed by \texttt{term}.

The following function is an utility to display a term to the console, similarly to
the built-in predicate \texttt{write/1} \RefSP{write-term/3}.

\begin{Indentation}
\begin{verbatim}
void Pl_Write(PlTerm term)
\end{verbatim}
\end{Indentation}

This \texttt{Pl\_Write} function can be used for debugging purpose. However, it is more
flexible to receive the content of the \texttt{write/1} as a C string. This can be
achieved by the following functions (using repectively \texttt{write/1},
\texttt{writeq/1}, \texttt{write\_canonical/1} and \texttt{display/1}
\RefSP{write-term/3} to obtain a textual representation of the term). These functions
return a dynamically allocated C string (using \texttt{malloc(3)}) which can be freed
by the user when no longer needed.

\begin{Indentation}
\begin{verbatim}
char *Pl_Write_To_String(PlTerm term)

char *Pl_Writeq_To_String(PlTerm term)

char *Pl_Write_Canonical_To_String(PlTerm term)

char *Pl_Display_To_String(PlTerm term)
\end{verbatim}
\end{Indentation}


Finally the following function performs the opposite converstion: given a C string it
returns the associated Prolog term. It uses \texttt{read\_term/2} \RefSP{read-term/3}
with the option \texttt{end\_of\_term(eof)} (thus the C string does not need to
terminate by a dot).

\begin{Indentation}
\begin{verbatim}
PlTerm Pl_Read_From_String(const char *str)
\end{verbatim}
\end{Indentation}



\subsubsection{Comparing and evaluating arithmetic expressions}
The following functions compare arithmetic expressions. Each function
corresponds to a comparison built-in predicate \RefSP{(=:=)/2}.

\begin{Indentation}
\begin{verbatim}
PlBool Pl_Builtin_Eq (PlTerm expr1, PlTerm expr2)
PlBool Pl_Builtin_Neq(PlTerm expr1, PlTerm expr2)
PlBool Pl_Builtin_Lt (PlTerm expr1, PlTerm expr2)
PlBool Pl_Builtin_Lte(PlTerm expr1, PlTerm expr2)
PlBool Pl_Builtin_Gt (PlTerm expr1, PlTerm expr2)
PlBool Pl_Builtin_Gte(PlTerm expr1, PlTerm expr2)
\end{verbatim}
\end{Indentation}

The following function evaluates the expression \texttt{expr} and stores its
result as a Prolog number (integer or floating point number) in
\texttt{result}:

\begin{Indentation}
\begin{verbatim}
void Pl_Math_Evaluate(PlTerm expr, PlTerm *result)
\end{verbatim}
\end{Indentation}

This function can be followed by a read function \RefSP{Reading-Prolog-terms}
to obtain the result.

\subsection{Raising Prolog errors}
\label{Raising-Prolog-errors}
The following functions allows a C function to raise a Prolog error. Refer
to the section concerning Prolog errors for more information about the
effect of raising an error \RefSP{Errors}.

\subsubsection{Managing the error context}
When one of the following error function is invoked it refers to the
implicit error context \RefSP{General-format-and-error-context}. This
context indicates the name and the arity of the concerned predicate. When
using a \texttt{foreign/2} declaration this context is set by default to the
name and arity of the associated Prolog predicate. This can be controlled
using the \IdxPO{bip\_name} option \RefSP{foreign/2-directive}. In any
case, the following functions can also be used to modify this context:

\begin{Indentation}
\begin{verbatim}
void Pl_Set_C_Bip_Name  (const char *functor, int arity)
void Pl_Unset_C_Bip_Name(void)
\end{verbatim}
\end{Indentation}

The function \texttt{Pl\_Set\_C\_Bip\_Name(functor, arity)} initializes the
context of the error with \texttt{functor} and \texttt{arity} (if
\texttt{arity}$<$0 only \texttt{functor} is significant). The function
\texttt{Pl\_Unset\_C\_Bip\_Name()} removes such an initialization (the context
is then reset to the last \texttt{Functor}/\texttt{Arity} set by a call to
\IdxPB{set\_bip\_name/2} \RefSP{set-bip-name/2}. This is useful when
writing a C routine to define a context for errors occurring in this routine
and, before exiting to restore the previous context.

\subsubsection{Instantiation error}
The following function raises an instantiation error \RefSP{Instantiation-error}:

\OneLine{void Pl\_Err\_Instantiation(void)}

\subsubsection{Uninstantiation error}
The following function raises an uninstantiation error \RefSP{Uninstantiation-error}:

\OneLine{void Pl\_Err\_Uninstantiation( PlTerm culprit)}

\subsubsection{Type error}
The following function raises a type error \RefSP{Type-error}:

\OneLine{void Pl\_Err\_Type(int atom\_type, PlTerm culprit)}

\texttt{atom\_type} is (the internal key of) the atom associated with the
expected type. For each type name \Param{T} there is a
corresponding predefined atom stored in a global variable whose name is of
the form \texttt{pl\_type\_\Param{T}}. \texttt{culprit} is the argument which
caused the error.

\SPart{Example}: \texttt{x} is an atom while an integer was expected:
\texttt{Pl\_Err\_Type(pl\_type\_integer, x)}.

\subsubsection{Domain error}
The following function raises a domain error \RefSP{Domain-error}:

\OneLine{void Pl\_Err\_Domain(int atom\_domain, PlTerm culprit)}

\texttt{atom\_domain} is (the internal key of) the atom associated with the
expected domain. For each domain name \Param{D} there is a
corresponding predefined atom stored in a global variable whose name is of
the form \texttt{domain\_\Param{D}}. \texttt{culprit} is the argument which
caused the error.

\SPart{Example}: \texttt{x} is $<$ 0 but should be $\geq$ 0:
\texttt{Pl\_Err\_Domain(pl\_domain\_not\_less\_than\_zero, x)}.

\subsubsection{Existence error}
The following function raises an existence error \RefSP{Existence-error}:

\OneLine{void Pl\_Err\_Existence(int atom\_object, PlTerm culprit)}

\texttt{atom\_object} is (the internal key of) the atom associated with the
type of the object. For each object name \Param{O} there is a
corresponding predefined atom stored in a global variable whose name is of
the form \texttt{pl\_existence\_\Param{O}}. \texttt{culprit} is the argument
which caused the error.

\SPart{Example}: \texttt{x} does not refer to an existing source:
\texttt{Pl\_Err\_Existence(pl\_existence\_source\_sink, x)}.

\subsubsection{Permission error}
The following function raises a permission error \RefSP{Permission-error}:

\OneLine{void Pl\_Err\_Permission(int atom\_operation, int atom\_permission,
PlTerm culprit)}

\texttt{atom\_operation} is (the internal key of) the atom associated with the
operation which caused the error. For each operation name
\Param{O} there is a corresponding predefined atom stored in a
global variable whose name is of the form
\texttt{pl\_permission\_operation\_\Param{O}}. \texttt{atom\_permission} is
(the internal key of) the atom associated with the tried permission. For each
permission name \Param{P} there is a corresponding predefined atom
stored in a global variable whose name is of the form
\texttt{pl\_permission\_type\_\Param{P}}. \texttt{culprit} is the argument
which caused the error.

\SPart{Example}: reading from an output stream \texttt{x}:
\texttt{Pl\_Err\_Permission(pl\_permission\_operation\_input, \\
pl\_permission\_type\_stream, x)}.

\subsubsection{Representation error}
The following function raises a representation error \RefSP{Representation-error}:

\OneLine{void Pl\_Err\_Representation(int atom\_limit)}

\texttt{atom\_limit} is (the internal key of) the atom associated with the
reached limit. For each limit name \Param{L} there is a
corresponding predefined atom stored in a global variable whose name is of
the form \texttt{pl\_representation\_\Param{L}}.

\SPart{Example}: an arity too big occurs:
\texttt{Pl\_Err\_Representation(pl\_representation\_max\_arity)}.

\subsubsection{Evaluation error}
The following function raises an evaluation error \RefSP{Evaluation-error}:

\OneLine{void Pl\_Err\_Evaluation(int atom\_error)}

\texttt{atom\_error} is (the internal key of) the atom associated with the
error. For each evaluation error name \Param{E} there is a
corresponding predefined atom stored in a global variable whose name is of
the form \texttt{pl\_evaluation\_\Param{E}}.

\SPart{Example}: a division by zero occurs:
\texttt{Pl\_Err\_Evaluation(pl\_evaluation\_zero\_divisor)}.

\subsubsection{Resource error}
The following function raises a resource error \RefSP{Resource-error}:

\OneLine{void Pl\_Err\_Resource(int atom\_resource)}

\texttt{atom\_resource} is (the internal key of) the atom associated with the
resource. For each resource error name \Param{R} there is a
corresponding predefined atom stored in a global variable whose name is of
the form \texttt{pl\_resource\_\Param{R}}.

\SPart{Example}: too many open streams:
\texttt{Pl\_Err\_Resource(pl\_resource\_too\_many\_open\_streams)}.

\subsubsection{Syntax error}
The following function raises a syntax error \RefSP{Syntax-error}:

\OneLine{void Pl\_Err\_Syntax(int atom\_error)}

\texttt{atom\_error} is (the internal key of) the atom associated with the
error. There is no predefined syntax error atoms.

\SPart{Example}: a \texttt{/} is expected:
\texttt{Pl\_Err\_Syntax(Pl\_Create\_Atom("/ expected"))}.

The following function emits a syntax error according to the value of the
\IdxPF{syntax\_error} \Idx{Prolog flag} \RefSP{set-prolog-flag/2}. This
function can then return (if the value of the flag is either
\texttt{warning} or \texttt{fail}). In that case the calling function should
fail (e.g. returning \texttt{PL\_FALSE}). This function accepts a file name (the
empty string C \texttt{""} can be passed), a line and column number and an
error message string. Using this function makes it possible to further call
the built-in predicate \IdxPB{syntax\_error\_info/4}
\RefSP{syntax-error-info/4}:

\OneLine{void Pl\_Emit\_Syntax\_Error(char *file\_name, int line, int column,
char *message)}

\SPart{Example}: a \texttt{/} is expected:
\texttt{Pl\_Emit\_Syntax\_Error("data", 10, 30, "/ expected")}.

\subsubsection{System error}
The following function raises a system error (4.3.11, page *):

\OneLine{void Pl\_Err\_System(int atom\_error)}

\texttt{atom\_error} is (the internal key of) the atom associated with the
error. There is no predefined system error atoms.

\SPart{Example}: an invalid pathname is given:
\texttt{Pl\_Err\_System(Pl\_Create\_Atom("invalid path name"))}.

The following function emits a system error associated with an operating
system error according to the value of the \IdxPF{os\_error} \Idx{Prolog
  flag} \RefSP{set-prolog-flag/2}. This function can then return (if the
value of the flag is either \texttt{warning} or \texttt{fail}). In that case
the calling function should fail (e.g. returning \texttt{PL\_FALSE}).

The following function uses the value of the \texttt{errno} C library
variable (basically it calls \texttt{Pl\_Err\_System} with the result
of \texttt{strerror(errno)}).

\OneLine{void Pl\_Os\_Error(void)}

\SPart{Example}: if a call to the C Unix function \texttt{chdir(2)} returns
\texttt{-1} then call \texttt{Os\_Error()}.


\subsection{Calling Prolog from C}

\subsubsection{Introduction}
The following functions allows a C function to call a Prolog predicate:

\begin{Indentation}
\begin{verbatim}
void   Pl_Query_Begin        (PlBool recoverable)
int    Pl_Query_Call         (int functor, int arity, PlTerm *arg)
int    Pl_Query_Start        (int functor, int arity, PlTerm *arg,
                              PlBool recoverable)
int    Pl_Query_Next_Solution(void)
void   Pl_Query_End          (int op)
PlTerm Pl_Get_Exception      (void)
void   Pl_Exec_Continuation  (int functor, int arity, PlTerm *arg)
void   Pl_Throw              (PlTerm ball)
\end{verbatim}
\end{Indentation}

The invocation of a Prolog predicate should be done as follows:

\begin{itemize}

\item open a query using \texttt{Pl\_Query\_Begin()}

\item compute the first solution using \texttt{Pl\_Query\_Call()}

\item eventually compute next solutions using
\texttt{Pl\_Query\_Next\_Solution()}

\item close the query using \texttt{Pl\_Query\_End()}

\end{itemize}

The function \texttt{Pl\_Query\_Begin(recoverable)} is used to initialize a
query. The argument \texttt{recoverable} shall be set to \texttt{PL\_TRUE} if
the user wants to recover, at the end of the query, the memory space consumed
by the query (in that case an additional choice-point is created). All terms
created in the heap, e.g. using \texttt{Pl\_Mk\_...}  family functions
\RefSP{Creating-Prolog-terms}, after the invocation of
\texttt{Pl\_Query\_Begin()} can be recovered when calling
\texttt{Pl\_Query\_End(PL\_TRUE)} (see below).

The function \texttt{Pl\_Query\_Call(functor, arity, arg)} calls a predicate
passing arguments. It is then used to compute the first solution. The
arguments \texttt{functor}, \texttt{arity} and \texttt{arg} are similar to
those of the functions handling complex terms
\RefSP{Introduction:(Manipulating-Prolog-terms)}. This function returns:

\begin{itemize}

\item \texttt{PL\_FAILURE} (a constant equal to \texttt{PL\_FALSE}, i.e. 0) if
the query fails.

\item \texttt{PL\_SUCCESS} (a constant equal to \texttt{PL\_TRUE}, i.e. 1) in
case of success. In that case the argument array \texttt{arg} can be used to
obtain the unification performed by the query.

\item \texttt{PL\_EXCEPTION} (a constant equal to 2). In that case function
\texttt{Pl\_Get\_Exception()} can be used to obtained the exceptional term
raised by \IdxCC{throw/1} \RefSP{catch/3}.

\end{itemize}

The function \texttt{Pl\_Query\_Start(functor, arity, arg, recoverable)} is a
shorthand equivalent to a call to \texttt{Pl\_Query\_Begin(recoverable)} followed by
a call to \texttt{Pl\_Query\_Call(functor, arity, arg)}.

The function \texttt{Pl\_Query\_Next\_Solution()} is used to compute a new
solution. It must be only used if the result of the previous solution was
\texttt{PL\_SUCCESS}. This functions returns the same kind of values as
\texttt{Pl\_Query\_Call()} (see above).

The function \texttt{Pl\_Query\_End(op)} is used to finish a query. This
function mainly manages the remaining alternatives of the query. However,
even if the query has no alternatives this function must be used to
correctly finish the query. The value of \texttt{op} is:

\begin{itemize}

\item \texttt{PL\_RECOVER}: to recover the memory space consumed by the
query. After that the state of Prolog stacks is exactly the same as before
opening the query. To use this option the query must have been initialized
specifying \texttt{PL\_TRUE} for \texttt{recoverable} (see above).

\item \texttt{PL\_CUT}: to cut remaining alternatives. The effect of this
option is similar to a cut after the query.

\item \texttt{PL\_KEEP\_FOR\_PROLOG}: to keep the alternatives for Prolog.
This is useful when the query was invoked in a foreign C function. In that
case, when the predicate corresponding to the C foreign function is invoked
a query is executed and the remaining alternatives are then available as
alternatives of that predicate.

\end{itemize}

Note that several queries can be nested since a stack of queries is
maintained. For instance, it is possible to call a query and before
terminating it to call another query. In that case the first execution of
\texttt{Pl\_Query\_End()} will finish the second query (i.e. the inner) and
the next execution of \texttt{Pl\_Query\_End()} will finish the first query.

The function \texttt{Pl\_Exec\_Continuation(functor, arity, arg)}
replaces the current calculus by the execution of the specified
predicate. The arguments \texttt{functor}, \texttt{arity} and \texttt{arg}
are similar to those of the functions handling complex terms
\RefSP{Introduction:(Manipulating-Prolog-terms)}.

Finally the function \texttt{Pl\_Throw(ball)} throws an exception. See the
\IdxCC{throw/1} control construct for more information on exceptions
\RefSP{catch/3}. Note that \texttt{Pl\_Throw(ball)} is logically equivalent (but
faster)
to \texttt{Pl\_Exec\_Continuation(Pl\_Find\_Atom("throw"), 1, \&ball)} .

\subsubsection{Example: \texttt{my\_call/1} - a \texttt{call/1} clone}

We here define a predicate \texttt{my\_call(Goal)} which acts like
\texttt{call(Goal)} except that we do not handle exceptions (if an exception
occurs the goal simply fails):

In the prolog file \texttt{examp.pl}:

\OneLine{:- foreign(my\_call(term)).}

In the C file \texttt{examp\_c.c}:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include <gprolog.h>

PlBool
my_call(PlTerm goal)

{
  PlTerm *arg;
  int functor, arity;
  int result;

  arg = Pl_Rd_Callable_Check(goal, &functor, &arity);
  Pl_Query_Begin(PL_FALSE);
  result = Pl_Query_Call(functor, arity, arg);
  Pl_Query_End(PL_KEEP_FOR_PROLOG);
  return (result == PL_SUCCESS);
}
\end{verbatim}
\end{Indentation}

The compilation produces an executable called \texttt{examp}:

\OneLine{\% gplc examp.pl examp\_c.c}

Examples of use:

\begin{CodeTwoCols}
\One{| ?- my\_call(write(hello)).}
\One{hello}
\SkipLine
\One{| ?- my\_call(for(X,1,3)).}
\SkipLine
\Two{X = 1 ?}{(here the user presses \texttt{;} to compute another solution)}
\SkipLine
\Two{X = 2 ?}{(here the user presses \texttt{;} to compute another solution)}
\SkipLine
\Two{X = 3}{(here the user is not prompted since there is no more alternative)}
\SkipLine
\One{| ?- my\_call(1).}
\One{{\lb}exception:~error(type\_error(callable,1),my\_call/1){\rb}}
\SkipLine
\One{| ?- my\_call(call(1)).}
\SkipLine
\One{no}
\end{CodeTwoCols}

When \texttt{my\_call(1)} is called an error is raised due to the use of
\texttt{Pl\_Rd\_Callable\_Check()}. However the error raised by
\texttt{my\_call(call(1))} is ignored and \texttt{PL\_FALSE} (i.e. a failure) is
returned by the foreign function.

To really simulate the behavior of \texttt{call/1} when an exception
is recovered it should be re-raised to be captured by an earlier
handler. The idea is then to execute a \texttt{throw/1} as the
continuation. This is what it is done by the following code:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include <gprolog.h>

PlBool
my_call(PlTerm goal)
{
  PlTerm *args;
  int functor, arity;
  int result;

  args = Pl_Rd_Callable_Check(goal, &functor, &arity);
  Pl_Query_Begin(PL_FALSE);
  result = Pl_Query_Call(functor, arity, args);
  Pl_Query_End(PL_KEEP_FOR_PROLOG);
  if (result == PL_EXCEPTION)
    {
      PlTerm except = Pl_Get_Exception();
      Pl_Throw(except); 
      // equivalent to Pl_Exec_Continuation(Find_Atom("throw"), 1, &except);
    }

  return result;
}
\end{verbatim}
\end{Indentation}

The following code propagates the error raised by \texttt{call/1}.

\begin{CodeTwoCols}
\One{| ?- my\_call(call(1)).}
\One{{\lb}exception:~error(type\_error(callable,1),my\_call/1){\rb}}
\end{CodeTwoCols}

Finally note that a simpler way to define \texttt{my\_call/1} is to use
\texttt{Pl\_Exec\_Continuation()} as follows:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include <gprolog.h>

PlBool
my_call(PlTerm goal)
{
  PlTerm *args;
  int functor, arity;

  args = Pl_Rd_Callable_Check(goal, &functor, &arity);
  Pl_Exec_Continuation(functor, arity, args);
  return PL_TRUE;
}
\end{verbatim}
\end{Indentation}

\subsubsection{Example: recovering the list of all operators}

We here define a predicate \texttt{all\_op(List)} which unifies
\texttt{List} with the list of all currently defined operators as would be done by: \texttt{findall(X,current\_op(\_,\_,X),List)}.

In the prolog file \texttt{examp.pl}:

\OneLine{:- foreign(all\_op(term)).}

In the C file \texttt{examp\_c.c}:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include <gprolog.h>

PlBool
all_op(PlTerm list)
{
  PlTerm op[1024];
  PlTerm args[3];
  int n = 0;
  int result;

  Pl_Query_Begin(PL_TRUE);
  args[0] = Pl_Mk_Variable();
  args[1] = Pl_Mk_Variable();
  args[2] = Pl_Mk_Variable();
  result = Pl_Query_Call(Find_Atom("current_op"), 3, args);
  while (result)
    {
      op[n++] = Pl_Mk_Atom(Pl_Rd_Atom(args[2])); /* arg[2]: the name of the op */
      result = Pl_Query_Next_Solution();
    }
  Pl_Query_End(PL_RECOVER);

  return Pl_Un_Proper_List_Check(n, op, list);
}
\end{verbatim}
\end{Indentation}

Note that we know here that there is no source for exception. In that case
the result of \texttt{Pl\_Query\_Call} and \texttt{Pl\_Query\_Next\_Solution}
can be considered as a boolean.

The compilation produces an executable called \texttt{examp}:

\OneLine{\% gplc examp.pl examp\_c.c}

Example of use:

\begin{Indentation}
\begin{verbatim}
| ?- all_op(L).

L = [:-,:-,\=,=:=,#>=,#<#,@>=,-->,mod,#>=#,**,*,+,+,',',...]

| ?- findall(X,current_op(_,_,X),L).

L = [:-,:-,\=,=:=,#>=,#<#,@>=,-->,mod,#>=#,**,*,+,+,',',...]
\end{verbatim}
\end{Indentation}


\subsection{Defining a new C \texttt{main()} function}

GNU Prolog allows the user to define his own \IdxK{main()}
function. This can be useful to perform several tasks before starting
the Prolog engine. To do this simply define a classical
\texttt{main(argc, argv)} function. The following functions can then be used:

\begin{Indentation}
\begin{verbatim}
int    Pl_Start_Prolog         (int argc, char *argv[])
void   Pl_Stop_Prolog          (void)
void   Pl_Reset_Prolog         (void)
PlBool Pl_Try_Execute_Top_Level(void)
\end{verbatim}
\end{Indentation}

The function \texttt{Pl\_Start\_Prolog(argc, argv)} initializes the Prolog
engine (\texttt{argc} and \texttt{argv} are the command-line variables). This
function collects all linked objects (issued from the compilation of Prolog
files) and initializes them. The initialization of a Prolog object file
consists in adding to appropriate tables new atoms, new predicates and
executing its system directives. A system directive is generated by the
Prolog to WAM compiler to reflect a (user) directive executed at compile-time
such as \texttt{op/3} \RefSP{op/3}. Indeed, when the compiler encounters such
a directive it immediately executes it and also generates a system directive
to execute it at the start of the executable.  When all system directives
have been executed the Prolog engine executes all initialization directives
defined with \IdxDi{initialization/1}
\RefSP{initialization/1}. The function returns the number of user
directives (i.e. \texttt{initialization/1}) executed. This function must be
called only once.

The function \texttt{Pl\_Stop\_Prolog()} stops the Prolog engine. This function
must be called only once after all Prolog treatment have been done.

The function \texttt{Pl\_Reset\_Prolog()} reinitializes the Prolog engine
(i.e. reset all Prolog stacks).

The function \texttt{Pl\_Try\_Execute\_Top\_Level()} executes the
\Idx{top-level} if linked \RefSP{Using-the-compiler} and returns
\texttt{PL\_TRUE}. If the top-level is not present the functions returns
\texttt{PL\_FALSE}.

Here is the definition of the default GNU Prolog \texttt{main()} function:

\begin{Indentation}
\begin{verbatim}
static int
Main_Wrapper(int argc, char *argv[])
{
  int nb_user_directive;
  PlBool top_level;

  nb_user_directive = Pl_Start_Prolog(argc, argv);

  top_level = Pl_Try_Execute_Top_Level();

  Pl_Stop_Prolog();

  if (top_level || nb_user_directive)
    return 0;

  fprintf(stderr,
          "Warning: no initial goal executed\n"
          "   use a directive :- initialization(Goal)\n"
          "   or remove the link option --no-top-level"
          " (or --min-bips or --min-size)\n");

  return 1;
}

int
main(int argc, char *argv[])
{
  return Main_Wrapper(argc, argv);
}
\end{verbatim}
\end{Indentation}

Note that under some circumstances it is necessary to encapsulate the code of
\texttt{main()} inside an intermediate function called by
\texttt{main()}. Indeed, some C compilers (e.g. gcc) treats \texttt{main()}
particularly, producing an incompatible code w.r.t GNU Prolog. So it is a
good idea to always use a wrapper function as shown above.

\subsubsection{Example: asking for ancestors}

In this example we use the following Prolog code (in a file called
\texttt{new\_main.pl}):

\begin{Indentation}
\begin{verbatim}
parent(bob,   mary).
parent(jane,  mary).
parent(mary,  peter).
parent(paul,  peter).
parent(peter, john).

anc(X, Y):-
        parent(X, Y).

anc(X, Z) :-
        parent(X, Y),
        anc(Y, Z).
\end{verbatim}
\end{Indentation}

The following file (called \texttt{new\_main\_c.c}) defines a \texttt{main()}
function read the name of a person and displaying all successors of that
person. This is equivalent to the Prolog query: \texttt{anc(Result, Name)}.

\begin{Indentation}
\begin{verbatim}
static int
Main_Wrapper(int argc, char *argv[])
{
  int func;
  PlTerm arg[10];
  char str[100];
  char *sol[100];
  int i, nb_sol = 0;
  PlBool res;

  Pl_Start_Prolog(argc, argv);

  func = Pl_Find_Atom("anc");
  for (;;)
    {
      printf("\nEnter a name (or 'end' to finish): ");
      fflush(stdout);
      scanf("%s", str);

      if (strcmp(str, "end") == 0)
	break;

      Pl_Query_Begin(PL_TRUE);

      arg[0] = Pl_Mk_Variable();
      arg[1] = Pl_Mk_String(str);
      nb_sol = 0;
      res = Pl_Query_Call(func, 2, arg);
      while (res)
	{
	  sol[nb_sol++] = Pl_Rd_String(arg[0]);
	  res = Pl_Query_Next_Solution();
	}
      Pl_Query_End(PL_RECOVER);

      for (i = 0; i < nb_sol; i++)
	printf("  solution: %s\n", sol[i]);
      printf("%d solution(s)\n", nb_sol);
    }

  Pl_Stop_Prolog();
  return 0;
}

int
main(int argc, char *argv[])
{
  return Main_Wrapper(argc, argv);
}
\end{verbatim}
\end{Indentation}

The compilation produces an executable called \texttt{new\_main}:

\OneLine{\% gplc new\_main.pl new\_main\_c.c}

Examples of use:

\begin{Indentation}
\begin{verbatim}
Enter a name (or 'end' to finish): john
  solution: peter
  solution: bob
  solution: jane
  solution: mary
  solution: paul
5 solution(s)

Enter a name (or 'end' to finish): mary
  solution: bob
  solution: jane
2 solution(s)

Enter a name (or 'end' to finish): end
\end{verbatim}
\end{Indentation}

%HEVEA\cutend