Affix
view release on metacpan or search on metacpan
lib/Affix.pod view on Meta::CPAN
=head3 C<realloc( $ptr, $new_size )>
Resizes the memory area pointed to by C<$ptr> to C<$new_size> bytes. The original pin is updated automatically
in-place.
$ptr = realloc( $ptr, 2048 );
=head3 C<strdup( $string )>
Allocates managed memory and copies the Perl string (along with a C<NULL> terminator) into it. Returns a managed
C<Pointer[Char]> pin.
my $str_ptr = strdup("Hello C!");
=head3 C<free( $ptr )>
Manually releases memory.
B<Warning:> Only use this on memory that you exclusively own (e.g., allocated via C<malloc>). Do not call C<free> on
unmanaged pointers returned by C libraries unless the library explicitly transfers ownership to you, or you will cause
a segmentation fault.
free($ptr);
=head3 C<own( $pin )>
Returns true if the given pin is an owned C<Affix::Memory> object (i.e., memory allocated via C<malloc> or C<calloc>
that Perl manages directly). Returns false for unmanaged pins or raw scalars.
if (own($ptr)) {
say "Perl owns this memory; it will be freed automatically.";
}
=head3 C<is_pin( $var )>
Returns true if the variable is currently bound to C memory via C<pin>, C<cast>, or pointer dereferencing. Returns
false for ordinary Perl scalars.
my $x = 42;
say is_pin($x); # false
pin $x, libc(), 'errno', Int;
say is_pin($x); # true
=head2 Lifecycle & Ownership
=head3 C<attach_destructor( $pin, $func_ptr, [$lib] )>
Attaches a custom C function to be called when the Pin is destroyed. This is incredibly useful for C libraries that
require specific cleanup routines (e.g., C<SDL_DestroyWindow>, C<sqlite3_free>).
# Find the address of the library's custom free function
my $free_func = find_symbol($my_lib, 'custom_free');
# When $ptr goes out of scope, Affix will call custom_free($ptr)
attach_destructor($ptr, $free_func, $my_lib);
=head3 C<readonly( $pin, [$bool] )>
Gets or sets the "const" status of a memory pin. If set to true, any attempt to write to that memory from Perl will
throw an exception.
readonly($point, 1);
$point->{x} = 20; # CRASH: Modification of a read-only C value
=head2 Type Casting
=head3 C<cast( $ptr, $type )>
The most powerful tool in the memory kit. It "overlays" a C type definition onto a raw memory address.
my $mem = malloc(16);
my $point = cast($mem, Struct[ x => Int, y => Int ]);
$point->{x} = 10;
=head1 POINTER UTILITIES
Navigate and inspect raw pointers with helper functions for address arithmetic, null checks, and more.
=head3 C<address( $ptr )>
Returns the virtual memory address of the pointer as a Perl Unsigned Integer (C<UInt64>). Useful for passing addresses
to other FFI libraries or debugging.
say sprintf("Address: 0x%X", address($ptr));
=head3 C<ptr_add( $ptr, $offset_bytes )>
Returns a new B<unmanaged alias Pin> offset by C<$offset_bytes>.
my $int_arr = calloc(10, Int);
my $next_elem = ptr_add($int_arr, sizeof(Int));
I<Note: If C<$ptr> is an Array type, C<ptr_add> correctly decays the returned pin into a Pointer to the element type.>
=head3 C<ptr_diff( $ptr1, $ptr2 )>
Returns the byte difference (C<$ptr1 - $ptr2>) between two pointers as an integer.
=head3 C<is_null( $ptr )>
Returns true if the address is C<NULL> (C<0x0>).
=head3 C<strnlen( $ptr, $max )>
Safe string length calculation. Checks the pointer for a C<NULL> terminator, scanning at most C<$max> bytes.
=head3 C<raw( $ptr, $length_in_bytes )>
Returns a Perl string containing the raw, un-decoded binary data extracted directly from the memory address. This is
the programmatic, binary equivalent of C<dump()>.
=head3 C<snapshot( $pin )>
Deeply reads the C memory backing a Pin and returns a pure, non-magical native Perl data structure (ArrayRef, HashRef,
or Scalar). Because it does not apply VTable magic to the returned values, reading elements from the returned structure
in a bulk operation (like summing a 10,000 element array) is exceptionally fast.
=head1 Raw Memory Operations
Classic C memory functions (memcpy, memset, etc.) available directly from Perl for high-performance byte manipulation.
These functions accept either Pins or raw integer addresses.
=over
=item * C<memcpy( $dest, $src, $bytes )>: Copies exactly C<$bytes> from C<$src> to C<$dest>.
=item * C<memmove( $dest, $src, $bytes )>: Copies C<$bytes> from C<$src> to C<$dest>. Safe to use if the memory regions overlap.
=item * C<memset( $ptr, $byte_val, $bytes )>: Fills the first C<$bytes> of the memory block with the value C<$byte_val>.
=item * C<memcmp( $ptr1, $ptr2, $bytes )>: Compares the first C<$bytes> of two memory blocks. Returns an integer less than, equal to, or greater than zero.
=item * C<memchr( $ptr, $byte_val, $bytes )>: Locates the first occurrence of C<$byte_val> within the first C<$bytes> of the memory block. Returns a new Pin pointing to the match, or C<undef>.
=back
=head1 C<Const> & Readonly Memory
Enforce C's const contract at the Perl level. Affix intercepts writes to read-only memory and throws a fatal exception:
C<Modification of a read-only C value attempted>.
=head2 Declarative Const: C<Const[ $type ]>
You can wrap any type in C<Const[ ... ]> within a signature.
# C: void process(const char* name, const int* values);
affix $lib, 'process', [ Const[String], Pointer[ Const[Int] ] ] => Void;
=head2 Imperative Const: C<readonly( $pin, [$bool] )>
The C<readonly()> function allows you to inspect or toggle the const status of a Pin or Aggregate at runtime. This acts
as an I<FFI Escape Hatch> (similar to C<const_cast> in C++).
my $point = cast($addr, Struct[ x => Int, y => Int ]);
readonly($point, 1); # Lock the entire struct
$point->{x} = 10; # FATAL ERROR
=head2 Recursive Protection
When an aggregate (Struct or Array) is marked as read-only, Affix automatically propagates that protection to all of
its members.
my $rect = cast($addr, Const[Struct[top => Struct[ x => Int, y => Int ], bottom => Struct[ x => Int, y => Int ] ]]);
# Even though 'x' wasn't explicitly marked Const, it inherited protection
# from the parent struct.
$rect->{top}{x} = 5; # FATAL ERROR
=head2 Casting with Const
When using C<cast( ... )>, you can prepend a C<+> to the type signature to create an immutable view of a raw memory
address.
my $view = cast($raw_addr, Const[MyStruct]);
# $view is now a read-only HashRef mapping to C memory.
=head1 Zero-copy Aggregates
Structs, unions, and arrays map directly to C memoryâno deep copies required. When C returns a pointer to an
aggregate, Affix wraps it in a magical Perl reference that reads and writes C memory in real time.
=head3 Native Array Indexing
C Arrays are traversed using standard Perl array syntax.
typedef Task => Struct[ id => Int, name => String ];
affix $lib, 'get_tasks', [] => Pointer[ Array[ Task(), 10 ] ];
my $tasks = get_tasks();
$tasks->[5]{id} = 404; # Writes directly to C memory!
=head3 Deep Null Safety
Traversing a `NULL` pointer in C causes a segfault. Affix wraps C memory in Perl safety rails. If you try to traverse a
`NULL` pointer inside a struct, Affix intercepts it and throws a standard Perl exception (C<Can't use an undefined
value as a HASH reference>).
=head1 LIBRARIES & SYMBOLS
Load and inspect dynamic libraries across platforms. Affix's smart discovery engine handles varying extensions,
prefixes, and search paths automatically.
=head2 Library Discovery
When you provide a bare library name (e.g., C<'z'>, C<'ssl'>, C<'user32'>) rather than an absolute path, Affix
automatically formats the name for the current platform (e.g., C<libz.so>, C<libz.dylib>, C<z.dll>) and searches the
following locations in order:
=over
=item 1. B<Standard System Paths:> Windows C<System32>/C<SysWOW64>; Unix C</usr/local/lib>, C</usr/lib>, C</lib>, C</usr/lib/system>.
=item 2. B<Environment Variables:> Paths defined in C<LD_LIBRARY_PATH>, C<DYLD_LIBRARY_PATH>, C<DYLD_FALLBACK_LIBRARY_PATH>, or C<PATH>.
=item 3. B<Local Paths:> The current working directory (C<.>) and its C<lib/> subdirectory.
=back
=head2 Functions
=head3 C<load_library( $path_or_name )>
Locates and loads a dynamic library into memory, returning an opaque C<Affix::Lib> handle.
my $lib = load_library('sqlite3');
B<Lifecycle:> Library handles are thread-safe and internally reference-counted. The underlying OS library is only
closed (e.g., via C<dlclose> or C<FreeLibrary>) when all Affix wrappers and pins relying on it are destroyed.
I<Note:> When using C<affix()> or C<wrap()>, you can safely pass the string name directly (e.g., C<affix('sqlite3',
...)>) and Affix will call C<load_library> for you internally. If you pass C<undef> instead of a library name, Affix
will search the currently running executable process.
=head3 C<locate_lib( $name, [$version] )>
Searches for a library using Affix's discovery engine and returns its absolute file path as a string. It B<does not>
load the library into memory. This is useful if you need to pass the library path to another tool or check for its
existence.
# Find libssl.so.1.1 or libssl.1.1.dylib
my $path = locate_lib('ssl', '1.1');
say "Found SSL at: $path" if $path;
=head3 C<find_symbol( $lib_handle, $symbol_name )>
Looks up an exported symbol (function or global variable) inside an already-loaded C<Affix::Lib> handle. Returns an
unmanaged C<Affix::Pointer> (Pin) of type C<Pointer[Void]> pointing to the memory address of the symbol.
my $lib = load_library('m');
# Get the raw memory address of the 'pow' function
my $pow_ptr = find_symbol($lib, 'pow');
if ($pow_ptr) {
say sprintf("pow() is located at: 0x%X", address($pow_ptr));
( run in 2.117 seconds using v1.01-cache-2.11-cpan-b16cb0d3907 )