Package: cffi

Function foreign-alloc

Lambda List

foreign-alloc (type &key initial-element initial-contents count null-terminated-p)

Arguments

type -- A foreign type.
initial-element -- A Lisp object.
initial-contents -- A sequence.
count -- An integer. Defaults to 1 or the length of initial-contents if supplied.
null-terminated-p -- A boolean, false by default.
pointer -- A foreign pointer to the newly allocated memory.

Details

The foreign-alloc function allocates enough memory to hold count objects of type type and returns a pointer. This memory must be explicitly freed using foreign-free once it is no longer needed.

If initial-element is supplied, it is used to initialize the count objects the newly allocated memory holds.

If an initial-contents sequence is supplied, it must have a length less than or equal to count and each of its elements will be used to initialize the contents of the newly allocated memory.

If count is omitted and initial-contents is specified, it will default to (length initial-contents).

initial-element and initial-contents are mutually exclusive.

When null-terminated-p is true, (1+ (max count (length initial-contents))) elements are allocated and the last one is set to NULL. Note that in this case type must be a pointer type (i.e. a type that canonicalizes to :pointer), otherwise an error is signaled.

Examples

  CFFI> (foreign-alloc :char)
  => #<A Mac Pointer #x102D80>     ; A pointer to 1 byte of memory.

CFFI> (foreign-alloc :char :count 20) => #<A Mac Pointer #x1024A0> ; A pointer to 20 bytes of memory.

CFFI> (foreign-alloc :int :initial-element 12) => #<A Mac Pointer #x1028B0> CFFI> (mem-ref * :int) => 12

CFFI> (foreign-alloc :int :initial-contents '(1 2 3)) => #<A Mac Pointer #x102950> CFFI> (loop for i from 0 below 3 collect (mem-aref * :int i)) => (1 2 3)

CFFI> (foreign-alloc :int :initial-contents #(1 2 3)) => #<A Mac Pointer #x102960> CFFI> (loop for i from 0 below 3 collect (mem-aref * :int i)) => (1 2 3)

;;; Allocate a char** pointer that points to newly allocated memory ;;; by the :string type translator for the string "foo". CFFI> (foreign-alloc :string :initial-element "foo") => #<A Mac Pointer #x102C40>

;;; Allocate a null-terminated array of strings. ;;; (Note: FOREIGN-STRING-TO-LISP returns NIL when passed a null pointer) CFFI> (foreign-alloc :string :initial-contents '("foo" "bar" "baz") :null-terminated-p t) => #<A Mac Pointer #x102D20> CFFI> (loop for i from 0 below 4 collect (mem-aref * :string i)) => ("foo" "bar" "baz" NIL) CFFI> (progn (dotimes (i 3) (foreign-free (mem-aref ** :pointer i))) (foreign-free **)) => nil
 

See also