Standard FFI examples usually show 1D arrays (a list of numbers). But real-world data like images, matrices, and physics grids are often N-dimensional. In C, these are defined as nested arrays: int grid[10][10].
With Affix's recursive magic, you can index these just like a Perl multidimensional array.
The Recipe
We will define a 3x3 identity matrix in C and read/write to it using nested Perl indices.
use v5.40;
use Affix qw[:all];
# 1. Define a 2D Array type (A 3-element array of 3-element arrays)
typedef Matrix3x3 => Array[ Array[ Float, 3 ], 3 ];
# 2. Allocate and map
my $mem = alloc_owned( sizeof( Matrix3x3() ) );
my $m = cast( $mem, Matrix3x3() );
# 3. Use nested indexing
# Affix calculates the stride (3 * sizeof(Float)) automatically
for my $i (0 .. 2) {
for my $j (0 .. 2) {
$m->[$i][$j] = ($i == $j) ? 1.0 : 0.0;
}
}
# 4. Verify
say 'Center value [1][1]: ' . $m->[1][1]; # 1.0
say 'Top-right [0][2]: ' . $m->[0][2]; # 0.0
How It Works
- Recursive Pointers
When you access
$m->[1], Affix returns a new, temporaryAffix::Pointerthat represents a "Live View" of the second row. Because this row is itself anArray, the second index[1]triggers another VTable lookup on that sub-segment of memory. - Stride Calculation
Affix knows that to get to row 1, it must skip exactly
3 * sizeof(Float)bytes. To get to column 1 within that row, it skips another1 * sizeof(Float).
Comments