-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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