If a C function is declared as taking a parameter with a pointer or an array type (for example,
float* or
int[3]), instances of the relevant specialized array can be passed in.
C type specifiers for array types are documented in
C type specifiers.
Here is an example; as is common with C functions, the array length is passed in separately, since C does not offer a runtime facility to determine the array length of a base pointer:
USING: alien.syntax specialized-arrays ;
SPECIALIZED-ARRAY: int
FUNCTION: void process_data ( int* data, int len )
int-array{ 10 20 30 } dup length process_data
Literal specialized arrays, as well as specialized arrays created with
<T-array> and
T >c-array are backed by a
byte-array in the Factor heap, and can move as a result of garbage collection. If this is unsuitable, the array can be allocated in unmanaged memory instead.
In the following example, it is presumed that the C library holds on to a pointer to the array's data after the
init_with_data() call returns; this is one situation where unmanaged memory has to be used instead. Note the use of destructors to ensure the memory is deallocated after the block ends:
USING: alien.syntax specialized-arrays ;
SPECIALIZED-ARRAY: float
FUNCTION: void init_with_data ( float* data, int len )
FUNCTION: float compute_result ( )
[
100 malloc-float-array &free
dup length init_with_data
compute_result
] with-destructors
Finally, sometimes a C library returns a pointer to an array in unmanaged memory, together with a length. In this case, a specialized array can be constructed to view this memory using
<direct-T-array>:
USING: alien.c-types alien.data classes.struct ;
STRUCT: device_info
{ id int }
{ name char* } ;
FUNCTION: void get_device_info ( int* length )
0 int <ref> [ get_device_info ] keep <direct-int-array> .
For a full discussion of Factor heap allocation versus unmanaged memory allocation, see
Byte arrays and the garbage collector.
Each specialized array has a
underlying slot holding a
byte-array with the raw data. Passing a specialized array as a parameter to a C function call will automatically extract the underlying data. To get at the underlying data directly, call the
>c-ptr word on a specialized array.