Welcome to the Affix Cookbook! This guide is a living collection of recipes, techniques, and architectural patterns for mastering Foreign Function Interfaces (FFI) in Perl using Affix. Whether you are seeking peak performance, accessing system libraries, or building polyglot applications, you will find practical examples and deep dives to help you on your journey.
Part I: Getting Started
The first part of this journey focuses on getting your feet wet with Foreign Function Interfaces (FFI) in Perl using Affix. You'll learn how to instantly bridge the gap between Perl and C by spinning up a compiler right inside your script. We will walk through the fundamentals of interacting with native code, from binding standard libraries on Linux to speaking Windows APIs. By the end of this section, you'll be comfortable writing, compiling, and calling C functions on the fly without worrying about makefiles, build steps, or intricate linking setups.
- Welcome to the Affix Cookbook
- The Instant C Library
- Speaking Windows
- System Libraries on Linux
- The Standard Library
Part II: Data Types and Memory
The core of any FFI library is understanding how data is represented in memory across language boundaries. In this part, we dive into the fundamental types—from numbers to strings, pointers to arrays—and explore how they translate between Perl and C. We will cover the pitfalls of binary data (like the infamous null byte trap), managing static state, handling opaque pointers, and manipulating n-dimensional tensors. You will also discover how to emulate 128-bit integers natively in Perl, giving you the tools to safely and effectively shuffle bytes across the barrier.
- Binary Data and the Null Byte Trap
- Strings and Static State
- Opaque Pointers
- Arrays vs Pointers
- Mutable Arrays
- N-Dimensional Arrays & Tensors
- Dealing with Flexible Array Members (FAM)
- Emulating Native 128-bit Integers in Perl
Part III: Structs and Enums
Moving beyond simple types, this section tackles complex data structures. You'll learn how to define and handle transparent structs, map them seamlessly to Perl objects, and work with smart enums to make your API resilient and expressive. We'll also cover advanced memory layouts, such as bitfield packing for hardware registers, and runtime introspection to dynamically discover the size and layout of structures. With features like Affix's unique "Pointers with Personality," you will start treating C structures like native Perl constructs.
- Transparent Structs
- Smart Enums
- Hardware Registers and Bitfield Packing [planned]
- The sizeof the Universe (Runtime Introspection)
- Pointers with Personality: How Affix Rethinks FFI Memory
Part IV: Functions, Callbacks, and Trampolines
FFI isn't just a one-way street. In Part IV, we focus on bi-directional communication through functions and callbacks. You will learn how to handle variadic functions (like printf), define Perl subroutines that C code can execute as callbacks, and manage context and closures across languages. We will also explore advanced techniques like direct marshalling trampolines and writing custom marshallers, enabling high-performance callbacks and deeply integrated cross-language workflows.
- Variadic Functions
- Callbacks
- Callbacks, Context, and Closures
- Direct Marshalling Trampolines
- Perl Callbacks in C Structs (vtables)
- Writing a Custom Marshaller [planned]
Part V: Polyglot FFI
Why stop at C? Affix is a true polyglot. This part opens the floodgates to integrating multiple programming languages within a single Perl script. We will guide you through binding to C++, Rust, Fortran, Assembly, Zig, Go, and D, demonstrating how to seamlessly blend them together into a single kitchen-sink library. Whether you're seeking the scientific speed of Fortran, the absolute power of Assembly, or the memory safety of Rust, you'll learn how to orchestrate them all from Perl.
- The Instant C++ Library
- The Instant Assembly, C, D, Fortran, Go, Rust, Zig Library
- The Kitchen Sink Polyglot Library
- Oxidizing Perl: Binding to Rust
- Scientific Speed with Fortran and Perl
- Absolute Power with Assembly and Perl
- Battle of the Bindings
Part VI: C++ Integration
C++ is notoriously difficult to bind due to name mangling and complex object models, but Affix makes it manageable. In this section, we tackle the beast of C++ integration. You will discover techniques for wrapping C++ classes with C shims, hacking vtables for direct access, and handling thiscall calling conventions. These chapters provide the specialized knowledge required to bridge Perl with one of the most powerful and widely-used systems languages.
- Wrapping C++ Classes with C Shims
- Wrapping C++ Classes by Hacking Vtables
- C++ VTables and ThisCall Integration
Part VII: Tooling, Packaging, and Ecosystem
A cookbook wouldn't be complete without discussing how to package and share your creations. Part VII delves into the broader ecosystem, teaching you how to build modules for CPAN using Module::Build and integrate with the Alien:: ecosystem. We will explore automated introspection and API generation using Affix::Wrap, creating module factories, and unlocking the vast C/C++ package ecosystem with Alien::Xrepo and Zig CC, making your FFI modules robust, portable, and easy to distribute.
- Automated Introspection with Affix Wrap
- Unlocking the C/C++ Ecosystem with Affix Wrap and Alien::Xrepo
- Using Affix with Alien:: Modules [planned]
- Packaging an Affix Build Module for CPAN
- Instant Runtime Wrappers
- An Affix Module Factory
- Just-in-Time API Generation
- Cross-Compiling with Zig CC
Part VIII: Performance, SIMD, and Memory Optimization
Performance is often the primary reason for writing native extensions. This part is dedicated to squeezing every last drop of speed out of your code. We cover manual and automatic resource management (RAII), memory arenas, and strategies for eliminating the "FFI tax" to achieve zero-copy data transfers. We also dive into SIMD (Single Instruction, Multiple Data) matrix benchmarks and vectors for heavy number crunching, proving peak performance with real-world profiling.
- Manual Memory Management
- Automatic Resource Management (RAII)
- Performance Optimization with Memory Arenas
- Eliminating the "FFI Tax": Zero-Copy C Memory in Perl with Affix
- Profiling Proves Peak Performance
- SIMD and Matrix Benchmarks
- SIMD Vectors for Number Crunching
- The Zero-Dependency Image Processor
Part IX: Advanced OS Features and Concurrency
Modern applications demand concurrency and access to low-level operating system features. In this section, we explore memory-mapped files (mmap) for inter-process communication, low-level networking, and real-time audio streaming. You'll also learn how to navigate the complexities of multithreaded FFI, cooperative fibers, asynchronous event loops, and techniques for taming the Global Interpreter Lock (GIL) when pushing Perl to its concurrent limits.
- Advanced File Handling
- Memory Mapping (mmap) and IPC [planned]
- Low-Level Networking with SockAddr [planned]
- Real-time Audio Streaming with Buffer [planned]
- FFI in a Multithreaded System
- Cooperative Fibers in FFI
- Taming the Global Interpreter Lock [planned]
- Asynchronous FFI and Event Loops [planned]
Part X: Architecture and Debugging
The final section equips you with the tools and architectural patterns to build robust, production-ready native integrations. We discuss comprehensive error handling, troubleshooting, and debugging memory leaks with tools like Valgrind and GDB. You will also learn advanced design patterns, such as the "Universal Object" pattern, culminating in a conclusion that ties together the master chef's secrets for a successful Affix project.
- Error Handling
- Troubleshooting and Debugging
- Debugging with Valgrind and GDB [planned]
- The "Universal Object" Pattern
Conclusion: The Master Chef's Secret [planned]
Comments