Perl handles memory for you. C does not. When you start allocating raw memory buffers in Affix, you are stepping into the C world. This recipe demonstrates how to manually allocate, manipulate, and free memory using the standard C lifecycle.
The Recipe
use v5.40;
use Affix qw[:all];
# 1. Allocation
# We allocate 15 bytes.
# malloc returns a Pointer[Void] (a pin).
my $void_ptr = malloc( 15 );
# 2. String Duplication
# strdup allocates new memory containing a copy of the string.
my $ptr_string = strdup("hello there!!\n");
# 3. Memory Copy
# We copy 15 bytes (text + null terminator) from one pointer to another.
# memcpy works on raw pointers, so passing $void_ptr is fine.
memcpy( $void_ptr, $ptr_string, 15 );
# 4. Read (The Cast)
# Dereferencing $void_ptr ($$void_ptr) would just return the memory address
# as an integer, because Affix doesn't know what's inside.
# We must CAST it to a specific type to read it.
my $str_view = cast( $void_ptr, String );
print $str_view;
How It Works
-
1.
mallocreturns an opaque pointermy $void_ptr = malloc( 15 );Just like in C,
mallocreturns avoid*. It represents a chunk of raw memory with no type information attached. -
2.
castadds meaningmy $str_view = cast( $void_ptr, String );Casting creates a new pin that points to the same memory address but has different type metadata.
$void_ptr -> Address 0x1234, Type: *void $str_view -> Address 0x1234, Type: *charWhen you dereference
$$str_view, Affix sees the type isStringand reads the memory until the null terminator. -
3. Pointer arithmetic via
memcpymemcpy( $void_ptr, $ptr_string, 15 );This is a raw memory operation. It doesn't care about types; it just moves bytes. This is extremely fast, but dangerous if you get the length wrong. Always ensure your destination buffer is large enough to hold the source data.
Kitchen Reminders
-
The
void *DefaultIf you see a large integer when you expected data (e.g.
2029945...), you are dereferencing aPointer[Void]. Usecast($ptr, Type)to tell Affix how to read the data. -
Buffer Overflows
Perl aims to protect you from buffer overflows. Affix does not.
memcpywill happily write past the end of your allocation and corrupt your program's memory. Measure twice, cut once. Yes, that's a carpentry reference in a cookbook. It's fine.