Home Contents Index Summary Previous Next

6.2 Runtimes and Foreign Code

Some applications may need to use the foreign language interface. Object code is by definition machine-dependent and thus cannot be part of the saved program file.

To complicate the matter even further there are various ways of loading foreign code:

To make a runtime executable that can run on multiple platforms one must make runtime checks to find the correct way of linking. Suppose we have a source-file myextension defining the installation function install().

If this file is compiled into a shared library, load_foreign_library/1 will load this library and call the installation function to initialise the foreign code. If it is loaded as a static extension, define install() as the predicate install/0:


static foreign_t
pl_install()
{ install();

  PL_succeed;
}

PL_extension PL_extensions [] =
{
/*{ "name",     arity,  function,       PL_FA_<flags> },*/

  { "install",  0,      pl_install,     0 },
  { NULL,       0,      NULL,           0 }     /* terminating line */
};

Now, use the following Prolog code to load the foreign library:


load_foreign_extensions :-
        current_predicate(install, install), !, % static loaded
        install.
load_foreign_extensions :-                      % shared library
        load_foreign_library(foreign(myextension)).

:- initialization load_foreign_extensions.

The path alias foreign is defined by file_search_path/2. By default it searches the directories <home>/lib/<arch> and <home>/lib. The application can specify additional rules for file_search_path/2.