Did you know ... | Search Documentation: |
A C++ interface to SWI-Prolog (Version 1) |
C++ provides a number of features that make it possible to define a much more natural and concise interface to dynamically typed languages than plain C does. Using programmable type-conversion (casting), native data-types can be translated automatically into appropriate Prolog types, automatic destructors can be used to deal with most of the cleanup required and C++ exception handling can be used to map Prolog exceptions and interface conversion errors to C++ exceptions, which are automatically mapped to Prolog exceptions as control is turned back to Prolog.
Volker Wysk has defined an alternative C++ mapping based on templates and compatible to the STL framework. See http://www.volker-wysk.de/swiprolog-c++/index.html.
I would like to thank Anjo Anjewierden for comments on the definition, implementation and documentation of this package.
The most useful area for exploiting C++ features is type-conversion.
Prolog variables are dynamically typed and all information is passed
around using the C-interface type term_t
. In C++, term_t
is embedded in the lightweight class PlTerm.
Constructors and operator definitions provide flexible operations and
integration with important C-types (char *
, wchar_t*
,
long
and double
).
The list below summarises the classes defined in the C++ interface.
[]
operator is overloaded to access elements in this vector. PlTermv
is used to build complex terms and provide argument-lists to Prolog
goals.type_error
exception.domain_error
exception.existence_error
exception.permission_error
exception.The required C(++) function header and registration of a predicate is arranged through a macro called PREDICATE().
Before going into a detailed description of the C++ classes we present a few examples illustrating the‘feel’of the interface.
This simple example shows the basic definition of the predicate hello/1 and how a Prolog argument is converted to C-data:
PREDICATE(hello, 1) { cout << "Hello " << (char *)A1 << endl; return TRUE; }
The arguments to PREDICATE()
are the name and arity of the predicate. The macros A<n>
provide access to the predicate arguments by position and are of the
type PlTerm. Casting a PlTerm
to a
char *
or wchar_t *
provides the natural
type-conversion for most Prolog data-types, using the output of write/1
otherwise:
?- hello(world). Hello world Yes ?- hello(X) Hello _G170 X = _G170
This example shows arithmetic using the C++ interface, including unification, type-checking and conversion. The predicate add/3 adds the two first arguments and unifies the last with the result.
PREDICATE(add, 3) { return A3 = (long)A1 + (long)A2; }
Casting a PlTerm to a long
performs a PL_get_long() and throws a C++ exception if the Prolog
argument is not a Prolog integer or float that can be converted without
loss to a long
. The
operator of PlTerm
is defined to perform unification and returns =
TRUE
or FALSE
depending on the result.
?- add(1, 2, X). X = 3. ?- add(a, 2, X). [ERROR: Type error: `integer' expected, found `a'] Exception: ( 7) add(a, 2, _G197) ?
This example is a bit harder. The predicate average/3 is defined to take the template average(+Var, :Goal, -Average) , where Goal binds Var and will unify Average with average of the (integer) results.
PlQuery takes the name of a
predicate and the goal-argument vector as arguments. From this
information it deduces the arity and locates the predicate. the
member-function next_solution() yields
TRUE
if there was a solution and FALSE
otherwise. If the goal yielded a Prolog exception it is mapped into a
C++ exception.
PREDICATE(average, 3) { long sum = 0; long n = 0; PlQuery q("call", PlTermv(A2)); while( q.next_solution() ) { sum += (long)A1; n++; } return A3 = (double)sum/(double)n; }
As we have seen from the examples, the PlTerm class plays a central role in conversion and operating on Prolog data. This section provides complete documentation of this class.
void *
.
PREDICATE(make_my_object, 1) { myclass *myobj = new myclass(); return A1 = (void *)myobj; } PREDICATE(free_my_object, 1) { myclass *myobj = (void *)A1; delete(myobj); return TRUE; }
PlTerm
can be cast to the following types:
long
if the PlTerm
is a Prolog integer or float that can be converted without loss to a
long. throws a
type_error
exception otherwise.long
, but might represent fewer bits.CVT_ALL|CVT_WRITE|BUF_RING
, which implies Prolog atoms and
strings are converted to the represented text. All other data is handed
to write/1. If
the text is static in Prolog, a direct pointer to the string is
returned. Otherwise the text is saved in a ring of 16 buffers and must
be copied to avoid overwriting.
=
is defined for the Types PlTerm,
long
, double
, char *
, wchar_t*
and
PlAtom. It performs Prolog
unification and returns TRUE
if successful and FALSE
otherwise.
The boolean return-value leads to somewhat unconventional-looking code as normally, assignment returns the value assigned in C. Unification however is fundamentally different to assignment as it can succeed or fail. Here is a common example.
PREDICATE(hostname, 1) { char buf[32]; if ( gethostname(buf, sizeof(buf)) == 0 ) return A1 = buf; return FALSE; }
long
and perform standard C-comparison between the two long integers. If PlTerm
cannot be converted a type_error
is raised.TRUE
if the PlTerm
is an atom or string representing the same text as the argument, FALSE
if the conversion was successful, but the strings are not equal and an
type_error
exception if the conversion failed.Below are some typical examples. See section 1.6 for direct manipulation of atoms in their internal representation.
A1 < 0 | Test A1 to hold a Prolog integer or float that can be transformed lossless to an integer less than zero. |
A1 < PlTerm(0) | A1
is before the term‘0’in the‘standard order of terms’.
This means that if A1 represents an atom, this test yields TRUE . |
A1 == PlCompound("a(1)") | Test A1
to represent the term
a(1) . |
A1 == "now" | Test A1 to be an atom or string holding the text “now” . |
Compound terms can be viewed as an array of terms with a name and
arity (length). This view is expressed by overloading the
operator.
[]
A type_error
is raised if the argument is not compound
and a
domain_error
if the index is out of range.
In addition, the following functions are defined:
type_error
is raised. Id arg is out of range, a
domain_error
is raised. Please note the counting from 1
which is consistent to Prolog's arg/3
predicate, but inconsistent to C's normal view on an array. See also
class PlCompound. The following
example tests x to represent a term with first-argument an
atom or string equal to gnat
.
..., if ( x[1] == "gnat" ) ...
const char *
holding the name of the functor of
the compound term. Raises a type_error
if the argument is
not compound.type_error
if the argument is not compound.
PL_VARIABLE
, PL_FLOAT
, PL_INTEGER
,
PL_ATOM
, PL_STRING
or PL_TERM
To avoid very confusing combinations of constructors and therefore possible undesirable effects a number of subclasses of PlTerm have been defined that provide constructors for creating special Prolog terms. These subclasses are defined below.
A SWI-Prolog string represents a byte-string on the global stack. It's lifetime is the same as for compound terms and other data living on the global stack. Strings are not only a compound representation of text that is garbage-collected, but as they can contain 0-bytes, they can be used to contain arbitrary C-data structures.
Character lists are compliant to Prolog's atom_chars/2 predicate.
syntax_error
exception is raised. Otherwise a new
term-reference holding the parsed text is created.hello(world)
.
PlCompound("hello", PlTermv("world"))
The class PlTail is both for analysing and constructing lists. It is called PlTail as enumeration-steps make the term-reference follow the‘tail’of the list.
"gnat"
,
a list of the form [gnat|B]
is created and the PlTail
object now points to the new variable B.
This function returns TRUE
if the unification succeeded
and
FALSE
otherwise. No exceptions are generated.
The example below translates the main() argument vector to Prolog and calls the prolog predicate entry/1 with it.
int main(int argc, char **argv) { PlEngine e(argv[0]); PlTermv av(1); PlTail l(av[0]); for(int i=0; i<argc; i++) l.append(argv[i]); l.close(); PlQuery q("entry", av); return q.next_solution() ? 0 : 1; }
[]
and returns the
result of the unification.TRUE
on success and FALSE
if
PlTail represents the empty list.
If PlTail is neither a list nor the
empty list, a type_error
is thrown. The example below
prints the elements of a list.
PREDICATE(write_list, 1) { PlTail tail(A1); PlTerm e; while(tail.next(e)) cout << (char *)e << endl; return TRUE; }
The class PlTermv represents an array of term-references. This type is used to pass the arguments to a foreignly defined predicate, construct compound terms (see PlTerm::PlTerm(const char *name, PlTermv arguments)) and to create queries (see PlQuery).
The only useful member function is the overloading of
,
providing (0-based) access to the elements. Range checking is performed
and raises a []
domain_error
exception.
The constructors for this class are below.
load_file(const char *file) { return PlCall("compile", PlTermv(file)); }
If the vector has to contain more than 5 elements, the following construction should be used:
{ PlTermv av(10); av[0] = "hello"; ...
Both for quick comparison as for quick building of lists of atoms, it is desirable to provide access to Prolog's atom-table, mapping handles to unique string-constants. If the handles of two atoms are different it is guaranteed they represent different text strings.
Suppose we want to test whether a term represents a certain atom, this interface presents a large number of alternatives:
Example:
PREDICATE(test, 1) { if ( A1 == "read" ) ...;
This writes easily and is the preferred method is performance is not critical and only a few comparisons have to be made. It validates A1 to be a term-reference representing text (atom, string, integer or float) extracts the represented text and uses strcmp() to match the strings.
Example:
static PlAtom ATOM_read("read"); PREDICATE(test, 1) { if ( A1 == ATOM_read ) ...;
This case raises a type_error
if A1 is not an
atom. Otherwise it extacts the atom-handle and compares it to the
atom-handle of the global PlAtom
object. This approach is faster and provides more strict type-checking.
Example:
static PlAtom ATOM_read("read"); PREDICATE(test, 1) { PlAtom a1(A1); if ( a1 == ATOM_read ) ...;
This approach is basically the same as section 1.6, but in nested if-then-else the extraction of the atom from the term is done only once.
Example:
PREDICATE(test, 1) { PlAtom a1(A1); if ( a1 == "read" ) ...;
This approach extracts the atom once and for each test extracts the represented string from the atom and compares it. It avoids the need for global atom constructors.
type_error
is thrown.TRUE
if the atom represents text, FALSE
otherwise. Performs a strcmp() for this.TRUE
or
FALSE
.
This class encapsulates PL_register_foreign(). It is defined as a class rather then a function to exploit the C++ global constructor feature. This class provides a constructor to deal with the PREDICATE() way of defining foreign predicates as well as constructors to deal with more conventional foreign predicate definitions.
PL_FA_VARARGS
calling convention, where the argument
list of the predicate is passed using an array of term_t
objects as returned by PL_new_term_refs(). This interface poses
no limits on the arity of the predicate and is faster, especially for a
large number of arguments.static foreign_t pl_hello(PlTerm a1) { ... } PlRegister x_hello_1(NULL, "hello", 1, pl_hello);
This construct is currently supported upto 3 arguments.
This class encapsulates the call-backs onto Prolog.
user
.TRUE
if
successful and FALSE
if there are no (more) solutions.
Prolog exceptions are mapped to C++ exceptions.Below is an example listing the currently defined Prolog modules to the terminal.
PREDICATE(list_modules, 0) { PlTermv av(1); PlQuery q("current_module", av); while( q.next_solution() ) cout << (char *)av[0] << endl; return TRUE; }
In addition to the above, the following functions have been defined.
The class PlFrame provides an interface to discard unused term-references as well as rewinding unifications (data-backtracking). Reclaiming unused term-references is automatically performed after a call to a C++-defined predicate has finished and returns control to Prolog. In this scenario PlFrame is rarely of any use. This class comes into play if the toplevel program is defined in C++ and calls Prolog multiple times. Setting up arguments to a query requires term-references and using PlFrame is the only way to reclaim them.
A typical use for PlFrame is the definition of C++ functions that call Prolog and may be called repeatedly from C++. Consider the definition of assertWord(), adding a fact to word/1:
void assertWord(const char *word) { PlFrame fr; PlTermv av(1); av[0] = PlCompound("word", PlTermv(word)); PlQuery q("assert", av); q.next_solution(); }
This example shows the most sensible use of PlFrame if it is used in the context of a foreign predicate. The predicate's thruth-value is the same as for the Prolog unification (=/2), but has no side effects. In Prolog one would use double negation to achieve this.
PREDICATE(can_unify, 2) { PlFrame fr; int rval = (A1=A2); fr.rewind(); return rval; }
The PREDICATE macro is there to make your code look nice, taking care of the interface to the C-defined SWI-Prolog kernel as well as mapping exceptions. Using the macro
PREDICATE(hello, 1)
is the same as writing:
static foreign_t pl_hello__1(PlTermv PL_av); static foreign_t _pl_hello__1(term_t t0, int arity, control_t ctx) { (void)arity; (void)ctx; try { return pl_hello__1(PlTermv(1, t0)); } catch ( PlTerm &ex ) { return ex.raise(); } } static PlRegister _x_hello__1("hello", 1, _pl_hello__1); static foreign_t pl_hello__1(PlTermv PL_av)
The first function converts the parameters passed from the Prolog kernel to a PlTermv instance and maps exceptions raised in the body to Prolog exceptions. The PlRegister global constructor registers the predicate. Finally, the function header for the implementation is created.
The PREDICATE() macros has a number of variations that deal with special cases.
PL_av
is not used.NAMED_PREDICATE("#", hash, 2) { A2 = (wchar_t*)A1; }
SWI-cpp.h
. FIXME: Needs cleanup and an example.
With no special precautions, the predicates are defined into the
module from which load_foreign_library/1
was called, or in the module
user
if there is no Prolog context from which to deduce the
module such as while linking the extension statically with the Prolog
kernel.
Alternatively, before loading the SWI-Prolog include file, the macro PROLOG_MODULE may be defined to a string containing the name of the destination module. A module name may only contain alpha-numerical characters (letters, digits, _). See the example below:
#define PROLOG_MODULE "math" #include <SWI-Prolog.h> #include <math.h> PREDICATE(pi, 1) { A1 = M_PI; }
?- math:pi(X). X = 3.14159
Prolog exceptions are mapped to C++ exceptions using the subclass PlException of PlTerm to represent the Prolog exception term. All type-conversion functions of the interface raise Prolog-compliant exceptions, providing decent error-handling support at no extra work for the programmer.
For some commonly used exceptions, subclasses of PlException have been created to exploit both their constructors for easy creation of these exceptions as well as selective trapping in C++. Currently, these are PlTypeEror and PlDomainError.
To throw an exception, create an instance of PlException and use throw().
char *data = "users"; throw PlException(PlCompound("no_database", PlTerm(data)));
The C++ model of exceptions and the Prolog model of exceptions are
different. Wherever the underlying function returns a "fail" return
code, the C++ API does a further check for whether there's an exception
and, if so, does a C++ throw
of a PlException
object. You can use C++ try-catch to intercept this and examine the
This subclass of PlTerm is used to represent exceptions. Currently defined methods are:
...; try { PlCall("consult(load)"); } catch ( PlException &ex ) { cerr << (char *) ex << endl; }
error(type_error(Expected, Actual)
, Context)
PlException::cppThrow() throws a PlTypeEror exception. This ensures consistency in the exception-class whether the exception is generated by the C++-interface or returned by Prolog.
The following example illustrates this behaviour:
PREDICATE(call_atom, 1) { try { return PlCall((char *)A1); } catch ( PlTypeError &ex ) { cerr << "Type Error caugth in C++" << endl; cerr << "Message: \"" << (char *)ex << "\"" << endl; return FALSE; } }
A type error expresses that a term does not satisfy the expected basic Prolog type.
A domain error expresses that a term satisfies the basic
Prolog type expected, but is unacceptable to the restricted domain
expected by some operation. For example, the standard Prolog open/3
call expect an io_mode
(read, write, append, ...). If an
integer is provided, this is a type error, if an atom other
than one of the defined io-modes is provided it is a domain error.
Most of the above assumes Prolog is‘in charge’of the application and C++ is used to add functionality to Prolog, either for accessing external resources or for performance reasons. In some applications, there is a main-program and we want to use Prolog as a logic server. For these applications, the class PlEngine has been defined.
Only a single instance of this class can exist in a process. When used in a multi-threading application, only one thread at a time may have a running query on this engine. Applications should ensure this using proper locking techniques.1For Unix, there is a multi-threaded version of SWI-Prolog. In this version each thread can create and destroy a thread-engine. There is currently no C++ interface defined to access this functionality, though ---of course--- you can use the C-functions.
argv[0]
from its main function, which is needed in the Unix version to find the
running executable. See PL_initialise() for details.argv[0]
.Section 1.4.11 has a simple example using this class.
Not all functionality of the C-interface is provided, but as
PlTerm and term_t
are
essentially the same thing with automatic type-conversion between the
two, this interface can be freely mixed with the functions defined for
plain C.
Using this interface rather than the plain C-interface requires a
little more resources. More term-references are wasted (but reclaimed on
return to Prolog or using PlFrame).
Use of some intermediate types (functor_t
etc.) is not
supported in the current interface, causing more hash-table lookups.
This could be fixed, at the price of slighly complicating the interface.
The mechanisms outlined in this document can be used for static linking with the SWI-Prolog kernel using swipl-ld(1). In general the C++ linker should be used to deal with the C++ runtime libraries and global constructors.
The current interface is entirely defined in the .h
file
using inlined code. This approach has a few advantages: as no C++ code
is in the Prolog kernel, different C++ compilers with different
name-mangling schemas can cooperate smoothly.
Also, changes to the header file have no consequences to binary compatibility with the SWI-Prolog kernel. This makes it possible to have different versions of the header file with few compatibility consequences.
In this document, we presented a high-level interface to Prolog exploiting automatic type-conversion and exception-handling defined in C++.
Programming using this interface is much more natural and requires only little extra resources in terms of time and memory.
Especially the smooth integration between C++ and Prolog exceptions reduce the coding effort for type checking and reporting in foreign predicates.