We end by a very simple example of using the foreign language interface of XSB. The programs above and below are programs simple_foreign.{H,c} in the examples directory.
#include <math.h> #include <stdio.h> #include <string.h> #include <alloca.h> /*----- Make sure your C compiler finds the following header file. ----- ----- The best way to do this is to include the directory XSB/emu ----- ----- on compiler's command line with the -I (/I in Windows) option -----*/ #include "cinterf.h" /*----------------------------------------------------------------------*/ int minus_one(void) { int i = ptoc_int(1); ctop_int(2, i-1); return TRUE; } /*----------------------------------------------------------------------*/ int my_sqrt(void) { int i = ptoc_int(1); ctop_float(2, (float) pow((double)i, 0.5)); return TRUE; } /*----------------------------------------------------------------------*/ int change_char(void) { char *str_in; int pos; int c; char *str_out; str_in = (char *) ptoc_string(1); str_out = (char *) alloca(strlen(str_in)+1); strcpy(str_out, str_in); pos = ptoc_int(2); c = ptoc_int(3); if (c < 0 || c > 255) /* not a character */ return FALSE; /* this predicate will fail on the Prolog side */ str_out[pos-1] = c; /* Now that we have constructed a new symbol, we must ensure that it appears in the symbol table. This can be done using function string_find() that searches the symbol table for the symbol, and if the symbol does not appear there, it inserts it. If we are sure that the symbol already appeared in the symbol table there is no need to use string_find(). */ ctop_string(4, (char *) string_find(str_out,1)); /* 1 = INSERT */ return TRUE; } /*----------------------------------------------------------------------*/
Here is a sample session illustrating the use of these files.
XSB Version 2.0 (Gouden Carolus) of June 26, 1999 [i686-pc-linux-gnu; mode: optimal; engine: slg-wam; scheduling: batched] | ?- [simple_foreign]. [Compiling C file ./simple_foreign.c using gcc] [Compiling Foreign Module ./simple_foreign] [simple_foreign compiled, cpu time used: 0.0099993 seconds] [simple_foreign loaded] yes | ?- change_char('Kostis', 2, 119, TempStr), % 119 is w change_char(TempStr, 5, 104, GrkName). % 104 is h TempStr = Kwstis GrkName = Kwsths; no | ?- minus_one(43, X). X = 42; no | ?- minus_one(43, 42). % No output unification is allowed Wrong arg in ctop_int 2a2 (Reg = 2) yes | ?- my_sqrt(4,X). X = 2 yes | ?- my_sqrt(23,X). X = 4.7958; no
There are additional sample programs in the examples directory that exhibit most of the features of the foreign language interface.