- Documentation
- Reference manual
- Foreign Language Interface
- The Foreign Include File
- Argument Passing and Control
- Atoms and functors
- Analysing Terms via the Foreign Interface
- Constructing Terms
- Unifying data
- Convenient functions to generate Prolog exceptions
- Foreign language wrapper support functions
- Serializing and deserializing Prolog terms
- BLOBS: Using atoms to store arbitrary binary data
- Exchanging GMP numbers
- Calling Prolog from C
- Discarding Data
- String buffering
- Foreign Code and Modules
- Prolog exceptions in foreign code
- Catching Signals (Software Interrupts)
- Miscellaneous
- Errors and warnings
- Environment Control from Foreign Code
- Querying Prolog
- Registering Foreign Predicates
- Foreign Code Hooks
- Storing foreign data
- Embedding SWI-Prolog in other applications
- The Foreign Include File
- Foreign Language Interface
- Packages
- Reference manual
It is obligatory to call either of the two closing functions to discard a foreign frame. Foreign frames may be nested.
int count_atoms() { fid_t fid = PL_open_foreign_frame(); term_t goal = PL_new_term_ref(); term_t a1 = PL_new_term_ref(); term_t a2 = PL_new_term_ref(); functor_t s2 = PL_new_functor(PL_new_atom("statistics"), 2); int atoms; PL_put_atom_chars(a1, "atoms"); PL_cons_functor(goal, s2, a1, a2); PL_call(goal, NULL); /* call it in current module */ PL_get_integer(a2, &atoms); PL_discard_foreign_frame(fid); return atoms; }
12.4.13 String buffering
Many of the functions of the foreign language interface involve
strings. Some of these strings point into static memory like those
associated with atoms. These strings are valid as long as the atom is
protected against atom garbage collection, which generally implies the
atom must be locked using PL_register_atom()
or be part of an accessible term. Other strings are more volatile.
Several functions provide a BUF_* flag that can be set to either BUF_STACK
(default) or
BUF_MALLOC
. Strings returned by a function accepting
BUF_MALLOC
must be freed using PL_free().
Strings returned using BUF_STACK
are pushed on a stack that
is cleared when a foreign predicate returns control back to Prolog. More
fine grained control may be needed if functions that return strings are
called outside the context of a foreign predicate or a foreign predicate
creates many strings during its execution. Temporary strings are scoped
using these macros: