10.22 The Structs Package—library(structs)

The structs package allows Prolog to hold pointers to C data structures, and to access and store into fields in those data structures. Currently, the only representation for a pointer supported by SICStus Prolog is an integer, so it isn't possible to guarantee that Prolog can't confuse a pointer with an ordinary Prolog term. What this package does is to represent such a pointer as a term with the type of the structure or array as its functor and the integer that is the address of the actual data as its only argument. We will refer such terms as foreign terms.

The package consists of two modules, str_decl and structs. The str_decl module is used at compile time to translate the structs-related constructs. Any file that defines or accesses structs should include the command:

     :- load_files(library(str_decl),
                   [when(compile_time), if(changed)]).

The structs module provides runtime support for structs. A file that accesses structs should include the command:

     :- use_module(library(structs)).

You will probably include both in most files that define and access structs.

Important caveats:

You should not count on future versions of the structs package to continue to represent foreign terms as compound Prolog terms. In particular, you should never explicitly take apart a foreign term using unification or functor/3 and arg/3. You may use the predicate foreign_type/2 to find the type of a foreign term, and cast/3 (casting a foreign term to address) to get the address part of a foreign term. You may also use cast/3 to cast an address back to a foreign term. You should use null_foreign_term/2 to check if a foreign term is null, or to create a null foreign term of some type.

It should never be necessary to explicitly take apart foreign terms.


Send feedback on this subject.