/* * Project : Embedding SWI-Prolog in a C program. * * Author : Lens Stephane Ulg * Date : 10/2009 * * Sort a list. * */ #include #include #define MAX_STRING_SIZE 32 void pl_put_list_nstrings(term_t, int, char (*)[MAX_STRING_SIZE]); int main(int argc, char *argv[]) { int i, j, res; char list[10][MAX_STRING_SIZE]; char *sortedListWrited; /* Initialise Prolog */ if ( !PL_initialise(argc, argv) ) PL_halt(1); /* Get the 10 strings to sort */ printf("Sort 10 strings (Rem : Max %i chars for a string)\n\n", MAX_STRING_SIZE); for (i = 0; i < 10; i++) { printf("Next string to sort : "); if( !fgets(list[i], MAX_STRING_SIZE, stdin) ) PL_halt(1); for (j = 0; j < MAX_STRING_SIZE; j++) if (list[i][j] == '\n') { list[i][j] = '\0'; break; } } /* Define terms to use with Prolog */ term_t h0 = PL_new_term_refs(2); term_t h1 = h0 + 1; /* Transform the list of strings to Prolog term */ pl_put_list_nstrings(h0, 10, list); /* Call the predicate */ res = PL_call_predicate(NULL, PL_Q_NORMAL, PL_predicate("msort", 2, "user"), h0); if (res != 1) { fprintf(stderr, "Error with the predicate !\n"); PL_halt(1); return(1); } /* Print the sorted list */ printf("\nSorted List :\n\n"); PL_get_chars(h1, &sortedListWrited, CVT_WRITE); printf("%s\n\n",sortedListWrited); /* Stop Prolog */ PL_halt(0); /* Stop Prolog */ return 0; } /* Put a list of n strings to prolog atom */ void pl_put_list_nstrings(term_t l, int n, char (*words)[MAX_STRING_SIZE]) { fid_t fid = PL_open_foreign_frame(); term_t a = PL_new_term_ref(); PL_put_nil(l); while(n--) { PL_put_atom_chars(a, words[n]); PL_cons_list(l, a, l); } PL_close_foreign_frame(fid); }