Every operating system comes with a "C standard library" or, simply, libc. It contains the fundamental building blocks of C programming: memory allocation, file I/O, string manipulation, system calls, and much more.
Affix provides a shortcut to access this library without you needing to know its exact filename (which varies wildly between Linux, macOS, and Windows).
The Recipe
We will bind the standard C function puts which takes a string, prints it to stdout, and appends a newline character.
use v5.40;
use Affix;
# 1. Bind
# libc is a helper function exported by Affix.
# It returns the handle to the system's standard library.
affix libc, 'puts' => [String] => Int;
# 2. Call
# Note: puts() automatically adds a newline "\n"
puts('Hello World');
# 3. Check Result
# puts returns a non-negative integer on success, or EOF (-1) on error.
my $ret = puts('Affix makes FFI easy.');
say 'Successfully wrote to stdout.' if $ret >= 0;
How It Works
-
1. The
libcHelperFinding the standard library is platform-dependent:
- Linux:
libc.so.6(usually) - macOS:
libSystem.B.dylib - Windows:
msvcrt.dll(orucrtbase.dll)
The
libcfunction (exported by Affix) handles this detection logic for you, returning the correct handle for your operating system. - Linux:
-
2. The
putsFunctionThe C signature for
putsis:int puts(const char *s);We map this to:
[String] => IntWhen you call
puts('Hello'), Affix takes your Perl string, ensures it is null-terminated, and passes the pointer to C. The C library writes the bytes to the file descriptor for STDOUT.
Kitchen Reminders
-
Output Buffering
Perl and C use their own IO buffers. If you mix
print "...",say "...", andputs(...)in the same script, the output might appear out of order depending on when the buffers are flushed. Setting$| = 1;in Perl usually helps, but doesn't strictly control the C buffer. -
Implicit Newlines
Unlike Perl's
print,putsalways adds a newline. If you want to print without a newline using C, you would need to bindprintf.