When a pointer is created, using fli:make-pointer
, or due to the allocation of a foreign object, memory is put aside to store the details of the pointer. Thus the pointer has to be deallocated using fli:free-foreign-object
when it is no longer needed in order to avoid tying up memory unnecessarily. However, if a pointer is only needed within the scope of a particular section of code, there is an FLI macro, fli: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
:initial-contents
'(0 1 2 3 4 5 6 7 8 9)))
When the ten integers are created, fli:allocate-foreign-object
returns a pointer to the first one. The next piece of code uses fli: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 fli:incf-pointer
, which increases the address stored in a pointer by the size of the object pointed to. There is a similar function called fli:decf-pointer
, which decreases the address held by a pointer in a similar fashion.