\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-2021 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)
int     Pl_Rd_C_Int_Check         (PlTerm term)
int     Pl_Rd_C_Int_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}

The function \texttt{Pl\_Rd\_C\_Int\_Check()} is similar to
\texttt{Pl\_Rd\_Integer\_Check()} but returns a C \texttt{int} instead
of a \texttt{PlLong}. If the Prolog integer does not fit into a C
\texttt{int}, a \texttt{representation\_error} is raised (this can
occur on 64-bits machine with \texttt{int} on 32-bits). Similarly for
\texttt{Pl\_Rd\_C\_Int\_Positive\_Check()}.
  
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
