3.4 An example of dynamic pointer allocation

When a pointer is created, using make-pointer, or due to the allocation of a foreign object, memory is put aside to store the details of the pointer. However, if a pointer is only needed within the scope of a particular section of code, there is an FLI macro, with-coerced-pointer, which can be used to create a temporary pointer which is automatically deallocated at the end of the code. The next example illustrates the use of this macro.

To start with, we need an object to use the temporary pointer on. The following code allocates ten consecutive integers, and sets their initial values.

(setf array-obj
      (fli:allocate-foreign-object :type :int
                  :nelems 10
                  '(0 1 2 3 4 5 6 7 8 9)))

When the ten integers are created, allocate-foreign-object returns a pointer to the first one. The next piece of code uses with-coerced-pointer to create a copy of the pointer, which is then used to print out the contents of the ten integers. At the end of the printing, the temporary pointer is automatically deallocated.

(fli:with-coerced-pointer (temp) array-obj
  (dotimes (x 10)
    (print (fli:dereference temp))
    (fli:incf-pointer temp)))

The above example also illustrates the use of the incf-pointer, which increases the address stored in a pointer by the size of the object pointed to. There is a similar function called decf-pointer, which decreases the address held by a pointer in a similar fashion.

LispWorks Foreign Language Interface User Guide and Reference Manual - 13 Sep 2005