Next Previous Up Top Contents Index

1 Introduction to the FLI

1.4 An example of dynamic memory allocation

In the previous example our defined interface functionget-cursor-position used the functionfli:allocate-foreign-object to allocate memory for an instance of aPOINT structure. This memory is now reserved, with a pointer to its location bound to the variablelocation. More detailed information on pointers is available in Chapter 3, "FLI Pointers". To free the memory associated with the foreign object requires the use of the functionfli:free-foreign-object.

(fli:free-foreign-object location)

There are other methods for dealing with the question of memory management. The following example defines a Lisp function that returns the x and y coordinates of the cursor without permanently tying up memory for structures that are only used once.

(defun current-cursor-position ()
  (fli:with-dynamic-foreign-objects ()
    (let ((lppoint (fli:allocate-dynamic-foreign-object 
                    :pointer-type 'lppoint)))
      (if (get-cursor-position lppoint)
        (values t (fli:foreign-slot-value lppoint 'x)
                  (fli:foreign-slot-value lppoint 'y))
        (values nil 0 0)))))

On callingcurrent-cursor-position the following happens:

1. The macrofli:with-dynamic-foreign-objects is called, which ensures that the lifetime of any allocated objects is within the scope of the code specified in its body.
2. The functionfli:allocate-dynamic-foreign-object is called to create an instance of the relevant data structure required to get the cursor position. Refer to it using thelppoint pointer.
3. The previously defined foreign functionget-cursor-position is called withlppoint.
4. Provided the call toGetCursorPos was successful the functionfli:foreign-slot-value is called twice, once to return the value in thex slot and again to return the value in they slot. If the call was unsuccessful then0 0 nil is returned.

LispWorks Foreign Language Interface - 12 Oct 1998

Next Previous Up Top Contents Index

Generated with Harlequin WebMaker