Thursday, July 19, 2012

Calling Prolog from Foreign Languages

When you define Prolog clauses for global predicates  as being of foreign language, those predicates may be called from foreign languages. They will have parameter access and entry and exit code, including register preservation, as for the language specified.
Example:predicate called from .pro in C language
/* Program hello_p.pro */
global predicates
char prohello_msg(string) - (i) language c
hello_c - language c
clauses
prohello_msg(S,C) :-
write(S," (press any key)"), readchar(C).
goal
prohello_msg("Hello from  Prolog"),
hello_c.

The global predicate prohello_msg is now accessible from C and can be called just like any other C function:


/* Program hello_c.c */
char prohello_msg(char *);
void hello_c()
{
  while ( prohello_msg("Hello from C (press 'C')") != 'C' )
    ;
}
Obviously returned value can be assigned to variable if there is any.

Standard Predicates

 

Most of Visual Prolog's standard predicates can be called from C, but their public names and exact functionality are subject to change without notice. It's therefore strongly recommended that you write a small set of interface routines if you want to call Visual Prolog standard predicates from C. The following illustrates bindings to a number of Visual Prolog's DOS Textmode I/O predicates:

/* Program spred_p.pro */
project "spred"
global predicates
myfail language c as "_fail"
mymakewindow(integer,integer,integer,string,integer,integer,
integer,integer)
               - (i,i,i,i,i,i,i,i) language c as "_makewindow"
myshiftwindow(integer) - (i) language c as "_shiftwindow"
myremovewindow language c as "_removewindow"
write_integer(integer) - (i) language c as "_write_integer"
write_real(real) - (i) language c as "_write_real"
write_string(string) - (i) language c as "_write_string"
myreadchar(char) - (o) language c as "_readchar"
myreadline(string) - (o) language c as "_readline"
extprog language c
clauses
myfail:- fail.
mymakewindow(Wno, Wattr, Fattr, Text, Srow, Scol, Rows, Cols):-
makewindow(Wno, Wattr, Fattr, Text, Srow, Scol, Rows, Cols).
myshiftwindow(WNO):- shiftwindow(WNO).
myremovewindow:- removewindow.
write_integer(I):- write(I).
write_real(R):- write(R).
write_string(S):- write(S).
myreadchar(CH):- readchar(CH).
myreadline(S):- readln(S).
goal
extprog.

These may be accessed freely by C, as illustrated by extprog:

reference:VProlog documentation

1 comment: