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