Alien-libssh
view release on metacpan or search on metacpan
misc/agent-context/.claude/skills/perl-xs/SKILL.md view on Meta::CPAN
---
name: perl-xs
description: "Use when writing or debugging XS â .xs files, typemaps, ppport.h, xsubpp or C compile errors, segfaults or leaks at the Perl/C boundary."
---
# XS â the Perl/C boundary
An `.xs` file is C with a preprocessor in front of it. `xsubpp` turns each XSUB
declaration into a C function reachable through Perl's calling convention; every
other line lands in the generated `.c` verbatim. So most of an XS file is plain C,
and the XS-specific part is three decisions:
1. **How does a C pointer live inside a Perl SV?** â `sv_magicext` with a per-type
`MGVTBL`. See [references/objects-and-memory.md](references/objects-and-memory.md)
2. **How does that SV convert at the boundary?** â a per-type `typemap` entry.
See [references/typemap.md](references/typemap.md)
3. **What does one XSUB look like inside?** â sections, `RETVAL`, the argument
stack. See [references/xsub-anatomy.md](references/xsub-anatomy.md)
Compiling, `ppport.h` and testing for leaks:
[references/build-and-test.md](references/build-and-test.md)
## The files
| File | Role |
|---|---|
| `Foo.xs` | all implementation; several `MODULE`/`PACKAGE` sections may share one file |
| `typemap` | one entry per type crossing the boundary â INPUT and OUTPUT |
| `ppport.h` | generated compatibility shims; regenerate it, never hand-edit |
| `lib/Foo.pm` | `XSLoader::load`, `$VERSION`, POD â no logic |
A package implemented entirely in XS still gets a `.pm` file: it carries `$VERSION`
and the POD, while the package itself comes into being when xsubpp emits its
`MODULE = ⦠PACKAGE = â¦` section. Each such `.pm` needs its own `our $VERSION`, and
they all move together on release.
The generated `Foo.c` is a build artifact. Keep it out of git.
## The preamble
```c
#define PERL_NO_GET_CONTEXT /* take the interpreter as an argument */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#define NEED_mg_findext /* one NEED_ per ppport.h shim actually used */
#include "ppport.h"
#include <foolib/foolib.h> /* the library being wrapped */
```
`PERL_NO_GET_CONTEXT` belongs in every XS file: without it each function that
touches the interpreter looks it up through thread-local storage. With it, the
interpreter travels as a parameter â which is why your own static helpers take
`pTHX_` and are called with `aTHX_`.
Each `NEED_foo` asks `ppport.h` to emit a static implementation of `foo` for Perls
that lack it, and must appear exactly once per compilation unit.
## MODULE, PACKAGE, PREFIX
```
MODULE = Foo PACKAGE = Foo
( run in 0.832 second using v1.01-cache-2.11-cpan-c32d3c3b8f1 )