9 Foreign Language Interface

SWI-Prolog offers a powerful interface to C Kernighan & Ritchie, 1978. The main design objectives of the foreign language interface are flexibility and performance. A foreign predicate is a C-function that has the same number of arguments as the predicate represented. C-functions are provided to analyse the passed terms, convert them to basic C-types as well as to instantiate arguments using unification. Non-deterministic foreign predicates are supported, providing the foreign function with a handle to control backtracking.

C can call Prolog predicates, providing both an query interface and an interface to extract multiple solutions from an non-deterministic Prolog predicate. There is no limit to the nesting of Prolog calling C, calling Prolog, etc. It is also possible to write the `main' in C and use Prolog as an embedded logical engine.


Section Index


9.1 Overview of the Interface
9.2 Linking Foreign Modules
9.2.1 What linking is provided?
9.2.2 What kind of loading should I be using?
9.3 Dynamic Linking of shared libraries
9.4 Using the library shlib for .DLL and .so files
9.4.1 Static Linking
9.5 Interface Data types
9.5.1 Type term_t: a reference to a Prolog term
9.5.1.1 Interaction with the garbage collector and stack-shifter
9.5.2 Other foreign interface types
9.6 The Foreign Include File
9.6.1 Argument Passing and Control
9.6.1.1 Non-deterministic Foreign Predicates
9.6.2 Atoms and functors
9.6.2.1 Atoms and atom-garbage collection
9.6.3 Analysing Terms via the Foreign Interface
9.6.3.1 Testing the type of a term
9.6.3.2 Reading data from a term
9.6.3.3 Exchanging text using length and string
9.6.3.4 Wide character versions
9.6.3.5 Reading a list
9.6.3.6 An example: defining write/1 in C
9.6.4 Constructing Terms
9.6.5 Unifying data
9.6.6 BLOBS: Using atoms to store arbitrary binary data
9.6.6.1 Defining a BLOB type
9.6.6.2 Accessing blobs
9.6.7 Exchanging GMP numbers
9.6.8 Calling Prolog from C
9.6.8.1 Predicate references
9.6.8.2 Initiating a query from C
9.6.9 Discarding Data
9.6.10 Foreign Code and Modules
9.6.11 Prolog exceptions in foreign code
9.6.12 Catching Signals (Software Interrupts)
9.6.13 Miscellaneous
9.6.13.1 Term Comparison
9.6.13.2 Recorded database
9.6.13.3 Getting file names
9.6.14 Errors and warnings
9.6.15 Environment Control from Foreign Code
9.6.16 Querying Prolog
9.6.17 Registering Foreign Predicates
9.6.18 Foreign Code Hooks
9.6.19 Storing foreign data
9.6.19.1 Examples for storing foreign data
9.6.20 Embedding SWI-Prolog in other applications
9.6.20.1 Threading, Signals and embedded Prolog
9.7 Linking embedded applications using plld
9.7.1 A simple example
9.8 The Prolog `home' directory
9.9 Example of Using the Foreign Interface
9.10 Notes on Using Foreign Code
9.10.1 Memory Allocation
9.10.2 Compatibility between Prolog versions
9.10.3 Debugging and profiling foreign code (valgrind)
9.10.4 Name Conflicts in C modules
9.10.5 Compatibility of the Foreign Interface