One 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
. Other lightweight classes, such as PlAtom
for
atom_t
are also provided. Constructors and operator
definitions provide flexible operations and integration with important
C-types (char*
, wchar_t*
, long
and
double
), plus the C++-types (std::string
,
std::wstring
). (char*
and wchar_t*
are deprecated in the C++ API; std::string
and
std::wstring
are safer and should be used instead.)
Another useful area is in handling errors and cleanup. Prolog errors can be modeled using C++ exceptions; and C++'s destructors can be used to clean up error situations, to prevent memory and other resource leaks.
See also section 1.6.5 for more on naming conventions and standard methods.
The general philosophy for C++ classes is that a “half-created” object should not be possible - that is, the constructor should either succeed with a completely usable object or it should throw an exception. This API tries to follow that philosophy, but there are some important exceptions and caveats. (For more on how the C++ and Prolog exceptions interrelate, see section 1.15.)
Most of the PL_*() functions have corresponding wrapper methods. For example, PlTerm::get_atom() calls Plx_get_atom(), which calls PL_get_atom(). If the PL_get_atom() has an error, it creates a Prolog error; the Plx_get_atom() wrapper checks for this and converts the error to a C++ exception, which is thrown; upon return to Prolog, the exception is turned back into a Prolog error. Therfore, code typically does not need to check for errors.
Some functions return false
to indicate either failure
or an error, for example PlTerm::unify_term();
for such methods, a check is made for an error and an exception is
thrown, so the return value of
false
only means failure. (The whole thing can be wrapped
in
PlCheckFail(), in which case a PlFail
exception is thrown, which is converted to failure in Prolog.) For more
on this, see
section 1.6.4, and for handling
failure, see
section 1.13.1.
For PL_*() functions that take or return char*
or
wchar_t*
values, there are also wrapper functions and
methods that use std::string
or std::wstring
.
Because these copy the values, there is usually no need to enclose the
calls with
PlStringBuffers
(which wraps PL_STRING_MARK() and
PL_STRING_RELEASE()). See also the rationale for string:
section 1.8.2.
Many of the classes (PlAtom
, PlTerm
, etc.)
are thin wrappers around the C interface's types (atom_t
,
term_t
, etc.). As such, they inherit the concept of “null” from
these types (which is abstracted as PlAtom::null
,
PlTerm::null
, etc., which typically is equivalent to
0
). Normally, you shouldn't need to check whether the
object is “fully created” , for the rare situations where a
check is needed, the methods is_null()
and not_null() are provided.
Most of the classes have constructors that create a “complete” object. For example,
PlAtom foo("foo");
will ensure that the object foo
is useable and will
throw an exception if the atom can't be created. However, if you choose
to create a PlAtom
object from an atom_t
value, no checking is done (similarly, no checking is done if you create
a PlTerm
object from a term_t
value).
In many situations, you will be using a term; for these, there are special constructors. For example:
PlTerm_atom foo("foo"); // Same as PlTerm(PlAtom("foo")) PlTerm_string str("a string");
To help avoid programming errors, some of the classes do not have a
default “empty” constructor. For example, if you with to
create a
PlAtom
that is uninitialized, you must explicitly use
PlAtom(PlAtom::null)
.
This make some code a bit more cumbersome because you can't omit the
default constructors in struct initalizers.
Many of the classes have an as_string()
method7This might be changed in
future to to_string(), to be consistent with std::to_string()
,
which is useful for debugging.
The method names such as
as_int32_t() were chosen itnstead of to_int32_t() because
they imply that the representation is already an int32_t
,
and not that the value is converted to a int32_t
. That is,
if the value is a float, int32_t
will fail with an error
rather than (for example) truncating the floating point value to fit
into a 32-bit integer.
Many of the classes wrap long-lived items, such as atoms, functors,
predicates, or modules. For these, it's often a good idea to define them
as static
variables that get created at load time, so that
a lookup for each use isn't needed (atoms are unique, so
PlAtom("foo")
requires
a lookup for an atom foo
and creates one if it isn't
found).
C code sometimes creates objects “lazily” on first use:
void my_function(...) { static atom_t ATOM_foo = 0; ... if ( ! foo ) foo = PL_new_atom("foo"); ... }
For C++, this can be done in a simpler way, because C++ will call a
local “static
” constructor on first use.
void my_function(...) { static PlAtom ATOM_foo("foo"); }
The class PlTerm
(which wraps term_t
) is
the most used. Although a PlTerm
object can be created from
a term_t
value, it is intended to be used with a
constructor that gives it an initial value. The default constructor
calls PL_new_term_ref() and throws an exception if this fails.
The various constructors are described in
section 1.6.6. Note that the
default constructor is not public; to create a “variable” term,
you should use the subclass constructor PlTerm_var().
The following files are provided:
SWI-cpp2.h
- Include this file to get the C++ API. It
automatically includes
SWI-cpp2-plx.h
and SWI-cpp2.cpp
, unless the
macro _SWI_CPP2_CPP_SEPARATE
is defined, in which case you
must compile SWI-cpp2.cpp
separately.
SWI-cpp2.cpp
- Contains the implementations of some
methods and functions. If you wish to compile this separately, you must
define the macro _SWI_CPP2_CPP_SEPARATE
before your include
for SWI-cpp2.h
.
SWI-cpp2-plx.h
- Contains the wrapper functions for the
most of the functions in
SWI-Prolog.h
. This file is not intended to be used by
itself, but is #include
d by SWI-cpp2.h
.
SWI-cpp2-atommap.h
- Contains a utility class for
mapping atom-to-atom or atom-to-term, which is useful for naming
long-lived blobs instead of having to pass them around as arguments.
test_cpp.cpp
, test_cpp.pl
- Contains
various tests, including some longer sequences of code that can help in
understanding how the C++ API is intended to be used. In addition, there
are test_ffi.cpp
, test_ffi.pl
, which often
have the same tests written in C, without the C++ API.
The list below summarises the classes defined in the C++ interface.
term_t
(for more details on term_t
,
see
Interface
Data Types).
This is a “base class” whose constructor is protected; subclasses specify the actual contents. Additional methods allow checking the Prolog type, unification, comparison, conversion to native C++-data types, etc. See section 1.11.1.
For more details about PlTerm
, see section
1.6.6
PlTerm
with constructors for building compound
terms. If there is a single string argument, then PL_chars_to_term()
or PL_wchars_to_term() is used to parse the string and create the
term. If the constructor has two arguments, the first is name of a
functor and the second is a PlTermv
with the arguments.[]
operator is overloaded to access elements in this vector. PlTermv
is used to build complex terms and provide argument-lists to Prolog
goals.atom_t
in their internal Prolog representation for
fast comparison. (For more details on
atom_t
, see
Interface
Data Types). For more details of PlAtom
, see section
1.11.12.4.functor_t
, which maps to the internal
representation of a name/arity pair.predicate_t
, which maps to the internal
representation of a Prolog predicate.module_t
, which maps to the internal
representation of a Prolog module.PlException
object and throws it. If the
enclosing code doesn't intercept the exception, the PlException
object is turned back into a Prolog error when control returns to Prolog
from the PREDICATE() macros.
This is a subclass of PlExceptionBase
, which is a subclass
of std::exception
.return false
instead
if failure is expected. An error can be signaled by calling
Plx_raise_exception() or one of the PL_*_error() functions
and then throwing PlFail
; but it's better style to create
the error throwing one of the subclasses of PlException
e.g.,
throw PlTypeError("int", t)
. Subclass of PlExceptionFailBase
.PlException
object, so a PlExceptionFail
object is thrown. This is turned into failure by the PREDICATE()
macro, resulting in normal Prolog error handling. Subclass of PlExceptionFailBase
.std::exception
, to
allow catching
PlException
, PlExceptionFail
or PlFail
in a single “catch” clause.PlExceptionBase
, to
allow catching
PlExceptionFail
or PlFail
in a single “catch” clause,
excluding PlException
.
The various PL_*() functions in SWI-Prolog.h
have
corresponding Plx_*() functions, defined in SWI-cpp2-plx.h
,
which is always included by SWI-cpp2.h
. There are three
kinds of wrappers, with the appropriate one being chosen according to
the semantics of the wrapped function:
false
,
indicating an error. The Plx_*() function checks for this and throws a PlException
object containing the error. The wrapper uses template<typename
C_t> C_t PlEx(C_t rc)
,
where C_t
is the return type of the PL_*() function.
true
if it succeeds and false
if it fails or
has a runtime error. If it fails, the wrapper checks for a Prolog error
and throws a PlException
object containing the error. The
wrapper uses template<typename C_t> C_t PlWrap(C_t
rc)
, where C_t
is the return type of the PL_*()
function.
A few PL_*() functions do not have a corresponding Plx*() function
because they do not fit into one of these categories. For example,
PL_next_solution() has multiple return values (PL_S_EXCEPTION
,
PL_S_LAST
, etc.) if the query was opened with the
PL_Q_EXT_STATUS
flag.
Most of the PL_*() functions whose first argument is of type
term_t
, atom_t
, etc. have corresponding
methods in classes PlTerm
, PlAtom
, etc.
Important: You should use the Plx_*() wrappers only in the context of a PREDICATE() call, which will handle any C++ exceptions. Some blob callbacks can also handle an exception (see section 1.6.8). Everywhere else, the result of calling a Plx_*() function is unpredicatable - probably a crash.
See also the discussion on design philosophy in section 1.6.1.
The classes all have names starting with “Pl” , using CamelCase; this contrasts with the C functions that start with “PL_” and use underscores.
The wrapper classes (PlFunctor
, PlAtom
,
PlTerm
), etc. all contain a field C_
that
contains the wrapped value (functor_t
, atom_t
, term_t
respectively). If this wrapped value is needed, it should be accessed
using the unwrap() or unwrap_as_ptr() methods.
In some cases, it's natural to use a pointer to a wrapper class. For
those, the function PlUnwrapAsPtr() returns nullptr
if the pointer is null; otherwise it returns the wrapped value (which
itself might be some kind of “null” ).
The wrapper classes, which subclass WrappedC<...>
,
all define the following methods and constants:
null
).
Some classes do not have a default constructor because it can lead to
subtle bugs - instead, they either have a different way of creating the
object or can use the “null” value for the class.PlAtom
,
the constructor takes an atom_t
value).C_
- the wrapped value. This can be used directly when
calling C functions, for example, if t
and a
are of type PlTerm
and PlAtom
: PlEx(PL_put_atom(t.unwrap(),a.unwrap()))
(although it's better to do Plx_put_atom(t.unwrap(),a.unwrap())
,
which does the check).null
- the null value (typically 0
, but
code should not rely on this).is_null()
, not_null()
- test for the wrapped value being null
.reset()
- set the
wrapped value to null
reset(new_value)
- set the wrapped value from the
wrapped type (e.g., PlTerm::reset(term_t new_value))reset_wrapped(new_value)
- set the wrapped value from
the same type (e.g., PlTerm::reset_wrapped(PlTerm new_value))bool
operator is disabled - you should use not_null()
instead.8The reason: a bool
conversion causes ambiguity with PlAtom(PlTterm)
and PlAtom(atom_t)
.
The method unwrap() can be used to access the C_
field, and can be used wherever a atom_t
or term_t
is used. For example, the PL_scan_options() example code can be
written as follows. Note the use of &callback.unwrap()
to pass a pointer to the wrapped term_t
value.
PREDICATE(mypred, 2) { auto options = A2; int quoted = false; size_t length = 10; PlTerm_var callback; PlCheckFail(PL_scan_options(options, 0, "mypred_options", mypred_options, "ed, &length, &callback.unwrap())); callback.record(); // Needed if callback is put in a blob that Prolog doesn't know about. // If it were an atom (OPT_ATOM): register_ref(). <implement mypred> }
For functions in SWI-Prolog.h
that don't have a C++
equivalent in SWI-cpp2.h
, PlCheckFail()
is a convenience function that checks the return code and throws a PlFail
exception on failure or PlException
if there was an
exception. The enclosing PREDICATE()
code catches PlFail
exceptions and converts them to the foreign_t
return code for failure. If the failure from the C function was due to
an exception (e.g., unification failed because of an out-of-memory
condition), the foreign function caller will detect that situation and
convert the failure to an exception.
The “getter” methods for PlTerm
all throw an
exception if the term isn't of the expected Prolog type. The “getter” methods
typically start with “as” , e.g. PlTerm::as_string().
There are also other “getter” methods, such as PlTerm::get_float_ex()
that wrap PL_*() functions.
“getters” for integers have an additional problem, in
that C++ doesn't define the sizes of int
, long
,
or
size_t
. It seems to be impossible to make an overloaded
method that works for all the various combinations of integer types on
all compilers, so there are specific methods for int64_t
,
uint64_t
, size_t
.
In some cases,it is possible to overload methods; for example, this
allows the following code without knowing the exact definition of
size_t
:
PREDICATE(p, 1) { size_t sz; A1.integer(&sz); ... }
It is strongly recommended that you enable conversion checking.
For example, with GNU C++, use these options (possibly with -Werror
):
-Wconversion -Warith-conversion -Wsign-conversion
-Wfloat-conversion
.
There is an additional problem with characters - C promotes them to int
but C++ doesn't. In general, this shouldn't cause any problems, but care
must be used with the various getters for integers.
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.
There are a number of subclasses that exist only to provide a safe
way of constructing at term. There is also a subclass (PlTermScoped
)
that helps reclaim terms.
Most of the PlTerm
constructors are defined as
subclasses of
PlTerm
, with a name that reflects the Prolog type of what
is being created (e.g., PlTerm_atom
creates a term from an
atom;
PlTerm_string
creates a term from a Prolog string). This is
done to ensure that the there is no ambiguity in the constructors - for
example, there is no way to distinguish between term_t
,
atom_t
, and ordinary integers, so there are constructors
PlTerm(), PlTerm_atom(), and PlTerm_integer. All of the
constructors are “explicit” because implicit creation of PlTerm
objects can lead to subtle and difficult to debug errors.
If a constructor fails (e.g., out of memory), a PlException
is thrown. The class and subclass constructors are as follows.
term_t
. This is a
lightweight class, so no code is generated.PlTerm
with constructors for building a term
that contains a Prolog integer from a
long
.9PL_put_integer()
takes a long
argument.PlTerm
with constructors for building a term
that contains a Prolog integer from a int64_t
.PlTerm
with constructors for building a term
that contains a Prolog integer from a uint64_t
.PlTerm
with constructors for building a term
that contains a Prolog integer from a size_t
.PlTerm
with constructors for building a term
that contains a Prolog float.PlTerm
with constructors for building a term
that contains a raw pointer. This is mainly for backwards compatibility;
new code should use blobs. A pointer is represented in Prolog
as a mangled integer. The mangling is designed to make most pointers fit
into a tagged-integer. Any valid pointer can be represented.
This mechanism can be used to represent pointers to C++ objects in
Prolog. Please note that MyClass
should define conversion
to and from void *
.
PREDICATE(make_my_object, 1) { auto myobj = new MyClass(); return A1.unify_pointer(myobj); } PREDICATE(my_object_contents, 2) { auto myobj = static_cast<MyClass*>(A1.as_pointer()); return A2.unify_string(myobj->contents); } PREDICATE(free_my_object, 1) { auto myobj = static_cast<MyClass*>(A1.as_pointer()); delete myobj; return true; }
PlTerm
with constructors for building a term
that contains a Prolog string object. For constructing a term from the
text form, see
PlCompound
.PlTerm
with constructors for building Prolog
lists of character integer values.PlTerm
with constructors for building Prolog
lists of one-character atoms (as atom_chars/2).PlTerm
for building and analysing Prolog lists.The methods are:
std::string
. If you use this, be sure to
wrap it with PlStringBuffers
, and if you use the BUF_MALLOC
flag, you can use std::unique_ptr<char, decltype(&PL_free)>
to manage the pointer.std::wstring
.
If you use this, be sure to wrap it with PlStringBuffers
,
and if you use the BUF_MALLOC
flag, you can use std::unique_ptr<char,
decltype(&PL_close)>
to manage the pointer.PL_FILE_NOERRORS
- throws PlFail
on failure, which is interpreted by the
enclosing PREDICATE
as either failure or an error,
depending on the flag bit PL_FILE_NOERRORS
.PL_VARIABLE
, PL_ATOM
,
etc, throwing an exception on Prolog error. bois_atom()
or is_string()
.PlTypeError
if PlTerm::is_attvar()
fails.PlTypeError
if PlTerm::is_variable()
fails.PlTypeError
if PlTerm::is_ground()
fails.PlTypeError
if PlTerm::is_atom()
fails.PlTypeError
if PlTerm::is_integer()
fails.PlTypeError
if PlTerm::is_string()
fails.PlTypeError
if PlTerm::is_atom_or_string()
fails.PlTypeError
if PlTerm::is_float()
fails.PlTypeError
if PlTerm::is_rational()
fails.PlTypeError
if PlTerm::is_compound()
fails.PlTypeError
if PlTerm::is_callable()
fails.PlTypeError
if PlTerm::is_list()
fails.PlTypeError
if PlTerm::is_dict()
fails.PlTypeError
if PlTerm::is_pair()
fails.PlTypeError
if PlTerm::is_atomic()
fails.PlTypeError
if PlTerm::is_number()
fails.PlTypeError
if PlTerm::is_acyclic()
fails.PlRecord
constructed from the term. Same as PlRecord(*this).std::string
.
The flags BUF_MALLOC
, BUF_STACK
, and BUF_ALLOW_STACK
are ignored and replaced by BUF_DISCARDABLE
.std::wstring
.
The flags BUF_MALLOC
, BUF_STACK
, and BUF_ALLOW_STACK
are ignored and replaced by BUF_DISCARDABLE
.PlTypeError
if not a
"compound" or atom.PlTypeError
if not a "compound"
or atom.nullptr
. Returns false
if the term
isn't a compound or atom.PlResourceError
).PlTerm::null
.
Does not reset the wrapped term. This is used implicitly in
PlTermScoped
’s destructor, which does reset the
wrapped term.PlTermScoped
’s destructor, which does reset the
wrapped term.false
if unification fails. If on failure, there isn't an immediate return to
Prolog (e.g., by wrapping the call with
PlCheckFail()), this method
should be called within the context of PlFrame
, and PlFrame::rewind()
should be called.compare(t2) == 0
.compare(t2) != 0
.compare(t2) < 0
.compare(t2) > 0
.compare(t2) <= 0
.compare(t2) >= 0
.
This class is experimental and subject to change.
Normally all term references in a scope are discarded
together or all term references created after a specific one are
reclaimed using PlTerm::reset_term_refs(). A PlTermScoped
object is the same as a PlTerm
object except that
PL_free_term_ref() is called on its wrapped term when the object
goes out of scope. This shrinks the current foreign frame if the term is
the last one in the frame and otherwise it marks it for reuse.
Here is an example, where PlTermScoped
is inside a
for-loop. If PlTerm
were used instead, the stack would grow
by the number of items in the array; PlTermScoped
ensures
that stack doesn't grow.10Assuming
that unify_atom_list() is called from a predicate implementation,
if PlTerm
were used instead of PlTermCopy
, all
the created terms would be discarded when the Prolog stack frame is
unwound; the use of PlTermScoped
reuses the terms in that
stack frame. A slightly more effiicient way of preventing
the Prolog stack from growing is to use PlTerm::put_term()
to reuse a term reference; but that is more difficult to understand and
also more error-prone.
bool unify_atom_list(const std::vector<std::string>& array, PlTerm list) { PlTermScoped tail(list); // calls PL_copy_term_ref() to copy `list` for( auto item : array ) { PlTermScoped head; // var term PlCheckFail(tail.unify_list(head, tail)); PlCheckFail(head.unify_chars(PL_ATOM, item)); } return tail.unify_nil(); }
The design of PlTermScoped
is modeled on
std::unique_ptr
11unique_ptr
was originally called scoped_ptr
in the Boost libraries,
but the name was changed to contrast with std::shared_ptr
,
which is reference-counted. and uses move semantics
to ensure safety.12Move
semantics are a relatively new feature in C++ and can be a bit
difficult to understand. Roughly speaking, a move is a copies
the object and then calls its destructor, so that any further use of the
object is an error. If an object defines move methods or constructors,
it can optimize this operation, and also can catch certain kinds of
errors at compile time.
A PlTermScoped
object can be created either with or
without a wrapped term - the PlTermScoped::reset()
method sets (or nulls) the wrapped term. A PlTermScoped
object cannot be copied or passed as a value to a function; the PlTermScoped::release()
method returns the wrapped term and resets the PlTermScoped
object so that any further use of the PlTermScoped
object
is an error.
As shown in the example above, PlTermScoped
can be used
instead of PlTerm
, in places where a loop would otherwise
cause the stack to grow. There are limitations on the operations that
are allowed on a PlTermScoped
object; in particular, a
PlTermScoped
object cannot be copied and cannot be
implicitly converted to a Plterm
.
The PlTermScoped
constructors always create a new term
ref, by calling either PL_new_term_ref() or PL_copy_term_ref().
If you try to copy or create a PlTermScoped
object from
another
PlTermScoped
object, you will get a compile-time error; you
can set the value from a PlTerm
object, which can be
obtained by calling PlTermScoped::release().
The methods derived from the PL_put_*() and PL_cons_*() functions
should not be used with a PlTermScoped
object. If you need
to use these, you can use PlTermScoped::get()
to get a PlTerm
, for which a put_*() method can be used.
To copy a PlTermScoped
object or to pass it as a value
in a function call, use the PlTermScoped::release()
method or std::move():
PlTermScoped ts(...); PlTerm t; // Copy to a PlTerm: t = ts.release(); // or: t = std::move(ts); // Pass as a value to a function: foo(ts.release()); // or: foo(std::move(ts); // Copy to a PlTermScoped: PlTermScoped ts2; ts2.reset(ts.release()); // or: ts2.reset(std::move(ts));
The methods are (in addition to, or overriding the methods in PlTerm
):
PlTermScoped
, use PlTermScoped::release()
to convert it to a PlTerm
.PlTerm
. This is typically used
when calling a function that expects a PlTerm
object and
which will not call
PlTerm::free_term_ref()
on it.t2.reset(t.release())
to copy a
PlTermScoped
; this can also be written
t2=std::move(t)
.PlTermScoped
objects’wrapped terms.
Nomenclature warning:
There are two different release()
functions:
PL_blob_t
).unique_ptr
.Disclaimer:
The blob API for C++ is not completely general, but is designed to make common use cases easy to write. For other use cases, the underlying C API can still be used. The use case is:
PlBlob
, which
provides a number of fields and methods, of which a few can be
overridden in the blob (notably: write_fields(),
compare_fields(), save(), load(), and the
destructor).std::unique_ptr
to manage the blob (that is, the blob is created using the new
operator and is not created on the stack).new
operator and
passes ownership to the blob. More complex behavior is possible, using PlAtom::register_ref()
and PlAtom::unregister_ref().A Prolog blob consists of five parts:
PL_blob_t
structure that defines the callbacks. The PL_BLOB_DEFINITION()
macro is typically used to create this, with the callbacks pointing to
methods in the C++ blob.PL_blob_t
structure, and
optionally a virtual destructor. The PL_BLOB_SIZE
macro is
used to define some required methods.std::unique_ptr
.
For the PL_blob_t
structure, the C++ API provides the
PL_BLOB_DEFINITION(blob_class,blob_name) macro, which references
a set of template functions that allow easily setting up the callbacks.
The C interface allows more flexibility by allowing some of the
callbacks to default; however, the C++ API for blobs provides suitable
callbacks for all of them, using the PL_BLOB_DEFINITION() macro.
For the data, which is subclassed from PlBlob
, the
programmer defines the various fields, a constructor that initializes
them, and a destructor. Optionally, override methods can be defined for
one of more of the methods PlBlob::compare_fields(), PlBlob::write_fields(),
PlBlob::save(), PlBlob::load(), PlBlob::pre_delete().
More details on these are given later.
There is a mismatch between how Prolog does memory management (and
garbage collection) and how C++ does it. In particular, Prolog assumes
that cleanup will be done in the release() callback function
associated with the blob whereas C++ typically does cleanup in a
destructor. The blob interface gets around this mismatch by providing a
default release() callback that assumes that the blob was created
using PL_BLOB_NOCOPY
and manages memory using a
std::unique_ptr
.15This release()
function has nothing to do with std::unique_ptr::release().
More details on this are in
section 1.6.8.1.
The C blob interface has a flag that determines how memory is
managed:
PL_BLOB_NOCOPY
. The PL_BLOB_DEFINITION() macro sets
this, so Prolog will call the C++ destructor when the blob is garbage
collected. (This call is done indirectly, using a callback that is
registeered with Prolog.)
The C++ API for blobs only supports blobs with
PL_BLOB_NOCOPY
.16The
API can probably also support blobs with PL_BLOB_UNIQUE
,
but there seems to be little point in setting this flag for non-text
blobs.
Some slightly obscure features of C++ are used with PlBlob
and
ContextType
, and can easily cause subtle bugs or memory
leaks if not used carefully.
When a C++ object is created, its memory is allocated (either on the stack or on the heap using new), and the constructors are called in this order:
There are special forms of the constructor for copying, moving, and
assigning. The “copy constructor” has a signature Type(const
Type&
and is used when an object is created by copying, for
example by assignment or passing the object on the stack in a function
call. The “move constructor” has the signature Type(Type&&
and is equivalent to the copy constructor for the new object followed by
the destructor for the old object. (Assignment is usually allowed to
default but can also be specified).
Currently, the copy and move constructors are not used, so it is best to explicitly mark them as not existing:
Type(const Type&) = delete; Type(Type&&) = delete; Type& operator =(const Type&) = delete; Type& operator =(Type&&) = delete;
A constructor may throw an exception - good programming style is to not leave a “half constructed” object but to throw an exception. Destructors are not allowed to throw exceptions,17because the destructor might be invoked by another exception, and C++ has no mechanism for dealing with a second exception. which complicates the API somewhat.
More details about constructors and destructors can be found in the FAQs for constructors and destructors.
Many classes or types have a constructor that simply assigns a
default value (e.g., 0 for int
) and the destructor does
nothing. In particular, the destructor for a pointer does nothing, which
can lead to memory leaks. To avoid memory leaks, the smart pointer
std::unique_ptr
18The
name “unique” is to distinguish this from a “shared” pointer.
A shared pointer can share ownership with multiple pointers and the
pointed-to object is deleted only when all pointers to the object have
been deleted. A unique pointer allows only a single pointer, so the
pointed-to object is deleted when the unique pointer is deleted.
can be used, whose destructor deletes its managed object. Note that std::unique_ptr
does not enforce single ownership; it merely makes single ownership easy
to manage and it detects most common mistakes, for example by not having
copy constructor or assignment operator.
For example, in the following, the implicit destructor for p
does nothing, so there will be a memory leak when a Ex1
object is deleted:
class Ex1 { public: Ex1() : p(new int) { } int *p; };
To avoid a memory leak, the code could be changed to this:
class Ex1 { public: Ex1() p(new int) { } ~Ex1() { delete p; } int *p; };
but it is easier to do the following, where the destructor for
std::unique_ptr
will free the memory:
class Ex1 { public: Ex1() p(new int) { } std::unique_ptr<int> p; };
The same concept applies to objects that are created in code - if a
C++ object is created using new, the programmer must
manage when its destructor is called. In the following, if the call to
data->validate()
fails, there will be a memory
leak:
MyData *foo(int some_value) { MyData *data = new MyData(...); data->some_field = some_value; if (! data->validate() ) throw std::runtime_error("Failed to validate data"); return data; }
Ths could fixed by adding delete data
before throwing
the runtime_error
; but this doesn't handle the situation of data->validate()
throwing an exception (which would require a catch/throw). Instead, it's
easiser to use std::unique_ptr
, which takes care of every
return or exception path:
MyData *foo(int some_value) { std::unique_ptr<MyData> data(new MyData(...)); data->some_field = some_value; if (! data->validate() ) throw std::runtime_error("Failed to validate data"); return data.release(); // don't delete the new MyData }
The destructor for std::unique_ptr
will delete the data
when it goes out of scope (in this case, by return or throw) unless the
std::unique_ptr::release() method is called.19The
call to unique_ptr<MYData>::release
doesn't call the destructor; it can be called using std::unique_ptr::get_deleter().
In the code above, the throw
will cause the
unique_ptr
’s destructor to be called, which will free
the data; but the data will not be freed in the return
statement because of the unique_ptr::release(). Using this style,
a pointer to data on the heap can be managed as easily as data on the
stack. The current C++ API for blobs takes advantage of this - in
particular, there are two methods for unifying a blob:
unique_ptr
allows specifying the delete function. For
example, the following can be used to manage memory created with PL_malloc():
std::unique_ptr<void, decltype(&PL_free)> ptr(PL_malloc(...), &PL_free);
or, when memory is allocated within a PL_*() function (in this case, using the Plx_*() wrapper for PL_get_nchars()):
size_t len; char *str = nullptr; Plx_get_nchars(t, &len, &str.get(), BUF_MALLOC|CVT_ALL|CVT_WRITEQ|CVT_VARIABLE|REP_UTF8|CVT_EXCEPTION); std::unique_ptr<char, decltype(&PL_free)> _str(str, &PL_free);
The current C++ API assumes that the C++ blob is allocated on the
heap. If the programmer wishes to use the stack, they can use std::unique_ptr
to automatically delete the object if an error is thrown -
PlTerm::unify_blob(std::unique_ptr<PlBlob>*)
prevents the automatic deletion if unification succeeds.
A unique_ptr
needs a bit of care when it is passed as an
argument. The unique_ptr::get() method can be used to get the “raw” pointer;
the delete must not be used with this pointer. Or, the unique_ptr::release()
method can be used to transfer ownership without calling the object's
destructor.
Using unique_ptr::release() is a bit incovenient, so instead
the
unique_ptr
can be passed as a pointer (or a reference).
This does not create a new scope, so the pointer must be assigned to a
local variable. For example, the code for unify_blob() is
something like:
bool PlTerm::unify_blob(std::unique_ptr<PlBlob>* b) const { std::unique_ptr<PlBlob> blob(std::move(*b)); if ( !unify_blob(blob.get()) ) return false; (void)blob.release(); return true; }
The line declaration for blob
uses the “move
constructor” to set the value of a newly scoped variable (std::move(*b)
is a cast, so unique_ptr
’s move constructor is used).
This has the same effect as calling b->reset()
,
so from this point on,
b
has the value nullptr
.
Alternatively, the local unique_ptr
could be set by
std::unique_ptr<PlBlob> blob(b->release());
or
std::unique_ptr<PlBlob> blob; blob.swap(*b);
If the call to PlTerm::unify_blob()
fails or throws an exception, the virtual destructor for blob
is called. Otherwise, the call to blob.release()
prevents the destructor from being called - Prolog now owns the blob
object and can call its destructor when the garbage collector reclaims
it.
TL;DR: Use PL_BLOB_DEFINITION() to define the blob with the
flag
PL_BLOB_NOCOPY
and the default PlBlob
wrappers; define your struct as a subclass of PlBlob
with
no copy constructor, move constructor, or assignment operator; create a
blob using
std::unique_ptr<PlBlob>(new ...)
, call PlTerm::unify_blob().
Optionally, define one or more of: compare_fields(), write_fields(),
save(), load() methods (these are described after the
sample code).
In this section, the blob is of type MyBlob
, a subclass
of PlBlob
. (Example code is given in section
1.6.8.5) and section 1.6.8.7.
A blob is typically created by calling a predicate that does the following:
auto ref = std::unique_ptr<PlBlob>(new MyBlob>(...))}
or
auto ref = std::make_unique<MyBlob>(...);
return PlTerm::unify_blob(&ref);
If unification fails or throws an exception, the object is automatically freed and its destructor is called.
If make_unique() was used to create the pointer, you need to call PlTerm::unify_blob() as follows, because C++'s type inferencing can't figure out that this is a covariant type:
std::unique_ptr<PlBlob> refb(ref.release()); // refb now "owns" the ptr - from here on, ref == nullptr return A2.unify_blob(&refb);
If unification succeeds, Prolog calls:
ref->release()
to pass ownership of the blob to
Prolog (when the blob is eventually garbage collected, the blob's
destructor will be called).
At this point, the blob is owned by Prolog and may be freed by its
atom garbage collector, which will call the blob's destructor (if the
blob shouldn't be deleted, it can override the the PlBlob::pre_delete()
method to return false
).
Whenever a predicate is called with the blob as an argument (e.g., as A1),
the blob can be accessed by
PlBlobv<MyBlob>::cast_check(A1.as_atom())
.
Within a method, the Prolog blob can be accessed as a term (e.g., for
constructing an error term) using the method MyBlob::symbol_term().
This field is initialized by the call to PlTerm::unify_blob();
if
MyBlob::symbol_term() is called before a successful call to
PlTerm::unify_blob(), MyBlob::symbol_term()
returns a
PlTerm_var
.
When the atom garbage collector runs, it frees the blob by first calling the release() callback, which does delete, which calls the destructor MyBlob::~MyBlob(). Note that C++ destructors are not supposed to raise exception; they also should not cause a Prolog error, which could cause deadlock unless the real work is done in another thread.
Often it is desired to release the resources before the garbage collector runs. To do this, the programmer can provide a “close” predicate that is the inverse of the “open” predicate that created the blob. This typically has the same logic as the destructor, except that it can raise a Prolog error.
When a blob is used in the context of a PREDICATE()
macro, it can raise a C++ exception (PlFail
or PlException
)
and the
PREDICATE() code will convert
the exception to the appropriate Prolog failure or error; memory
allocation exceptions are also handled.
Blobs have callbacks, which can run outside the context of a PREDICATE(). Their exception handling is as follows:
PlAtom::null
,
which is interpreted by Prolog as failure.false
(or throw a PlException
or
PlExceptinFailBase
, which will be interpreted as a return
value of false
), resulting in the blob not being garbage
collected, and the destructor not being called. Note that this doesn't
work well with final clean-up atom garbage collection, which disregards
the return value and also doesn't respect the ordering of blob
dependencies (e.g., if an iterator blob refers to a file-like blob, the
file-like blob might be deleted before the iterator is deleted).
This code runs in the gc
thread. The only PL_*()
function that can safely be called are
PL_unregister_atom() (which is what PlAtom::unregister_ref()
calls).
Here is minimal sample code for creating a blob that owns a
connection to a database. It has a single field (connection
)
and defines compare_fields() and write_fields().
A second sample code shows how to wrap a system pointer - section 1.6.8.7
struct MyConnection { std::string name; explicit MyConnection(); explicit MyConnection(const std::string& _name); bool open(); bool close() noexcept; void portray(PlStream& strm) const; }; struct MyBlob; static PL_blob_t my_blob = PL_BLOB_DEFINITION(MyBlob, "my_blob"); struct MyBlob : public PlBlob { std::unique_ptr<MyConnection> connection; explicit MyBlob() : PlBlob(&my_blob) { } explicit MyBlob(const std::string& connection_name) : PlBlob(&my_blob), connection(std::make_unique<MyConnection>(connection_name)) { if ( !connection->open() ) throw MyBlobError("my_blob_open_error"); } PL_BLOB_SIZE ~MyBlob() noexcept { if ( !close() ) Sdprintf("***ERROR: Close MyBlob failed: %s\n", name().c_str()); // Can't use PL_warning() } inline std::string name() const { return connection ? connection->name : ""; } bool close() noexcept { if ( !connection ) return true; bool rc = connection->close(); connection.reset(); // Can be omitted, leaving deletion to ~MyBlob() return rc; } PlException MyBlobError(const char* error) const { return PlGeneralError(PlCompound(error, PlTermv(symbol_term()))); } int compare_fields(const PlBlob* _b_data) const override { auto b_data = static_cast<const MyBlob*>(_b_data); // See note about cast return name().compare(b_data->name()); } bool write_fields(IOSTREAM *s, int flags) const override { PlStream strm(s); strm.printf(","); return write_fields_only(strm); } bool write_fields_only(PlStream& strm) const { if ( connection ) connection->portray(strm); else strm.printf("closed"); return true; } bool portray(PlStream& strm) const { strm.printf("MyBlob("); write_fields_only(strm); strm.printf(")"); return true; } }; // %! create_my_blob(+Name: atom, -MyBlob) is semidet. PREDICATE(create_my_blob, 2) { // Allocating the blob uses std::unique_ptr<MyBlob> so that it'll be // deleted if an error happens - the auto-deletion is disabled by // ref.release() inside unify_blob() before returning success. auto ref = std::unique_ptr<PlBlob>(new MyBlob(A1.as_atom().as_string())); return A2.unify_blob(&ref); } // %! close_my_blob(+MyBlob) is det. // % Close the connection, silently succeeding if is already // % closed; throw an exception if something goes wrong. PREDICATE(close_my_blob, 1) { auto ref = PlBlobV<MyBlob>::cast_ex(A1, my_blob); if ( !ref->close() ) throw ref->MyBlobError("my_blob_close_error"); return true; } // %! portray_my_blob(+Stream, +MyBlob) is det. // % Hook predicate for // % user:portray(MyBlob) :- // % blob(MyBlob, my_blob), !, // % portray_my_blob(current_output, MyBlob). PREDICATE(portray_my_blob, 2) { auto ref = PlBlobV<MyBlob>::cast_ex(A2, my_blob); PlStream strm(A1, 0); return ref->portray(strm); }
PL_blob_t
structure with the wrapper functions and flags
set to PL_BLOB_NOCOPY
. It should be declared outside the PlBlob
class and should not be marked const
- otherwise, a runtime
error can occur.20The cause of the
runtime error is not clear, but possibly has to do with the order of
initializing globals, which is unspecified for C++.
MyBlob
struct is a subclass of PlBlob
.
See below for a discussion of the default behaviors.
MyBlob
contains a pointer to a MyConnection
object and keeps a copy of the connection's name. The MyConnection
object is handled by a std::unique_ptr
smart pointer, so
that it is automatically freed when the MyBlob
object is
freed.
PlBlob
constructor.
MyBlob
class must not provide a copy or move
constructor, nor an assignment operator (PlBlob has these as
delete, so if you try to use one of these, you will get
a compile-time error).
PlBlob
’s constructor sets blob_t_
to
a pointer to the my_blob
definition. This is used for
run-time consistency checking by the various callback functions and for
constructing error terms (see PlBlob::symbol_term()).
PlBlob
’s acquire() is called by PlBlobV<MyBlob>::acquire()
and fills in the symbol_
field. MyBlob
must
not override this - it is not a virtual method. The symbol_
field can be accessed by PlBlob::symbol_term().
MyConnection
object. If this fails, an exception is thrown.
The constructor then calls MyConnection::open() and throws an
exception if that fails. (The code would be similar if instead the
constructor for MyConnection
also did an open and threw an
exception on failure.)
PL_BLOB_SIZE
is boilerplate that defines a
blob_size_() method that is used when the blob is created.
PlUnknownError("...")
,
that will try to create a Prolog term, which will crash because the
environment for creating terms is not available. Because
there is no mechanism for reporting an error, the destructor prints a
message on failure (calling
PL_warning() would cause a crash).
PlBlob::close() calls MyConnection::close() and then
frees the object. Error handling is left to the caller because of the
possibility that this is called in the context of garbage collection. It
is not necessary to free the MyConnection
object here - if
it is not freed, the
std::unique_ptr<MyConnection>
’s
destructor would free it.
0
(``equal” ).
The _b_data argument is of type const PlBlob*
- this is cast to const MyBlob*
using a
static_cast
. This is safe because Prolog guarantees that
PlBlobV<PlBlob>::compare() will only be called
if both blobs are of the same type.
The flags argument is the same as given to PlBlobV<PlBlob>::write(),
which is a bitwise or of zero or more of the PL_WRT_*
flags that were passed in to the caling PL_write_term() (defined
in SWI-Prolog.h
). The
flags do not have the PL_WRT_NEWLINE
bit set, so
it is safe to call PlTerm::write() and there is no need for
writing a trailing newline.
If anything in PlBlob::write_fields() throws a C++ exception, it will be caught by the calling PlBlobV<PlBlob>::write() and handled appropriately.
std::unique_ptr<PlBlob>()
creates a
MyBlob that is deleted when it goes out of scope. If an exception occurs
between the creation of the blob or if the call to unify_blob()
fails, the pointer will be automatically freed (and the
MyBlob
destructor will be called).
PlTerm::unify_blob()
is called with a pointer to a
std::unique_ptr
, which takes ownership of the object by
calling std::unique_ptr<PlBlob>::release() and
passes the pointer to Prolog, which then owns it. This also sets ref
to nullptr
, so any attempt to use ref after a
call to PlTerm::unify_blob()
will be an error.
If you wish to create a MyBlob
object instead of a
PlBlob
object, a slightly different form is used:
auto ref = std::make_unique<MyBlob>(...); ... std::unique_ptr<PlBlob> refb(ref.release()); PlCheckFail(A2.unify_blob(&refb)); return true;
MyBlob
pointer using the
PlBlobV<MyBlob>::cast_ex() function, which will
throw a
type_error
if the argument isn't a blob of the expected
type.
struct MyFileBlob; static PL_blob_t my_file_blob = PL_BLOB_DEFINITION(MyFileBlob, "my_file_blob"); static const PlOptionsFlag<int> MyFileBlob_options("MyFileBlob-options", { {"absolute", PL_FILE_ABSOLUTE}, {"ospath", PL_FILE_OSPATH}, {"search", PL_FILE_SEARCH}, {"exist", PL_FILE_EXIST}, {"read", PL_FILE_READ}, {"write", PL_FILE_WRITE}, {"execute", PL_FILE_EXECUTE}, {"noerrors", PL_FILE_NOERRORS} }); struct MyFileBlob : public PlBlob { std::FILE* file_; std::string mode_; int flags_; std::string filename_; std::vector<char> buffer_; // used by read(), to avoid re-allocation explicit MyFileBlob() : PlBlob(&my_file_blob) { } explicit MyFileBlob(PlTerm filename, PlTerm mode, PlTerm flags) : PlBlob(&my_file_blob), mode_(mode.as_string()) { flags_ = MyFileBlob_options.lookup_list(flags); filename_ = filename.get_file_name(flags_); file_ = fopen(filename_.c_str(), mode_.c_str()); if ( !file_ ) // TODO: get error code (might not be existence error) throw PlExistenceError("my_file_blob_open", PlTerm_string(filename_)); // for debugging: // PlTerm_string(filename.as_string() + "\" => \"" + // filename_ + "\", \"" + mode_ + // ", flags=" + MyFileBlob_options.as_string(flags_) + "\")") } PL_BLOB_SIZE std::string read(size_t count) { assert(sizeof buffer_[0] == sizeof (char)); assert(sizeof (char) == 1); buffer_.reserve(count); return std::string(buffer_.data(), std::fread(buffer_.data(), sizeof buffer_[0], count, file_)); } bool eof() const { return std::feof(file_); } bool error() const { return std::ferror(file_); } virtual ~MyFileBlob() noexcept { if ( !close() ) // Can't use PL_warning() Sdprintf("***ERROR: Close MyFileBlob failed: (%s)\n", filename_.c_str()); } bool close() noexcept { if ( !file_ ) return true; int rc = std::fclose(file_); file_ = nullptr; return rc == 0; } PlException MyFileBlobError(const std::string error) const { return PlGeneralError(PlCompound(error, PlTermv(symbol_term()))); } int compare_fields(const PlBlob* _b_data) const override { // dynamic_cast is safer than static_cast, but slower (see documentation) // It's used here for testing (the documentation has static_cast) auto b_data = dynamic_cast<const MyFileBlob*>(_b_data); return filename_.compare(b_data->filename_); } bool write_fields(IOSTREAM *s, int flags) const override { PlStream strm(s); strm.printf(","); return write_fields_only(strm); } bool write_fields_only(PlStream& strm) const { // For debugging: // strm.printf("%s mode=%s flags=%s", filename_.c_str(), mode_.c_str(), // MyFileBlob_options.as_string(flags_).c_str()); strm.printf("%s", filename_.c_str()); if ( !file_ ) strm.printf("-CLOSED"); return true; } bool portray(PlStream& strm) const { strm.printf("MyFileBlob("); write_fields_only(strm); strm.printf(")"); return true; } }; PREDICATE(my_file_open, 4) { auto ref = std::unique_ptr<PlBlob>(new MyFileBlob(A2, A3, A4)); return A1.unify_blob(&ref); } PREDICATE(my_file_close, 1) { auto ref = PlBlobV<MyFileBlob>::cast_ex(A1, my_file_blob); if ( !ref->close() ) // TODO: get the error code throw ref->MyFileBlobError("my_file_blob_close_error"); return true; }
<cstdio>
. The blob wraps the
file pointer returned from fopen() and also keeps a few other
values for debugging (the mode, flags, filename from the call to fopen())
plus a buffer for read operations.
[search,read]
would map to‘examPL_FILE_SEARCH|PL_FILE_READ‘.
MyFileBlob
struct defines the blob that wraps a
FILE*
. The constructor (which is called by predicate
my_file_open/4)
converts the flags term (a list of atoms or strings) to a
flag that is passed to PL_get_file_name(), to convert the filename
to a string containing the abslute file name. This is then passed to fopen(),
together with the
mode. If the call to fopen() fails, a C++ exception is
thrown, to be handled by Prolog. Other errors, such as a wrong argument
type to PL_get_file_name() can also cause an exception.
FILE*
to null, so that close won't be done twice.
MyBlob
in section
1.6.8.5.
MyFileBlob
constructor with Filename, Mode,
flags and unifies the blob with File.
Passing a Prolog blob around can be inconvenient; it is easier if a
blob can be identified an atom. An example of this is with streams,
which are identified by atoms such as user_input
.
A utility class AtomMap
is provided for this situation.
See section 1.17.4.
The C++ API remains a work in progress.
SWI-Prolog string handling has evolved over time. The functions that
create atoms or strings using char*
or wchar_t*
are “old school” ; similarly with functions that get the
string as
char*
or wchar_t*
. The PL_get,unify,put_[nw]chars()
family is more friendly when it comes to different input, output,
encoding and exception handling.
Roughly, the modern API is PL_get_nchars(), PL_unify_chars() and PL_put_chars() on terms. There is only half of the API for atoms as PL_new_atom_mbchars() and PL-atom_mbchars(), which take an encoding, length and char*.
For return values, char*
is dangerous because it can
point to local or stack memory. For this reason, wherever possible, the
C++ API returns a std::string
, which contains a copy of the
string. This can be slightly less efficient that returning a
char*
, but it avoids some subtle and pervasive bugs that
even address sanitizers can't detect.23If
we wish to minimize the overhead of passing strings, this can be done by
passing in a pointer to a string rather than returning a string value;
but this is more cumbersome and modern compilers can often optimize the
code to avoid copying the return value.
Some functions require allocating string space using PL_STRINGS_MARK().
The PlStringBuffers
class provides a RAII wrapper
that ensures the matching PL_STRINGS_RELEASE() is done. The PlAtom
or PlTerm
member functions that need the string buffer use PlStringBuffers
,
and then copy the resulting string to a std::string
value.
The C++ API has functions such as PlTerm::get_nchars()
that use
PlStringBuffers
and then copy the result to a
std::string
result, so the programmer often doesn't need to
use PlStringBuffers
.
BUF_STACK
. This isn't needed if you use a method such as
PlTerm::as_string(), but
is needed for calling certain PL_*() or Plx_*() wrapped functions.
The constructor calls PL_STRINGS_MARK() and the destructor calls PL_STRINGS_RELEASE(). Here is an example of its use, for writing an atom to a stream, using Plx_atom_wchars(), which must be called within a strings buffer:
PREDICATE(w_atom_cpp, 2) { auto stream(A1), term(A2); PlStream strm(stream, STIO_OUTPUT); PlStringBuffers _string_buffers; const pl_wchar_t *sa = Plx_atom_wchars(term.as_atom().unwrap(), nullptr); strm.printfX("/%Ws/", sa); return true; }
PlStream
can be used to get a stream from a Prolog term,
or to lock the stream so that other threads cannot interleave their
output. With either usage, PlStream
is a RAII
class that ensure the matchin PL_release_stream() is done, and
also handles some subtle problems with C++ exceptions.
The methods are:
PlStream
object to an invalid stream (see PlStream::check_stream()).IOSTREAM*
, PlStream
is implicitly converted to IOSTREAM*
.PlStream
object contains a valid stream and throws an
exception if it doesn't. This is used to ensure that PlStream::release()
hasn't been called.
Most of the stream I/O functions have corresponding methods in PlStream
.
For example, Sfprintf() corresponds to
PlStream::printf(). PlStream::seek() and PlStream::tell()
call
Sseek64() and Stell64() instead of long
(they
are also deprecated: PlStream::seek64() and PlStream::tell64()
are preferred).
The C interface to stream I/O doesn't raise a Prolog error when
there's a stream error (typically indicated by a -1 return code).
Instead, the error sets a flag on the stream and
PL_release_stream() creates the error term. The
PlStream
destructor calls PL_release_stream(); but
it's a fatal error in C++ to raise an exception in a destructor if the
destructor is invoked by stack-unwinding due to another exception,
including the pseudo-exceptions PlFail
and
PlExceptionFail
.
To get around this, the various stream I/O functions have wrapper
methods in the PlStream
class that check for an error and
call PlStream::release()
to create the Prolog error, which is thrown as a C++ error.
The destructor calls PlStream::release(), which throws a C++ exception if there is a stream error. This is outside the destructor, so it is safe - the destructor checks if the stream has been released and does nothing in that situation.
The following two code examples do essentially the same thing:
PREDICATE(name_arity, 1) { PlStream strm(Scurrent_output); strm.printf("name = %s, arity = %zd\n", A1.name().as_string().c_str(), A1.arity()); return true; }
PREDICATE(name_arity, 1) { PlStream strm(Scurrent_output); try { strm.printf("name = %s, arity = %zd\n", A1.name().as_string().c_str(), A1.arity()); } PREDICATE_CATCH({strm.release(); return false;}) return true; }
If you write the code as follows, using Sfprintf() directly, it is possible that a fatal exception will be raised on an I/O error:
PREDICATE(name_arity, 1) { PlStream strm(Scurrent_output); Sfprintf(strm, "name = %s, arity = %zd\n", A1.name().as_string().c_str(), A1.arity()); return true; // WARNING: the PlStream destructor might throw a C++ // exception on stack unwinding, giving a fatal // fatal runtime exception. }
If you don't use these, and want to throw an exception if there's an
error, the following code works because PlStream
(and the
underlying PL_acquire_stream()) can be called recursively:
{ PlStream strm(...); strm.release(); }
Many of the “opaque object handles” , such as atom_t
,
term_t
, and functor_t
are integers.24Typically uintptr_t
values, which the C standard defines as “an unsigned integer type
with the property that any valid pointer to void can be converted to
this type, then converted back to pointer to void, and the result will
compare equal to the original pointer.’ As such,
there is no compile-time detection of passing the wrong handle to a
function.
This leads to a problem with classes such as PlTerm
-
C++ overloading cannot be used to distinguish, for example, creating a
term from an atom versus creating a term from an integer. There are a
number of possible solutions, including:
struct
instead of an
integer.It is impractical to change the C code, both because of the amount of edits that would be required and also because of the possibility that the changes would inhibit some optimizations.
There isn't much difference between subclasses versus tags; but as a matter of design, it's better to specify things as constants than as (theoretically) variables, so the decision was to use subclasses.
The utility program swipl-ld (Win32: swipl-ld.exe) works with both C and C++ programs. See Linking embedded applications using swipl-ld for more details.
Your C++ compiler should support at least C++-17.
To avoid incompatibilities amongst the various C++ compilers’ABIs,
the object file from compiling SWI-cpp2.cpp
is not included
in the shared object libswipl
; instead, it must be compiled
along with any foreign predicate files. If the macro
_SWI_CPP2_CPP_SEPARATE
is defined before the include for
SWI-cpp2.h
, then SWI-cpp2.cpp
is not
automatically included and must be compiled separately - either by
creating a
.a
file or by adding a #include <SWI-cpp2.cpp>
to one of your source files.