You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 mapmy$mem = alloc_owned( sizeof( Matrix3x3() ) );
my$m = cast( $mem, Matrix3x3() );
# 3. Use nested indexing# Affix calculates the stride (3 * sizeof(Float)) automaticallyformy$i (0 .. 2) {
formy$j (0 .. 2) {
$m->[$i][$j] = ($i == $j) ? 1.0 : 0.0;
}
}
# 4. Verifysay'Center value [1][1]: ' . $m->[1][1]; # 1.0say'Top-right [0][2]: ' . $m->[0][2]; # 0.0
How It Works
Recursive Pointers
When you access $m->[1], Affix returns a new, temporary Affix::Pointer that represents a "Live View" of the second row. Because this row is itself an Array, 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 another 1 * sizeof(Float).
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
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.
How It Works
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.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).All reactions