For Programmers: Free Programming Magazines  


Home > Archive > Prolog > June 2007 > Re: Possible to register a foreign function dynamically?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: Possible to register a foreign function dynamically?
yuce

2007-06-01, 8:05 am

> If above is how Python programmers would like to see it, I guess it is
> fine. The divantage of moving further away from the C interface is
> that you cannot easily translate example code written in C to Python.


The PL_* functions of PySWIP are still available to the programmers,
so C sources will be easily transformed to Python; but I need to have
another layer that makes the task easier since we [Python programmers]
are a little lazy I guess :) For example, instead of the following to
retrieve the items of a list:

# t is of type term_t
head = PL_new_term_ref()
items = []
v = c_char_p()
while PL_get_list(t, head, t):
PL_get_chars(head, addressof(v), CVT_ALL|CVT_WRITE)
items.append(v.value)

I wrapped that into getList, so it becomes:

items = getList(t)

I think this is a great improvement for usability. Also I am trying to
follow the same naming convention, so PL_get_list becomes getList, or
PL_get_atom_chars becomes getAtomChars; so I guess someone used the C
API will be able to start programming with PySWIP immediately [or in a
very short time].

> P.s. Does this also allow easy embedding of Python in Prolog?


I haven't factored this yet, in fact I have no idea how it can be done
[apart from register_foreign]

> P.s. Make sure to avoid global variables to make the interface
> thread-safe. The only thing global is the initialisation
> of the Prolog system, as there can only be one of them.


I haven't tested this on a multi-threaded program yet but I don't have
any global variables so there shouldn't be any problems. I have a
singleton Prolog class which initializes and finalizes the system,
here's the code for initialization:

def __initialize(cls):
plargs = (c_char_p*3)()
plargs[0] = "./"
plargs[1] = "-q"
plargs[2] = "\x00"
PL_initialise(2, plargs)

swipl_fid = PL_open_foreign_frame()
swipl_load = PL_new_term_ref()
PL_chars_to_term("asserta(pyrun(GoalString,BindingList):-
(atom_chars(A,GoalString),"
" atom_to_term(A,Goal,BindingList),call(Go
al))).",
swipl_load)

PL_call(swipl_load, None)
PL_discard_foreign_frame(swipl_fid)
__initialize = classmethod(__initialize)

`pyrun` is used when querying SWI-Prolog [I haven't write this code
myself, and I will remove the Prolog code once I add the predicate/
term creation functions]

The finalization code just calls `PL_halt(0)`.

How it seems?

Thanks again :)

Yuce


Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com