10.35.7 Interfacing with Foreign Code

Foreign terms may be passed between Prolog and other languages through the foreign interface.

To use this, all foreign types to be passed between Prolog and another language must be declared with foreign_type/2 before the foreign/[2,3] clauses specifying the foreign functions.

The structs package extends the foreign type specifications recognized by the foreign interface. In addition to the types already recognized by the foreign interface, any atomic type recognized by the structs package is understood, as well as a pointer to any named structs type.

For example, if you have a function

char nth_char(string, n)
    char *string;
    int n;
        return string[n];

You might use it from Prolog as follows:

:- foreign_type cstring = array(integer_8).

foreign(nth_char, c, nth_char(+pointer(cstring), +integer, [-integer_8])).

This allows the predicate nth_char/3 to be called from Prolog to determine the nth character of a C string.

Note that all existing foreign interface type specifications are unaffected, in particular address/[0,1] continue to pass addresses to and from Prolog as plain integers.

If you use the foreign resource linker, splfr, on a Prolog file that uses the structs package, you must pass it the --structs option. This will make splfr understand foreign type specifications and translate them into C declarations in the generated header file (see The Foreign Resource Linker).

Send feedback on this subject.