XS, FFI and Embedding

51.1 FFI::Platypus (Call C Without Writing C Glue)

use v5.36;
use FFI::Platypus 2.00;
my $ffi = FFI::Platypus->new(api => 2);
$ffi->lib(undef);                                  # search libc and the current process
$ffi->attach(puts   => ['string'] => 'int');
$ffi->attach(strlen => ['string'] => 'size_t');
puts("Hello from C's puts");
say strlen('Perl');                                # 4

$ffi->lib('./libmymath.so');
$ffi->attach(add => ['int', 'int'] => 'int');
say add(2, 3);

51.2 XS (Perl's Native Extension Interface)

XS uses xsubpp and typemaps to convert between Perl SVs and C types. Learn about SV*, AV*, HV*, reference counts (SvREFCNT_inc), and mortals (sv_2mortal).

Inline::C embeds C directly in Perl source for prototyping:

Other bridges: Inline::Python, Inline::Java, FFI::Platypus::Lang::Rust, Alien::* modules (bundle native libraries).

h2xs -A -n My::Fast            # scaffold an XS module (or use Module::Starter / Dist::Zilla)
/* Fast.xs */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

MODULE = My::Fast    PACKAGE = My::Fast

int
add(a, b)
    int a
    int b
  CODE:
    RETVAL = a + b;
  OUTPUT:
    RETVAL
use Inline C => <<'END_C';
int square(int x) { return x * x; }
END_C
print square(7), "\n";   # 49

51.3 Embedding Perl

Embed the interpreter in C/C++ apps (perlembed: perl_alloc, perl_parse, perl_run, eval_pv). Examples: Vim, WeeChat, irssi, PostgreSQL (PL/Perl), Apache (mod_perl).