Each argument of a foreign function (except for the control argument)
is of type term_t, an opaque handle to a Prolog term. Three
groups of functions are available for the analysis of terms. The first
just validates the type, like the Prolog predicates var/1, atom/1,
etc., and are called PL_is_*(). The second group attempts
to translate the argument into a C primitive type. These predicates take
a term_t and a pointer to the appropriate C type and return TRUE
or
FALSE depending on successful or unsuccessful translation.
If the translation fails, the pointed-to data is never modified.
PL_get_*() also
validate the type and thus the two sections below are equivalent.
if ( PL_is_atom(t) )
{ char *s;
PL_get_atom_chars(t, &s);
...;
}
or
char *s;
if ( PL_get_atom_chars(t, &s) )
{ ...;
}
Version 7 added PL_NIL, PL_BLOB,
PL_LIST_PAIR and PL_DICT. Older versions
classify PL_NIL and PL_BLOB as PL_ATOM,
PL_LIST_PAIR as PL_TERM and do not have dicts.
PL_VARIABLE | A variable or attributed variable |
PL_ATOM | A Prolog atom |
PL_NIL | The constant [] |
PL_BLOB | A blob (see section 12.4.10.2) |
PL_STRING | A string (see section 5.2) |
PL_INTEGER | A integer |
PL_RATIONAL | A rational number |
PL_FLOAT | A floating point number |
PL_TERM | A compound term |
PL_LIST_PAIR | A list cell ([H|T]) |
PL_DICT | A dict (see section 5.4)) |
The functions PL_is_<type> are an alternative to PL_term_type().
The test PL_is_variable(term)
is equivalent to
PL_term_type(term)
== PL_VARIABLE, but the first is considerably faster. On the
other hand, using a switch over PL_term_type()
is faster and more readable then using an if-then-else using the
functions below. All these functions return either TRUE or FALSE.
The functions PL_get_*() read information from a Prolog
term. Most of them take two arguments. The first is the input term and
the second is a pointer to the output value or a term reference. The
return value is TRUE or FALSE, indicating the
success of the "get" operation. Most functions have a related "_ex"
function that raises an error if the argument is the operation cannot be
completed. If the Prolog term is not suitable, this is a type, domain or
instantiation error. If the receiving C type cannot represent the value
this is a representation error.
For integers an alternative interface exists, which helps deal with
the various integer types in C and C++. They are convenient for use with
_Generic selection or C++ overloading.
BUF_STACK implies, if the data is not static (as from an
atom), that the data is pushed on a stack. If BUF_MALLOC is
used, the data must be freed using PL_free()
when no longer needed.
With the introduction of wide characters (see section
2.18.1), not all atoms can be converted into a char*.
This function fails if t is of the wrong type, but also if
the text cannot be represented. See the REP_* flags below
for details. See also PL_get_wchars()
and PL_get_nchars().
Text that contains a 0-code cannot be represented as a 0-terminated
string. If such text is converted by PL_get_chars()
or another function that does not return the length, the function fails
or, if
CVT_EXCEPTION is given, raises the exception
representation_error(nul_terminated_string(Text)). Text is
the converted term: an atom, string, code or character list, or any term
if one of the “CVT_WRITE*” flags is used. The name refers to
the C representation and not to the Prolog string type.
The first set of flags (CVT_ATOM through CVT_VARIABLE,
if set, are tested in order, using the first that matches. If none of
these match, then a check is made for one of CVT_WRITE,
CVT_WRITE_CANONICAL, CVT_WRITEQ being set. If
none of the “CVT_WRITE*” flags are set, then a type_error
is raised.
CVT_RATIONAL to represent rational numbers using
hexadecimal notation. Hexadecimal notation is notably useful for
transferring big integers to other programming environments if the
target system can read hexadecimal notation because the result is both
more compact and faster to write and read.CVT_RATIONAL|CVT_FLOAT.
Note that
CVT_INTEGER is implied by CVT_RATIONAL.CVT_NUMBER|CVT_ATOM|CVT_STRING.CVT_XINTEGER is not
implied). Note that this does not include variables or terms (with the
exception of a list of characters/codes). Equivalent to
CVT_ATOMIC|CVT_LIST._3290).BUF_* is provided, BUF_STACK is implied.CVT_WRITE, but using writeq/2.CVT_WRITE, but using write_canonical/2.BUF_STACK is safe, but slower. Also, some flags
can cause BUF_DISCARDABLE to be treated as
BUF_STACK. See section
12.4.14.BUF_RING is an alias
for
BUF_STACK. BUF_STACK is the default if
BUF_MALLOC is not specified. BUF_STACK should
not be used inside a loop, unless it is within a (PL_STRINGS_MARK-PL_STRINGS_RELEASE).
See
section 12.4.14.BUF_MALLOC is specified, BUF_STACK
is ignored. See section
12.4.14.PL_get_chars(l, s,
CVT_LIST|flags), provided flags
contains none of the CVT_* flags.FALSE.
If t is a floating point number that can be represented as a
long, this function succeeds as well. See also PL_get_int64()
and PL_get_long_ex().int64_t, assign its value over i. See also PL_get_int64_ex().uint64_t, assign its value over i. Note that
this requires GMP support for representing uint64_t values
with the high bit set. See also PL_get_uint64_ex().true, false, set val
to the C constant TRUE or FALSE and return
success, otherwise return failure. The values on, 1, off,
0 and are also accepted. PL_get_stdbool_ex()
deals with the C11
bool type while PL_get_bool_ex()
targetted C standard versions before the introduction of bool..qlf file or used in arithmetic. PL_get_pointer()
only succeeds on a pointer integer, so a plain integer typed by the user
or computed using arithmetic is not taken for a pointer. A pointer must
fit in a small integer (max_tagged_integer);
otherwise PL_put_pointer()
and
PL_unify_pointer()
raise a representation error. The exception is 64-bit Android, which
keeps a tag in the top byte of heap pointers: there such pointers are
represented as plain integers and
PL_get_pointer()
accepts integers that are too large to be small. Representing C pointers
as integers is unsafe: the pointer may be used after the object
it points at is deallocated. The
blob API described in section
12.4.10 provides a safe way for handling foreign resources that
cooperates with Prolog garbage collection.NULL). This is the same as PL_get_name_arity(),
but this function fails if t is an atom.FALSE if t is not a compound or index
is out of range (zero or higher than the arity of the compound). This
function never raises a Prolog exception.term_t
and calling an API function for each argument. The type
pl_value_t is defined as below.
typedef struct pl_value
{ uint64_t type : 8; /* PL_VARIABLE, PL_ATOM, ... */
uint64_t length : 56; /* length of value.s */
union
{ int64_t i; /* PL_INT64 */
double f; /* PL_FLOAT; numbers if PL_AS_FLOAT */
atom_t a; /* PL_ATOM, PL_NIL, PL_BLOB */
functor_t t; /* PL_TERM, PL_LIST_PAIR, PL_DICT */
char *s; /* text (see CVT_*, REP_*, BUF_*) */
} value;
} pl_value_t;
The field type is the type of the argument and is one of
PL_VARIABLE, PL_ATOM, PL_NIL, PL_BLOB,
PL_INT64, PL_INTEGER (an integer that does not
fit in 64 bits), PL_RATIONAL, PL_FLOAT, PL_STRING,
PL_TERM, PL_LIST_PAIR or PL_DICT.
The type and flags decide which member of value
is filled. Text is stored in s with its length in bytes in length,
using the REP_* and BUF_* flags as PL_get_nchars().
The following flags decide on the conversion:
a holds the atom
handle. The empty list and blobs always use a.CVT_XINTEGER, the text is hexadecimal.1r3.double in f. The field
type still tells the type of the number. This flag is an
alias for CVT_FLOAT. The function fails or, using
CVT_EXCEPTION, raises a float overflow error if a number
cannot be represented as a float.
Strings are always represented as text. Floats are always represented
as f. Variables and compound terms are never converted. For
compound terms, t holds the functor.
The function fails silently if from and count
are not a valid range of arguments. If t is not compound, it
fails or raises a type error if CVT_EXCEPTION is given. If
the function fails using BUF_MALLOC, no text needs to be
freed.
All internal text representation in SWI-Prolog is represented using
char * plus length and allow for 0-bytes in them.
The foreign library supports this by implementing a *_nchars()
function for each applicable *_chars() function. Below we briefly
present the signatures of these functions. For full documentation
consult the *_chars() function.
NULL. If len
is not NULL, the text may contain 0-codes.In addition, the following functions are available for creating and inspecting atoms:
(size_t)-1,
it is computed from s using
strlen(). See PL_new_atom()
for error handling.
Support for exchange of wide-character strings is still under
consideration. The functions dealing with 8-bit character strings return
failure when operating on a wide-character atom or Prolog string object.
The functions below can extract and unify both 8-bit and wide atoms and
string objects. Wide character strings are represented as C arrays of
objects of the type pl_wchar_t, which is guaranteed to be
the same as wchar_t on platforms supporting this type. For
example, on MS-Windows, this represents a 16-bit UTF-16 string, while
using the GNU C library (glibc) this represents 32-bit UCS4 characters.
(size_t)-1,
it is computed from s using wcslen(). See PL_new_atom()
for error handling.PL_ATOM, PL_STRING,
PL_CODE_LIST or PL_CHAR_LIST.PL_CODE_LIST and PL_CHAR_LIST.
It serves two purposes. It allows for returning very long lists from
data read from a stream without the need for a resizing buffer in C.
Also, the use of difference lists is often practical for further
processing in Prolog. Examples can be found in packages/clib/readutil.c
from the source distribution.NULL, the input is a 0-terminated string:
the decoder never reads past the 0-byte. Returns the number of bytes
consumed, or -1 if the sequence is invalid. Only the shortest encoding
of a code point up to U+10FFFF is valid. An invalid sequence consumes
one byte and returns that byte in cp, except for a surrogate
(U+D800 ... U+DFFF), which consumes the sequence and returns U+FFFD.
This is the decoder Prolog uses for UTF-8 text, so foreign code using it
agrees with Prolog on, e.g., the number of characters in invalid UTF-8.
ASCII is decoded inline.
The result is locale-independent and identical on every supported
platform. Width data is sourced at table-build time from
EastAsianWidth.txt (UAX #11) and the general-category
property, and stored as two bits in each uflags_map entry
alongside the syntax classification used by the parser; runtime lookups
are a single byte fetch. The Unicode version that drives the table is
reported by the unicode_syntax_version
flag (see
section 2.15.1.9).
The argument is a full 32-bit code point. Avoid casting to
wchar_t before the call: wchar_t is 16-bit on
Windows, and the cast silently drops non-BMP characters.
src/Unicode/ and consulted by the
Prolog reader. Provided so foreign extensions and embedded toolkits
(notably xpce) classify code points exactly as SWI-Prolog does, locale-
independently. id_start and id_continue follow
Prolog's identifier syntax (close to UAX #31 XID_Start /
XID_Continue, adjusted for Prolog). layout matches the
reader's whitespace set (white_space/1 in
src/Unicode/derived_core_properties.pl).if ( PL_ctype_flags(c) & PL_CTYPE_ALPHA ) ...
PL_CTYPE_ALNUM | PL_CTYPE_ALPHA
or a numeric character |
PL_CTYPE_ALPHA | Unicode Alphabetic |
PL_CTYPE_CNTRL | general category Cc or Cf |
PL_CTYPE_DIGIT | 0 ...9,
as POSIX demands |
PL_CTYPE_GRAPH | printable and not white space |
PL_CTYPE_LOWER | Unicode Lowercase |
PL_CTYPE_PRINT | PL_CTYPE_GRAPH
or white space |
PL_CTYPE_PUNCT | printable, neither alnum nor space |
PL_CTYPE_SPACE | Unicode White_Space |
PL_CTYPE_UPPER | Unicode Uppercase |
This is the classifier behind code_type/2
and char_type/2
and a locale-independent replacement for the <wctype.h>
functions
iswalpha(), iswspace(), ... Besides not varying with
LC_CTYPE, it does not vary between C libraries (glibc and
Darwin disagree on whether U+00A0 and U+0085 are white space, for
example) and it answers for the full Unicode range also on Windows,
where wint_t is 16 bits and the <wctype.h>
functions silently fail for non-BMP code points.
Simple means one code point in, one code point out, so conversion is
length preserving: U+00DF LATIN SMALL LETTER SHARP S and the ligatures
are returned unchanged rather than expanded to SS,
FI, ... as SpecialCasing.txt would have it.
As with the classes, the mapping comes from the Unicode Character
Database and is therefore the same in every locale --- notably it does
not apply the Turkish and Azeri dotted/dotless i rules ---
and on every platform, and it works for non-BMP code points also on
Windows.
The functions from this section are intended to read a Prolog list from C. Suppose we expect a list of atoms; the code below will print the atoms, each on a line. Please note the following:
term_t term reference for the
elements (head). This reference is reused for each element.term_t. As it is not allowed to
overwrite the term_t passed in as arguments to a predicate,
we must
copy the argument term_t.char*. We want it to convert atoms, return the
result as a multibyte string (REP_UTF8 may also be
used) and finally we want an exception on type, instantiation or
representation errors (if the system's default encoding cannot represent
some characters of the Unicode atom). This may create temporary copies
of the atom text - PL_STRINGS_MARK() ... PL_STRINGS_RELEASE()
handles that._ex suffix, but they raise type, domain,
or instantiation errors when the input is invalid; whereas the plain
version may only raise resource exceptions if the request cannot be
fulfilled due to resource exhaustion.
foreign_t
pl_write_atoms(term_t l)
{ term_t head = PL_new_term_ref(); /* the elements */
term_t tail = PL_copy_term_ref(l); /* copy (we modify tail) */
int rc = TRUE;
while( rc && PL_get_list_ex(tail, head, tail) )
{ PL_STRINGS_MARK();
char *s;
if (rc=PL_get_chars(head, &s, CVT_ATOM|REP_MB|CVT_EXCEPTION)) )
rc = Sfprintf(Scurrent_output, "%s\n", s);
PL_STRINGS_RELEASE();
}
return rc && PL_get_nil_ex(tail); /* test end for [] */
}
Note that as of version 7, lists have a new representation unless the option --traditional is used. see section 5.1.
It is allowed to pass 0 for tail and NULL for len.
(size_t)-1, call func
for all elements from start to the end of the list. The type
of func is below. The argument index is the index
of the element in the slice, i.e., it starts at 0 for the element start.
typedef int (*pl_list_slice_f)(term_t elem, size_t index, void *closure);
The term reference elem is reused for all elements and is
only valid during the call to func. func may call
any API function, including functions that create terms or call Prolog.
If
func returns FALSE, PL_get_list_slice()
stops and returns
FALSE, leaving an exception raised by func in
place. If
count is not NULL, it is filled with the number
of elements processed.
The function returns FALSE if the list is too short, if
length is (size_t)-1 and the list is partial,
does not end in or is cyclic, or if the
list is partial, not a list or cyclic before the end of the slice. If flags
includes
[]CVT_EXCEPTION, a partial list raises an instantiation error
and a cyclic list or a term that is not a list raises a type error. A
list that is too short does not raise an exception. Cycles are detected
without extra cost for short lists. Below is the list example using this
function:
static int
write_atom(term_t a, size_t index, void *closure)
{ int rc;
char *s;
PL_STRINGS_MARK();
if ( (rc=PL_get_chars(a, &s, CVT_ATOM|REP_MB|CVT_EXCEPTION)) )
rc = Sfprintf(closure, "%s\n", s) >= 0;
PL_STRINGS_RELEASE();
return rc;
}
foreign_t
pl_write_atoms(term_t l)
{ return PL_get_list_slice(l, 0, (size_t)-1,
write_atom, Scurrent_output,
NULL, CVT_EXCEPTION);
}
Below is an example. While PL_option_t is a struct, its
members are initialised using the PL_OPTION() macro. The data
structure is not constant because PL_scan_options()
adds the option names as
atoms to speed up option processing. The macro PL_OPTIONS_END
terminates the option list.
static PL_option_t mypred_options[] =
{ PL_OPTION("quoted", OPT_BOOL),
PL_OPTION("length", OPT_SIZE),
PL_OPTION("callback", OPT_TERM),
PL_OPTIONS_END
};
static foreign_t
mypred(term_t a1, term_t options)
{ int quoted = FALSE;
size_t length = 10;
term_t callback = 0;
if ( !PL_scan_options(options, 0, "mypred_options", mypred_options,
"ed, &length, &callback) )
return FALSE;
<implement mypred>
}
The only defined value for flags is currently OPT_ALL,
which causes this function to raise a domain error if an option is
passed that is not in specs. Default in SWI-Prolog is to
silently ignore unknown options, unless the Prolog flag iso
is true. The opttype argument defines the type
(group) of the options, e.g., "write_option". Option types
are defined by the ISO standard. SWI-Prolog only uses this if OPT_ALL
is specified, to raise a domain_error of the indicated type
if some option is unused. The type name is normally the name of the
predicate followed by
_option or the name of a representative of a group of
predicates to which the options apply.
Defined option types and their corresponding pointer type are described below.
OPT_BOOL intOPT_STDBOOL boolTRUE.OPT_INT intOPT_INT64 int64_tOPT_UINT64 uint64_tOPT_SIZE size_tOPT_DOUBLE doubleOPT_STRING char*CVT_ALL|REP_UTF8|BUF_STACK|CVT_EXCEPTION. The buffered
string must be guarded using PL_STRINGS_MARK()
and PL_STRINGS_RELEASE().OPT_ATOM atom_tOPT_TERM term_tThe ISO standard demands that if an option is repeated the last occurrence holds. This implies that PL_scan_options() must scan the option list to the end.
Figure 6 shows a simplified definition of write/1 to illustrate the described functions. This simplified version does not deal with operators. It is called display/1, because it mimics closely the behaviour of this Edinburgh predicate.
foreign_t
pl_display(term_t t)
{ functor_t functor;
int arity, len, n;
char *s;
switch( PL_term_type(t) )
{ case PL_VARIABLE:
case PL_ATOM:
case PL_INTEGER:
case PL_FLOAT:
PL_get_chars(t, &s, CVT_ALL);
if (! Sfprintf(Scurrent_output, "%s", s) )
PL_fail;
break;
case PL_STRING:
if ( !PL_get_string_chars(t, &s, &len) &&
!Sfprintf(Scurrent_output, "\"%s\"", s) )
PL_fail;
break;
case PL_TERM:
{ term_t a = PL_new_term_ref();
if ( !PL_get_name_arity(t, &name, &arity) &&
!Sfprintf(Scurrent_output, "%s(", PL_atom_chars(name)) )
PL_fail
for(n=1; n<=arity; n++)
{ if ( ! PL_get_arg(n, t, a) )
PL_fail;
if ( n > 1 )
if ( ! Sfprintf(Scurrent_output, ", ") )
PL_fail;
if ( !pl_display(a) )
PL_fail;
}
if ( !Sfprintf(Scurrent_output, ")") )
PL_fail;
break;
default:
PL_fail; /* should not happen */
}
}
PL_succeed;
}