Calling Arbitrary Prolog Goals from C

Any Prolog predicate can be made callable from foreign code, including system built-ins. An especially useful case of this generally useful ability is making the built-in call/1 callable. call/1 is declared callable like any other predicate, and is passed the Prolog term to be called. The term may have originated in Prolog, or may have been constructed in C using the supplied term manipulation functions (see fli-p2f-trm).

In this particular example, we pass a term from Prolog to C, then C calls call/1 with that term. This lets us concentrate on the calling rather than on the construction of the term to be called.

On the Prolog side of the interface, the following declaration is loaded:

     :- extern(call(+term)).

On the C side, the following function is defined, compiled and either loaded into Prolog using the dynamic foreign interface or statically linked with Prolog:

     #include <quintus/quintus.h>
     QP_term_ref t;
             QP_pred_ref call = QP_predicate("call", 1, "user");
             QP_query(call, t);

This done, any goal that can be called from Prolog can also be called from C by passing it to call_prolog/1.