Affix
view release on metacpan or search on metacpan
lib/Affix.pod view on Meta::CPAN
my $val = 50;
is deref_and_add( \$val ), 60; # Passes address of $val as int*
# C: void modify_int_ptr(int* p, int new_val);
affix $lib, 'modify_int_ptr', [ Pointer[Int], Int ] => Void;
modify_int_ptr( \$val, 999 );
say $val; # 1000; C function wrote through the pointer
=head4 Array Indexing
Pointers to arrays support direct element access via array subscript syntax. Reads and writes go directly to C memory:
affix $lib, 'get_array_ptr', [] => Pointer[ Array[ Int, 4 ] ];
my $arr = get_array_ptr();
say $arr->[0]; # Read first element from C memory
$arr->[2] = 99; # Write third element in C memory
To take a deep copy (snapshot), dereference into an anonymous array ref:
my $snapshot = [@$arr];
$snapshot->[0] = 100; # Modifying snapshot does NOT affect C memory
=head4 Void Pointers
If C<$type> is C<Void>, the pointer is "terminal." Dereferencing it will return C<undef>. In this case, use C<cast()>
or C<address()> to work with the raw memory address.
=head3 Specialized Pointers
=over
=item * B<C<File>> / B<C<PerlIO>>: Maps Perl filehandles (Globs or IO objects) to C<FILE*> or C<PerlIO*>. B<Must> be wrapped in a pointer: C<Pointer[File]>.
=item * B<C<SockAddr>>: Specialized marshalling for packed socket strings (e.g., from C<Socket::pack_sockaddr_in>) to C<struct sockaddr*>.
=item * B<C<SV>>: Direct, low-level access to Perl's internal Interpreter Object (C<SV*>). B<Must> be wrapped in a pointer: C<Pointer[SV]>.
=back
=head2 Aggregate Types
=head3 C<Struct[ @members ]>
A C struct, mapped to a Perl C<HashRef>.
# C: typedef struct { int x; int y; } Point;
typedef Point => Struct[ x => Int, y => Int ];
=head3 C<Union[ @members ]>
A C union, mapped to a Perl C<HashRef> with exactly one key.
# C: union { int key_code; float pressure; };
typedef Event => Union[ key_code => Int, pressure => Float ];
=head3 C<Packed[ $aggregate ]> / C<Packed[ $align, $aggregate ]>
Forces specific byte alignment on a Struct or Union (e.g., C<#pragma pack(1)>).
# Without explicit alignment (default):
Packed[ Struct[ flag => Char, data => Int ] ];
# With explicit alignment (e.g., #pragma pack(push, 1)):
Packed( 1, Struct[ flag => Char, data => Int ] );
=head3 C<Array[ $type, $count ]>
A fixed-size C array. Maps to a Perl C<ArrayRef>.
# C: double Vector3[3];
typedef Vector3 => Array[ Double, 3 ];
=head3 Bitfields
Specify bit widths using the pipe (C<|>) operator within Structs/Unions. Affix handles all masking and shifting.
# C: typedef struct { uint32_t a : 1; uint32_t b : 3; } Config;
typedef Config => Struct[ a => UInt32 | 1, b => UInt32 | 3 ];
=head2 Live Views (Zero-Copy Aggregates)
In Affix, memory structures are live by design. When C returns a pointer to an aggregate (Struct, Union, or Array), or
when you use C<cast()> to overlay a type onto a memory address, Affix does not copy the data.
Instead, it returns a magical Perl reference (blessed into C<Affix::Pointer>) mapped directly to the C memory via Perl
VTables. This means zero-copy performance without the overhead of C<tie>.
Modifying keys or elements in these structures updates C memory immediately, and reading them reads directly from the C
heap.
# Example: Live view of a struct
my $live = cast( $ptr, Struct[ x => Int, y => Int ] );
$live->{x} = 42; # Updates C memory
=head3 Unified Access
Magical C<Affix::Pointer> references allow direct field access (C<< $p->{field} >>) without explicit casting.
affix $lib, 'get_ptr', [] => Pointer[Point];
my $p = get_ptr();
say $p->{x}; # Unified access! Reads directly from C memory.
$p->{y} = 50; # Writes directly to C memory.
=head2 Callbacks & Functions
=over
=item * B<C<< Callback[ [$params] => $ret ] >>>: Defines the signature of a C function pointer. Allows you to pass Perl subroutines into C functions.
# C: void set_handler( void (*cb)(int) );
affix $lib, 'set_handler', [ Callback[ [Int] => Void ] ] => Void;
=item * B<C<ThisCall( $cb_or_sig )>>: Helper for C++-style C<__thiscall> callbacks. Prepends a C<Pointer[Void]> (the C<this> pointer) to the signature.
=back
=head2 Variadic Functions (VarArgs)
Affix supports C functions that take a variable number of arguments (e.g., C<printf>, C<ioctl>). When defining a
signature, use the C<VarArgs> token at the end of the argument list.
=head3 Basic Usage
# C: int printf(const char* format, ...);
lib/Affix.pod view on Meta::CPAN
=item * B<Linux/macOS (System V AMD64 ABI):> Arguments are passed in C<rdi, rsi, rdx, rcx, r8, r9>, with the rest on the stack.
=item * B<Windows (Microsoft x64):> Arguments are passed in C<rcx, rdx, r8, r9>, with "shadow space" reserved on the stack.
=back
=head2 Go
Go libraries can be loaded if they are compiled with C<-buildmode=c-shared>. Note that Go slices and strings contain
internal metadata (length/capacity) and do not map directly to C arrays or C<char*>. Use the C<C> package inside Go
(C<import "C">) and C<*C.char> to bridge the boundary.
=head1 ERROR HANDLING & DEBUGGING
Diagnose FFI issues with built-in error reporting, memory inspection, and hex dumps. Bridging two entirely different
runtimes can lead to spectacular crashes if types or memory boundaries are mismatched.
=head2 Error Handling
=head3 C<errno()>
Accesses the system error code from the most recent FFI or standard library call (reads C<errno> on Unix and
C<GetLastError> on Windows).
This function returns a B<dualvar>. It behaves as an integer in numeric context, and magically resolves to the
human-readable system error message (via C<strerror> or C<FormatMessage>) in string context.
# Suppose a C file-open function fails
my $fd = c_open("/does/not/exist");
if (!$fd) {
my $err = errno();
# String context
say "Failed to open: $err"; # "No such file or directory"
# Numeric context
if (int($err) == 2) {
say "Code 2 specifically triggered.";
}
}
B<Note:> You must call C<errno()> immediately after the C function invokes, as subsequent Perl operations (like
printing to STDOUT) might overwrite the system's error register.
=head2 Memory Inspection
=head3 C<dump( $pin, $length_in_bytes )>
Prints a formatted hex dump of the memory pointed to by a Pin directly to C<STDOUT>. This is an invaluable tool for
verifying that C structs or buffers contain the data you expect.
my $ptr = strdup("Affix Debugging");
dump($ptr, 16);
# Output:
# Dumping 16 bytes from 0x55E9A8A5 at script.pl line 42
# 000 41 66 66 69 78 20 44 65 62 75 67 67 69 6e 67 00 | Affix Debugging.
=head3 C<sv_dump( $scalar )>
Dumps Perl's internal interpreter structure (SV) for a given scalar to C<STDOUT>. This exposes the raw flags, reference
counts, and memory layout of the Perl variable itself.
my $val = 42;
sv_dump($val);
# Exposes IV flags, memory addresses of the SV head, etc.
=head2 Advanced Debugging
=head3 C<set_destruct_level( $level )>
Sets the internal C<PL_perl_destruct_level> variable.
When testing XS/FFI code for memory leaks using tools like Valgrind or AddressSanitizer, you often want Perl to
meticulously clean up all global memory during its destruction phase (otherwise the leak checker will be flooded with
false-positive "leaks" that are actually just memory Perl intentionally leaves to the OS to reclaim).
# Call this at the start of your script when running under Valgrind
set_destruct_level(2);
=head1 COMPANION MODULES
Auto-generate bindings from C/C++ headers and compile polyglot source with two companion modules:
=over
=item * L<B<Affix::Wrap>|Affix::Wrap>: Parses C/C++ headers using the Clang AST to automatically generate Affix bindings for entire libraries.
=item * L<B<Affix::Build>|Affix::Build>: A polyglot builder that compiles inline C, C++, Rust, Zig, Go, and 15+ other languages into dynamic libraries you can bind instantly.
=back
=head1 THREAD SAFETY & CONCURRENCY
Understand the threading model: what's safe to do from callbacks, and what must happen in the main thread before
spawning any threads. Affix bridges Perl (a single-threaded interpreter, generally) with libraries that may be
multi-threaded. This creates potential hazards that you must manage.
=head2 1. Initialization Phase vs. Execution Phase
Functions that modify Affix's global state are B<not thread-safe>. You must perform all definitions in the main thread
before starting any background threads or loops in the library.
Unsafe operations that you should never call from Callbacks or in a threaded context:
=over
=item * C<affix( ... )> - Binding new functions.
=item * C<typedef( ... )> - Registering new types.
=back
=head2 2. Callbacks
When passing a Perl subroutine as a C<Callback>, avoid performing complex Perl operations like loading modules or
defining subs inside callbacks triggered on a foreign thread. Such callbacks should remain simple: process data, update
a shared variable, and return.
If the library executes the callback from a background thread (e.g., window managers, audio callbacks), Affix attempts
to attach a temporary Perl context to that thread. This should be sufficient but Perl is gonna be Perl.
=head1 RECIPES & EXAMPLES
Real-world patterns including linked lists and C++ vtable calls. See L<The Affix
Cookbook|https://github.com/sanko/Affix.pm/discussions/categories/recipes> for comprehensive guides to using Affix.
( run in 1.400 second using v1.01-cache-2.11-cpan-a49fcb8fa48 )