- 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
- BLOBS: Using atoms to store arbitrary binary data
- Exchanging GMP numbers
- Calling Prolog from C
- Discarding Data
- 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
11.4.21 Embedding SWI-Prolog in other applications
With embedded Prolog we refer to the situation where the `main' program is not the Prolog application. Prolog is sometimes embedded in C, C++, Java or other languages to provide logic based services in a larger application. Embedding loads the Prolog engine as a library to the external language. Prolog itself only provides for embedding in the C language (compatible with C++). Embedding in Java is achieved using JPL using a C-glue between the Java and Prolog C interfaces.
The most simple embedded program is below. The interface function PL_initialise() must be called before any of the other SWI-Prolog foreign language functions described in this chapter, except for PL_initialise_hook(), PL_new_atom(), PL_new_functor() and PL_register_foreign(). PL_initialise() interprets all the command line arguments, except for the -t toplevel flag that is interpreted by PL_toplevel().
int main(int argc, char **argv) { if ( !PL_initialise(argc, argv) ) PL_halt(1); PL_halt(PL_toplevel() ? 0 : 1); }
- int PL_initialise(int argc, char **argv)
- Initialises the SWI-Prolog heap and stacks, restores the Prolog state,
loads the system and personal initialisation files, runs the initialization/1
hooks and finally runs the
-g goal hook.
Special consideration is required for
argv[0]
. On Unix, this argument passes the part of the command line that is used to locate the executable. Prolog uses this to find the file holding the running executable. The Windows version uses this to find a module of the running executable. If the specified module cannot be found, it tries the modulelibpl.dll
, containing the Prolog runtime kernel. In all these cases, the resulting file is used for two purposes:- See whether a Prolog saved state is appended to the file. If this is
the case, this state will be loaded instead of the default
boot.prc
file from the SWI-Prolog home directory. See also qsave_program/[1,2] and section 11.5. - Find the Prolog home directory. This process is described in detail in section 11.6.
PL_initialise() returns 1 if all initialisation succeeded and 0 otherwise.bugVarious fatal errors may cause PL_initialise() to call PL_halt(1), preventing it from returning at all.
In most cases, argc and argv will be passed from the main program. It is allowed to create your own argument vector, provided
argv[0]
is constructed according to the rules above. For example:int main(int argc, char **argv) { char *av[10]; int ac = 0; av[ac++] = argv[0]; av[ac++] = "-x"; av[ac++] = "mystate"; av[ac] = NULL; if ( !PL_initialise(ac, av) ) PL_halt(1); ... }
Please note that the passed argument vector may be referred from Prolog at any time and should therefore be valid as long as the Prolog engine is used.
A good setup in Windows is to add SWI-Prolog's
bin
directory to yourPATH
and either pass a module holding a saved state, or"libpl.dll"
asargv[0]
. If the Prolog state is attached to a DLL (see the -dll option of swipl-ld), pass the name of this DLL. - See whether a Prolog saved state is appended to the file. If this is
the case, this state will be loaded instead of the default
- int PL_is_initialised(int *argc, char ***argv)
- Test whether the Prolog engine is already initialised. Returns
FALSE
if Prolog is not initialised andTRUE
otherwise. If the engine is initialised and argc is notNULL
, the argument count used with PL_initialise() is stored in argc. Same for the argument vector argv. - int PL_set_resource_db_mem(const unsigned char *data, size_t size)
- This function must be called at most once and before calling
PL_initialise().
The memory area designated by data and size must
contain the resource data and be in the format as produced by
qsave_program/2.
The memory area is accessed by PL_initialise()
as well as calls to open_resource/3.177This
implies that the data must remain accessible during the lifetime of the
process if open_resource/3
is used. Future versions may provide a function to detach the resource
database and cause open_resource/3
to raise an exception.
For example, we can include the bootstrap data into an embedded executable using the steps below. The advantage of this approach is that it is fully supported by any OS and you obtain a single file executable.
- Create a saved state using qsave_program/2
or
% swipl -o state -c file.pl ...
- Create a C source file from the state using e.g., the Unix utility xxd(1):
% xxd -i state > state.h
- Embed Prolog as in the example below. Instead of calling the
toplevel you probably want to call your application code.
#include <SWI-Prolog.h> #include "state.h" int main(int argc, char **argv) { if ( !PL_set_resource_db_mem(state, state_len) || !PL_initialise(argc, argv) ) PL_halt(1); return PL_toplevel(); }
Alternative to xxd, it is possible to use inline assembler, e.g. the gcc
incbin
instruction. Code for gcc was provided by Roberto Bagnara on the SWI-Prolog mailinglist. Given the state in a filestate
, create the following assembler program:.globl _state .globl _state_end _state: .incbin "state" _state_end:
Now include this as follows:
#include <SWI-Prolog.h> #if __linux #define STATE _state #define STATE_END _state_end #else #define STATE state #define STATE_END state_end #endif extern unsigned char STATE[]; extern unsigned char STATE_END[]; int main(int argc, char **argv) { if ( !PL_set_resource_db_mem(STATE, STATE_END - STATE) || !PL_initialise(argc, argv) ) PL_halt(1); return PL_toplevel(); }
As Jose Morales pointed at https://github.com/graphitemaster/incbin, which contains a portability layer on top of the above idea.
- Create a saved state using qsave_program/2
or
- int PL_toplevel()
- Runs the goal of the -t toplevel switch (default prolog/0) and returns 1 if successful, 0 otherwise.
- int PL_cleanup(int status)
- This function performs the reverse of PL_initialise().
It runs the
PL_on_halt()
and at_halt/1
handlers, closes all streams (except for the `standard I/O' streams
which are flushed only), deallocates all memory if status
equals `0' and restores all signal handlers. The
status argument is passed to the various termination hooks
and indicates the exit-status.
The function returns
TRUE
if successful andFALSE
otherwise. Currently,FALSE
is returned when an attempt is made to call PL_cleanup() recursively or if one of the exit handlers cancels the termination using cancel_halt/1. Exit handlers may only cancel termination if status is 0.In theory, this function allows deleting and restarting the Prolog system in the same process. In practice, SWI-Prolog's cleanup process is far from complete, and trying to revive the system using PL_initialise() will leak memory in the best case. It can also crash the appliction.
In this state, there is little practical use for this function. If you want to use Prolog temporarily, consider running it in a separate process. If you want to be able to reset Prolog, your options are (again) a separate process, modules or threads.
- void PL_cleanup_fork()
- Stop intervaltimer that may be running on behalf of profile/1.
The call is intended to be used in combination with fork():
if ( (pid=fork()) == 0 ) { PL_cleanup_fork(); <some exec variation> }
The call behaves the same on Windows, though there is probably no meaningful application.
- int PL_halt(int status)
- Clean up the Prolog environment using PL_cleanup()
and if successful call exit() with the status argument. Returns
FALSE
if exit was cancelled by PL_cleanup().
11.4.21.1 Threading, Signals and embedded Prolog
This section applies to Unix-based environments that have signals or multithreading. The Windows version is compiled for multithreading, and Windows lacks proper signals.
We can distinguish two classes of embedded executables. There are small C/C++ programs that act as an interfacing layer around Prolog. Most of these programs can be replaced using the normal Prolog executable extended with a dynamically loaded foreign extension and in most cases this is the preferred route. In other cases, Prolog is embedded in a complex application that---like Prolog---wants to control the process environment. A good example is Java. Embedding Prolog is generally the only way to get these environments together in one process image. Java VMs, however, are by nature multithreaded and appear to do signal handling (software interrupts).
On Unix systems, SWI-Prolog installs handlers for the following signals:
- SIGUSR2
- has an empty signal handler. This signal is sent to a thread after
sending a thread-signal (see
thread_signal/2).
It causes blocking system calls to return with
EINTR
, which gives them the opportunity to react to thread-signals.In some cases the embedded system and SWI-Prolog may both use
SIGUSR2
without conflict. If the embedded system redefinesSIGUSR2
with a handler that runs quickly and no harm is done in the embedded system due to spurious wakeup when initiated from Prolog, there is no problem. If SWI-Prolog is initialised after the embedded system it will call the handler set by the embedded system and the same conditions as above apply. SWI-Prolog's handler is a simple function only chaining a possibly previously registered handler. SWI-Prolog can handle spuriousSIGUSR2
signals. - SIGINT
- is used by the top level to activate the tracer (typically bound to control-C). The first control-C posts a request for starting the tracer in a safe, synchronous fashion. If control-C is hit again before the safe route is executed, it prompts the user whether or not a forced interrupt is desired.
- SIGTERM, SIGABRT and SIGQUIT
- are caught to cleanup before killing the process again using the same signal.
- SIGSEGV, SIGILL, SIGBUS, SIGFPE and SIGSYS
- are caught by to print a backtrace before killing the process again using the same signal.
- SIGHUP
- is caught and causes the process to exit with status 2 after cleanup.
The --nosignals option can be used to inhibit all
signal processing except for SIGUSR2
. The handling of SIGUSR2
is vital for dealing with blocking system call in threads. The used
signal may be changed using the --sigalert=NUM option
or disabled using --sigalert=0
.