Foreign Interfaces
Also: embedding Prolog in C/C++ (PL_initialise, PL_call), C++ interface (SWI-cpp2.h), Rust bindings (swipl-rs).
43.1 C (SWI-Prolog foreign interface)
Also: embedding Prolog in C/C++ (PL_initialise, PL_call), C++ interface (SWI-cpp2.h), Rust bindings (swipl-rs).
// hello.c
#include <SWI-Prolog.h>
static foreign_t pl_add(term_t a, term_t b, term_t c) {
long x, y;
if (!PL_get_long(a, &x) || !PL_get_long(b, &y)) return FALSE;
return PL_unify_integer(c, x + y);
}
install_t install_hello(void) {
PL_register_foreign("c_add", 3, pl_add, 0);
}swipl-ld -shared -o hello hello.c?- use_foreign_library(hello), c_add(2, 3, X). % X = 543.2 Python — Janus (bidirectional, SWI 9.1+)
import janus_swi as janus
janus.consult("family.pl")
for d in janus.query("grandparent(tom, X)"):
print(d["X"])
print(janus.query_once("Y is X * 2", {"X": 21})["Y"]) # 42?- py_call(math:sqrt(16), R). % R = 4.0
?- py_call(numpy:array([1, 2, 3]), A), py_call(A:sum(), S).43.3 Java, JavaScript & others
JPL — Java ↔ SWI-Prolog bridge.
SWI-Prolog WASM — run SWI in the browser/Node; Tau Prolog (pure JS); Trealla WASM.
Scryer Prolog embeddable from Rust; ichiban/prolog for Go; tuProlog (Java/Kotlin)..NET: CSProlog, SWI via SwiPlCs.
43.4 Calling external programs
:- use_module(library(process)).
?- process_create(path(ls), ['-l'], [stdout(pipe(Out))]),
read_string(Out, _, S), close(Out).