6.6.10.4 Vector Accessing from C

A vector can be read and modified from C with the functions scm_c_vector_ref and scm_c_vector_set_x. In addition to these functions, there are two other ways to access vectors from C that might be more efficient in certain situations: you can use the unsafe vector macros; or you can use the general framework for accessing all kinds of arrays (see Accessing Arrays from C), which is more verbose, but can deal efficiently with all kinds of vectors (and arrays). For arrays of rank 1 whose backing store is a vector, you can use the scm_vector_elements and scm_vector_writable_elements functions as shortcuts.

C Macro: size_t SCM_SIMPLE_VECTOR_LENGTH (SCM vec)

Evaluates to the length of the vector vec. No type checking is done.

C Macro: SCM SCM_SIMPLE_VECTOR_REF (SCM vec, size_t idx)

Evaluates to the element at position idx in the vector vec. No type or range checking is done.

C Macro: void SCM_SIMPLE_VECTOR_SET (SCM vec, size_t idx, SCM val)

Sets the element at position idx in the vector vec to val. No type or range checking is done.

C Function: const SCM * scm_vector_elements (SCM array, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)

Acquire a handle for array and return a read-only pointer to its elements. array must be either a vector, or an array of rank 1 whose backing store is a vector; otherwise an error is signaled. The handle must eventually be released with scm_array_handle_release.

The variables pointed to by lenp and incp are filled with the number of elements of the array and the increment (number of elements) between successive elements, respectively. Successive elements of array need not be contiguous in their underlying “root vector” returned here; hence the increment is not necessarily equal to 1 and may well be negative too (see Shared Arrays).

The following example shows the typical way to use this function. It creates a list of all elements of array (in reverse order).

scm_t_array_handle handle;
size_t i, len;
ssize_t inc;
const SCM *elt;
SCM list;

elt = scm_vector_elements (array, &handle, &len, &inc);
list = SCM_EOL;
for (i = 0; i < len; i++, elt += inc)
  list = scm_cons (*elt, list);
scm_array_handle_release (&handle);
C Function: SCM * scm_vector_writable_elements (SCM array, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)

Like scm_vector_elements but the pointer can be used to modify the array.

The following example shows the typical way to use this function. It fills an array with #t.

scm_t_array_handle handle;
size_t i, len;
ssize_t inc;
SCM *elt;

elt = scm_vector_writable_elements (array, &handle, &len, &inc);
for (i = 0; i < len; i++, elt += inc)
  *elt = SCM_BOOL_T;
scm_array_handle_release (&handle);