All Manuals > Foreign Language Interface User Guide and Reference Manual > 8 Type Reference

:reference FLI Type Descriptor

Summary

Passes a foreign object of a specified type by reference, and automatically dereferences the object.

Package

keyword

Syntax

:reference type &key allow-null lisp-to-foreign-p foreign-to-lisp-p

Arguments
type
The type of the object to pass by reference.
allow-null
A boolean.
lisp-to-foreign-p
If non-nil, allow conversion from Lisp to the foreign language. The default value is t.
foreign-to-lisp-p
If non-nil, allow conversion from the foreign language to Lisp. The default value is t.
Description

The FLI type :reference is essentially the same as a :pointer type, except that :reference is automatically dereferenced when it is processed.

The :reference type is useful as a foreign function argument. When a function is called with an argument of the type (:reference type), an object of type is dynamically allocated across the scope of the foreign function, and is automatically de-allocated once the foreign function terminates. The value of the argument is not copied into the temporary instance of the object if lisp-to-foreign-p is nil, and similarly, the return value is not copied back into a Lisp object if foreign-to-lisp-p is nil.

If allow-null is non-nil and the input argument is nil then a null pointer is passed instead of a reference to an object containing nil. allow-null defaults to nil.

Notes

If the argument is of an aggregate type and foreign-to-lisp-p is true, then a malloc'd copy is made which you should later free explicitly. It is usually better to use:pointer, make the temporary foreign object using with-dynamic-foreign-objects and then copy whatever slots you need into a normal Lisp object on return.

Examples

In the following example an :int is allocated, and a pointer to the integer is bound to the Lisp variable number. Then a pointer to number, called point1, is defined. The pointer point1 is set to point to number, itself a pointer, but to an :int.

(setq number (fli:allocate-foreign-object :type :int))
(setf (fli:dereference number) 42)
(setq point1 (fli:allocate-foreign-object 
              :type '(:pointer :int)))
(setf (fli:dereference point1) number)

If point1 is dereferenced, it returns a pointer to an :int. To get at the value stored in the integer, we need to dereference twice:

(fli:dereference (fli:dereference point1))

However, if we dereference point1 as a :reference, we only have to dereference it once to get the value:

(fli:dereference point1 :type '(:reference :int))
See also

:reference-pass
:reference-return


Foreign Language Interface User Guide and Reference Manual - 01 Dec 2021 19:34:59