Foreign Dynamic Allocation - SBCL 1.0.31 User Manual
Description: SBCL 1.0.31 User Manual

Previous: Coercing Foreign Values, Up: Operations On Foreign Values

#### 8.3.3 Foreign Dynamic Allocation

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.

— Macro: sb-alien:make-alien type size

> The `sb-alien:make-alien` macro 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 `deref` to change the result to an array before you can use `deref` to 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) => 10

>   If 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.

— Function: sb-alien:free-alien foreign-value

> The `sb-alien:free-alien` function frees the storage for foreign-value, which must have been allocated with Lisp `make-alien` or C `malloc`.

> See also the `sb-alien:with-alien` macro, which allocates foreign values on the stack.