"sec:foreign-get-iostream">12.9.1 Get
IO stream handles
There are several ways to get access to an IO Stream handle,
basically get them from Prolog, get access to the standard streams and
create a new stream. The standard streams are available as
Sinput
, Soutput
and Serror
. Note
that these are thread specific. Creating a new stream is discussed with Snew().
Below are the functions to obtain a stream handle from a Prolog term,
obtain and release ownership.
- int PL_get_stream(term_t t, IOSTREAM **s, int flags)
- Get a stream handle from the Prolog term t. Returns
TRUE
on success andFALSE
on failure, by default generating an exception. The flags argument is a bitwise disjunction of these flags:SIO_INPUT
- Get an input stream. If t is a stream pair (see stream_pair/3), return the input channel. If t is an output stream the function fails.
SIO_OUTPUT
- Get an output stream. See
SIO_INPUT
for details. If neitherSIO_OUTPUT
norSIO_INPUT
is given t may not be a pair. SIO_NOERROR
- If the function fails no exception is produced.
The returned stream is owned by the calling thread using PL_acquire_stream().
- int PL_get_stream_from_blob(atom_t b, IOSTREAM **s, int flags)
- Same as PL_get_stream(),
but operates directly on the blob b. This allows for foreign
code that wishes long term access to a stream to maintain a handle to
the stream as a (registered)
atom_t
object rather than aIOSTREAM*
. - IOSTREAM * PL_acquire_stream(IOSTREAM *s)
- Obtain ownership of s and return s. The application must call PL_release_stream() when done. Only one thread can own a stream and this call blocks if some other thread owns the stream. Note that PL_get_stream() acquires ownership. This function may be called multiple times by the same thread (recursive lock).
- int PL_release_stream(IOSTREAM *s)
- Give up ownership acquired using PL_acquire_stream()
or PL_get_stream().
If the stream is an an error state, return
FALSE
with an exception. Otherwise returnTRUE
.
Below is an example that writes “Hello World'' to a stream provided by Prolog.
static foreign_t hello_world(term_t to) { IOSTREAM *s; if ( PL_get_stream(to, &s, SIO_OUTPUT) ) { Sfprintf(s, "Hello World!\n"); return PL_release_stream(s); } return FALSE; } ... // fragment from install function PL_register_foreign("hello world", 1, hello_world, 0);