Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chansey97/86b9d854336f34d371543e3519009162 to your computer and use it in GitHub Desktop.
Save chansey97/86b9d854336f34d371543e3519009162 to your computer and use it in GitHub Desktop.
Sample C foreign interface for SWI-Prolog called with my_function('6',N) loaded with :-use_foreign_library(foreign('test.so')). compile: swipl-ld -shared -o test test.c
#include <SWI-Prolog.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct context /* define a context structure */
{
int max;
} context;
foreign_t
my_function(term_t in, term_t out, control_t handle)
{ struct context * ctxt;
switch( PL_foreign_control(handle) )
{ case PL_FIRST_CALL:
ctxt = malloc(sizeof(struct context));
char *s_max;
if(PL_get_atom_chars(in, &s_max)) {
ctxt->max = atoi(s_max) - 1;
printf("PL_FIRST_CALL\n");
if(PL_unify_integer(out,ctxt->max)) {
PL_retry_address(ctxt);
}
else {
printf("failed to unify\n");
PL_fail;
}
}
else {
PL_fail;
}
case PL_REDO:
ctxt = PL_foreign_context_address(handle);
printf("PL_REDO\n");
if(ctxt->max>0) {
ctxt->max = ctxt->max -1;
PL_unify_integer(out,ctxt->max);
PL_retry_address(ctxt);
}
else {
printf("0, abording\n");
free(ctxt);
PL_fail;
}
case PL_PRUNED:
printf("PL_PRUNED\n");
ctxt = PL_foreign_context_address(handle);
free(ctxt);
PL_succeed;
default:
PL_fail;
}
}
install_t
install_test()
{ PL_register_foreign("my_function", 2, my_function, PL_FA_NONDETERMINISTIC);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment