Next: , Previous: , Up: Calling C from Prolog   [Contents][Index]


6.2.2 Conversion Declarations

Conversion declaration predicates:

foreign_resource(+ResourceName,+Functions)   hook

Specifies that a set of foreign functions, to be called from Prolog, are to be found in the resource named by ResourceName. Functions is a list of functions exported by the resource. Only functions that are to be called from Prolog and optionally one init function and one deinit function should be listed. The init and deinit functions are specified as init(Function) and deinit(Function) respectively (see Init and Deinit Functions). This predicate should be defined entirely in terms of facts (unit clauses) and will be called in the relevant module, i.e. not necessarily in the user module. For example:

foreign_resource('terminal', [scroll,pos_cursor,ask]).

specifies that functions scroll(), pos_cursor() and ask() are to be found in the resource terminal. See mpg-ref-foreign_resource.

foreign(+CFunctionName, +Predicate)   hook
foreign(+CFunctionName, +Language, +Predicate)   hook

Specify the Prolog interface to a C function. Language is at present constrained to the atom c, so there is no advantage in using foreign/3 over foreign/2. CFunctionName is the name of a C function. Predicate specifies the name of the Prolog predicate that will be used to call CFunction(). Predicate also specifies how the predicate arguments are to be translated to and from the corresponding C arguments. These predicates should be defined entirely in terms of facts (unit clauses) and will be called in the relevant module, i.e. not necessarily in the user module. For example:

foreign(pos_cursor, c, move_cursor(+integer, +integer)).

The above example says that the C function pos_cursor() has two integer value arguments and that we will use the predicate move_cursor/2 to call this function. A goal move_cursor(5, 23) would translate into the C call pos_cursor(5,23);.

The third argument of the predicate foreign/3 specifies how to translate between Prolog arguments and C arguments. A call to a foreign predicate will throw an Instantiation Error if an input arguments is uninstantiated, a Type Error if an input arguments has the wrong type, or a Domain Error if an input arguments is in the wrong domain. The call will fail upon return from the function if the output arguments do not unify with the actual arguments.

The available conversions are listed in the next subsection. See mpg-ref-foreign.



Send feedback on this subject.