Loading Foreign Executables

The built-in Prolog predicate load_foreign_executable/1 is used to load foreign functions directly into Prolog from a shared object file and to attach selected functions and routines in the loaded file to Prolog predicates.

The example below demonstrates the use of these predicates to load code compiled using the C compiler.

In the above example, foreign (or foreign.pl) is a file containing facts that describe how Prolog is to call the foreign functions. If it is given a filename without an extension then it automatically appends the appropriate extension; thus in the example above, math is specified to load math.so.

The loading process may fail if:

If the load does not complete successfully then an exception is raised and the call to load_foreign_executable/1 fails; no change is made to the Prolog state. The load can be retried once the problem has been corrected.

Once a foreign program is loaded, it cannot be unloaded or replaced, although you can abolish or redefine any procedure attached to it.

Notes:

  1. Any foreign file loaded via a load_foreign_executable/1 command that is embedded in a file being loaded into Prolog will be sought relative to the directory from which the file is being loaded. For example, if the file /usr/fred/test.pl contains the command
                   :- load_foreign_executable(test).
                   

    then the file to be loaded would be /usr/fred/test.so.

  2. When the linker is given a library such as -lX11, it will look for a "shared library" version and if one exists record this library as a dependency in the shared object file. load_foreign_executable/1 will then automatically load this library (if not already loaded) when it loads the shared object file.

    If the linker is given a library for which no shared library exists, then object files from the static library are incorporated into the shared object file as needed. This means that any routine in a static library that is to be accessed from Prolog must have some reference to it in one of the object files being linked into the shared object file.

  3. It is better to load one large shared object file than many small ones. You may have several Prolog files that require routines from one shared object file -- in other words, a shared library. The shared library is only loaded once, but different functions could be attached to Prolog predicates in different calls to load_foreign_executable/1. For example, under UNIX, most of the files in the Prolog Library that load foreign code use the shared library file libpl.so.

A description of the internal operation of the load_foreign_executable/1 predicate is given in fli-p2f-lfe to help solve more difficult foreign code loading problems.