NumPy
NAME
Inline::Python3::NumPy - Zero-copy NumPy array integration
SYNOPSIS
use Inline::Python3;
use Inline::Python3::NumPy;
my $py = Inline::Python3.new;
# Create NumPy array in Python
$py.run(q:to/PYTHON/);
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6]], dtype='float64')
PYTHON
# Get zero-copy access
my $arr = $py.numpy-array($py.run('data', :eval).ptr);
# Direct element access (no copying)
say $arr[0, 0]; # 1
$arr[1, 2] = 42; # Modifies Python array
# Get raw data pointer for C interop
my $raw-data = $arr.as-num64-array();
# Slice operations
my $slice = $arr.slice(0..1, 1..2);
DESCRIPTION
This module provides zero-copy access to NumPy arrays from Raku. It allows:
Direct memory access without copying data
Element access using Raku syntax
Type-safe views of array data
Slice operations
Metadata access (shape, strides, dtype)
Performance
Zero-copy operations are orders of magnitude faster than converting arrays: - Element access: ~100ns (vs ~1ms for conversion) - No memory allocation for access - Direct pointer arithmetic
Limitations
- Only contiguous arrays support direct indexing - Limited dtype support (common numeric types) - Multi-dimensional indexing requires manual calculation
METHODS
new(:$python, :$ptr)
Create a NumPyArray wrapper from a Python object pointer.
AT-POS(*@indices)
Get element at given indices (zero-copy).
ASSIGN-POS(*@indices, $value)
Set element at given indices (zero-copy).
as-TYPE-array()
Get typed view of raw data (int8, int16, int32, int64, num32, num64).
to-array()
Convert to Raku array (copies data).