6.2.8 Foreign Code Examples

Given: a Prolog file ex.pl and a C file ex.c shown below.

                                      
ex.pl
foreign_resource(ex, [c1, c2, c11, c21, c3, c4, c5, c6]). foreign(c1, c, c1(+integer, [-integer])). foreign(c2, c, c2(-integer)). foreign(c11, c, c11(+atom, [-atom])). foreign(c21, c, c21(+atom, -atom)). foreign(c3, c, c3(+float, [-float])). foreign(c4, c, c4(-float)). foreign(c5, c, c5(+string,[-string])). foreign(c6, c, c6(-string)). :- load_foreign_resource(ex).
                                       
ex.c
#include <sicstus/sicstus.h> /* ex_glue.h is generated by splfr from the foreign/[2,3] facts. Always include the glue header in your foreign resource code. */ #include "ex_glue.h" /* c1(+integer, [-integer]) */ SP_integer c1(a) SP_integer a; { return(a+9); } /* c2(-integer) */ void c2(a) SP_integer *a; { *a = 99; } /* c11(+atom, [-atom]) */ SP_atom c11(a) SP_atom a; { return(a); } /* c21(+atom, -atom) */ void c21(a,b) SP_atom a; SP_atom *b; { *b = a; } /* c3(+float, [-float]) */ double c3(a) double a; { return(a+9.0); } /* c4(-float) */ void c4(a) double *a; { *a = 9.9; } /* c5(string, [-string]) */ char const * c5(a) char const * a; { return(a); } /* c6(-string) */ void c6(a) char const * *a; { *a = "99"; }

Dialog at the command level:

     % splfr ex.pl ex.c
     % sicstus -l ex
     % compiling /home/matsc/sicstus4/ex.pl...
     %  loading foreign resource /home/matsc/sicstus4/ex.so in module user
     % compiled /home/matsc/sicstus4/ex.pl in module user, 0 msec 3184 bytes
     SICStus 4.2.3 ...
     Licensed to SICS
     | ?- c1(1,X1), c2(X2), c11(foo,X11), c21(foo,X21), c3(1.5,X3), c4(X4), c5(foo,X5), c6(X6).
     X1 = 10,
     X2 = 99,
     X3 = 10.5,
     X4 = 9.9,
     X5 = foo,
     X6 = '99',
     X11 = foo,
     X21 = foo ? <RET>
     yes

Send feedback on this subject.