Previous: Coercing Foreign Values, Up: Operations On Foreign Values
Lisp code can call the C standard library functions malloc and
free to dynamically allocate and deallocate foreign
variables. The Lisp code shares the same allocator with foreign C
code, so it's OK for foreign code to call free on the result of
Lisp sb-alien:make-alien, or for Lisp code to call
sb-alien:free-alien on foreign objects allocated by C
code.
The
sb-alien:make-alienmacro returns a dynamically allocated foreign value of the specified type (which is not evaluated.) The allocated memory is not initialized, and may contain arbitrary junk. If supplied, size is an expression to evaluate to compute the size of the allocated object. There are two major cases:
- When type is a foreign array type, an array of that type is allocated and a pointer to it is returned. Note that you must use
derefto change the result to an array before you can usederefto read or write elements:(cl:in-package "CL-USER") ; which USEs package "SB-ALIEN" (defvar *foo* (make-alien (array char 10))) (type-of *foo*) => (alien (* (array (signed 8) 10))) (setf (deref (deref foo) 0) 10) => 10If supplied, size is used as the first dimension for the array.
- When type is any other foreign type, then an object for that type is allocated, and a pointer to it is returned. So
(make-alien int)returns a(* int). If size is specified, then a block of that many objects is allocated, with the result pointing to the first one.