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

Kitchen Reminders