PERLXSTUT(1perl)

πŸ“¦
version 5.44.0 Β· 2 versions
, in arch rolling

πŸ’– perlxstut β€” Tutorial for writing XSUBs πŸ’–

okay bestie, welcome to the manual page PERLXSTUT(1perl), also known as perlxstut β€” it's the tutorial for writing XSUBs, and yes we are going to have the best time. ✨


πŸ“– DESCRIPTION

So this tutorial is gonna walk you through, step by step, the whole thing of creating a Perl extension. It's lowkey assumed that you already have access to perlguts, perlclib, perlapi, and perlxs β€” like those are your prerequisites bestie, go read them. 🫢

It starts off super simple and then gets more and more complex, and every new example adds some new feature to the pile. Some concepts might not be fully explained until later on in the tutorial, and that's on purpose β€” it's so the reader gets eased into building extensions slowly instead of getting absolutely jumpscared. 😭

Also heads up: this tutorial was written from a Unix point of view. Where the author knows things are different on other platforms (like Win32, for example), they said they'll list them. And if you find something that got missed? Please let them know. πŸ™ˆ


πŸŽ€ SPECIAL NOTES πŸŽ€

πŸ› οΈ make

This tutorial assumes that the make program Perl is configured to use is literally called "make". But the way that isn't always true β€” in the examples coming up, instead of running "make", you might have to sub in whatever make program Perl has actually been configured to use. Run perl -V:make and it will tell you what it is. periodt. πŸ’…

⏳ Version caveat

Okay so when you're writing a Perl extension for general consumption, you should expect that it's gonna get used with versions of Perl different from whatever version is sitting on your machine. Since you're reading this document, the version of Perl on your machine is probably 5.005 or later β€” but bestie, your users might have much more ancient versions. πŸ’€

To understand what kinds of incompatibilities you might run into β€” and in the rare case that the Perl on your machine is older than this document β€” go look at the section on "Troubleshooting these Examples" for more info.

If your extension uses features of Perl that aren't available on older releases, your users would really appreciate an early meaningful warning. You'd probably put that info into the README file, but ngl, nowadays installation of extensions may be performed automatically, guided by the CPAN.pm module or other tools.

In MakeMaker-based installations, Makefile.PL gives you the earliest opportunity to do version checks. You can put something like this in Makefile.PL for that purpose:

eval { require 5.007 }
    or die <<EOD;
############
### This module uses frobnication framework which is not available
### before version 5.007 of Perl.  Upgrade your Perl before
### installing Kara::Mba.
############
EOD

πŸ”— Dynamic Loading versus Static Loading

So there's this common belief that if a system can't dynamically load a library, you just can't build XSUBs at all. That is incorrect. You can build them β€” you just have to link the XSUBs subroutines with the rest of Perl, creating a new executable. It's giving very much Perl 4 energy, honestly.

This tutorial still works on a system like that! The XSUB build mechanism will check the system and build a dynamically-loadable library if it can, or else it builds a static library and then, optionally, a new statically-linked executable with that static library linked in. πŸ’ͺ

Now β€” if you wanna build a statically-linked executable on a system that can dynamically load libraries, here's the move: in all the following examples, everywhere the command "make" with no arguments gets executed, run the command "make perl" instead. πŸ‘‘

And if you generated one of those statically-linked executables on purpose, then instead of saying "make test", you should say "make test_static". On systems that can't build dynamically-loadable libraries at all? Simply saying "make test" is sufficient. slay.

🧡 Threads and PERL_NO_GET_CONTEXT

For threaded builds, perl needs the context pointer for the current thread. Without PERL_NO_GET_CONTEXT, perl will call a function to retrieve the context. For improved performance, include:

#define PERL_NO_GET_CONTEXT

as shown below. For more details, see perlguts. ✨


πŸ¦‹ TUTORIAL πŸ¦‹

Now let's go on with the show! 🎬

🌸 EXAMPLE 1

Our first extension is gonna be very simple. When we call the routine in the extension, it prints out a well-known message and returns. iconic behavior, honestly.

Run "h2xs -A -n Mytest". This creates a directory named Mytest β€” possibly under ext/ if that directory exists in the current working directory. Several files get created under the Mytest dir, including MANIFEST, Makefile.PL, lib/Mytest.pm, Mytest.xs, t/Mytest.t, and Changes.

The MANIFEST file contains the names of all the files just created in the Mytest directory.

The file Makefile.PL should look something like this:

use ExtUtils::MakeMaker;

# See lib/ExtUtils/MakeMaker.pm for details of how to influence
# the contents of the Makefile that is written.
WriteMakefile(
    NAME         => 'Mytest',
    VERSION_FROM => 'lib/Mytest.pm', # finds $VERSION
    LIBS         => [''],        # e.g., '-lm'
    DEFINE       => '',          # e.g., '-DHAVE_SOMETHING'
    INC          => '-I',        # e.g., '-I. -I/usr/include/other'
);

The file Mytest.pm should start with something like this:

package Mytest;

use 5.008008;
use strict;
use warnings;

require Exporter;

our @ISA = qw(Exporter);
our %EXPORT_TAGS = ( 'all' => [ qw(

) ] );

our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );

our @EXPORT = qw(

);

our $VERSION = '0.01';

require XSLoader;
XSLoader::load('Mytest', $VERSION);

# Preloaded methods go here.

1;
__END__
# Below is the stub of documentation for your module. You better
# edit it!

The rest of the .pm file contains sample code for providing documentation for the extension.

Finally, the Mytest.xs file should look something like this:

#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

#include "ppport.h"

MODULE = Mytest             PACKAGE = Mytest

Let's edit the .xs file by adding this to the end of the file:

void
hello()
    CODE:
        printf("Hello, world!\n");

It is okay for the lines starting at the CODE: line to not be indented. However, for readability purposes, it's suggested that you indent CODE: one level and the lines following it one more level. πŸŽ€

Now we'll run "perl Makefile.PL". This creates a real Makefile, which make needs. Its output looks something like:

% perl Makefile.PL
Checking if your kit is complete...
Looks good
Writing Makefile for Mytest
%

Now, running make will produce output that looks something like this (some long lines have been shortened for clarity and some extraneous lines have been deleted):

 % make
cp lib/Mytest.pm blib/lib/Mytest.pm
perl xsubpp  -typemap typemap  Mytest.xs > Mytest.xsc && \
mv Mytest.xsc Mytest.c
Please specify prototyping behavior for Mytest.xs (see perlxs manual)
cc -c     Mytest.c
Running Mkbootstrap for Mytest ()
chmod 644 Mytest.bs
rm -f blib/arch/auto/Mytest/Mytest.so
cc -shared -L/usr/local/lib Mytest.o -o blib/arch/auto/Mytest/Mytest.so

chmod 755 blib/arch/auto/Mytest/Mytest.so
cp Mytest.bs blib/arch/auto/Mytest/Mytest.bs
chmod 644 blib/arch/auto/Mytest/Mytest.bs
Manifying blib/man3/Mytest.3pm
%

You can safely ignore the line about "prototyping behavior" β€” it's explained in "The PROTOTYPES: Keyword" in perlxs. no cap. πŸ™ˆ

Perl has its own special way of easily writing test scripts, but for this example only, we'll create our own test script. Create a file called hello that looks like this:

use ExtUtils::testlib;

use Mytest;

Mytest::hello();

Now we run the script and we should see the following output:

% perl hello
Hello, world!
%

🌈 EXAMPLE 2

Now let's add to our extension a subroutine that takes a single numeric argument as input and returns 1 if the number is even or 0 if the number is odd. math queen behavior. πŸ’…

Add the following to the end of Mytest.xs:

int
is_even(input)
        int input
    CODE:
        RETVAL = (input % 2 == 0);
    OUTPUT:
        RETVAL

There does not need to be whitespace at the start of the "int input" line, but it's useful for improving readability. Placing a semi-colon at the end of that line is also optional. Any amount and kind of whitespace may be placed between the "int" and "input".

Now re-run make to rebuild our new shared library. πŸ”₯

In order to test that our extension works, we now need to look at the file Mytest.t. This file is set up to imitate the same kind of testing structure that Perl itself has. Within the test script, you perform a number of tests to confirm the behavior of the extension, printing "ok" when the test is correct, "not ok" when it isn't.

use Test::More tests => 4;
BEGIN { use_ok('Mytest') };

#########################

# Insert your test code below, the Test::More module is use()ed here
# so read its man page ( perldoc Test::More ) for help writing this
# test script.

is( Mytest::is_even(0), 1 );
is( Mytest::is_even(1), 0 );
is( Mytest::is_even(2), 1 );

We will be calling the test script through the command "make test". You should see output that looks something like this:

 %make test
PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e"
"test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/Mytest....ok
All tests successful.
Files=1, Tests=4, 0 wallclock secs ( 0.03 cusr + 0.00 csys = 0.03 CPU)
%

πŸ‘‘ What has gone on?

The program h2xs is the starting point for creating extensions. In later examples we'll see how we can use h2xs to read header files and generate templates to connect to C routines. ✨

h2xs creates a number of files in the extension directory. The file Makefile.PL is a perl script which will generate a true Makefile to build the extension. We'll take a closer look at it later.

The .pm and .xs files contain the meat of the extension. The .xs file holds the C routines that make up the extension. The .pm file contains routines that tell Perl how to load your extension.

Generating the Makefile and running "make" created a directory called blib (which stands for "build library") in the current working directory. This directory will contain the shared library that we will build. Once we have tested it, we can install it into its final location. πŸŽ€

Invoking the test script via make test did something very important. It invoked perl with all those -I arguments so that it could find the various files that are part of the extension. It is very important that while you are still testing extensions that you use make test. If you try to run the test script all by itself, you will get a fatal error. Another reason it is important to use make test to run your test script is that if you are testing an upgrade to an already-existing version, using make test ensures that you will test your new extension, not the already-existing version.

Like, protector energy fr. make test is the friend who makes sure you're actually testing your new code and not some dusty old version lurking in your filesystem. Do not skip it. 😭

When Perl sees a use extension;, it searches for a file with the same name as the use'd extension that has a .pm suffix. If that file cannot be found, Perl dies with a fatal error. The default search path is contained in the @INC array.

In our case, Mytest.pm tells perl that it will need the Exporter and Dynamic Loader extensions. It then sets the @ISA and @EXPORT arrays and the $VERSION scalar; finally it tells perl to bootstrap the module. Perl will call its dynamic loader routine (if there is one) and load the shared library.

The two arrays @ISA and @EXPORT are very important. The @ISA array contains a list of other packages in which to search for methods (or subroutines) that do not exist in the current package. This is usually only important for object-oriented extensions (which we will talk about much later), and so usually doesn't need to be modified.

The @EXPORT array tells Perl which of the extension's variables and subroutines should be placed into the calling package's namespace. Because you don't know if the user has already used your variable and subroutine names, it's vitally important to carefully select what to export. Do not export method or variable names by default without a good reason. πŸ™ˆ

As a general rule, if the module is trying to be object-oriented then don't export anything. If it's just a collection of functions and variables, then you can export them via another array, called @EXPORT_OK. This array does not automatically place its subroutine and variable names into the namespace unless the user specifically requests that this be done.

See perlmod for more information.

The $VERSION variable is used to ensure that the .pm file and the shared library are "in sync" with each other. Any time you make changes to the .pm or .xs files, you should increment the value of this variable.

Writing good test scripts ✨

The importance of writing good test scripts cannot be over-emphasized. You should closely follow the ok/not ok style that Perl itself uses, so that it is very easy and unambiguous to determine the outcome of each test case. When you find and fix a bug, make sure you add a test case for it. πŸŽ€

By running make test, you ensure that your Mytest.t script runs and uses the correct version of your extension. If you have many test cases, save your test files in the t directory and use the suffix .t. When you run make test, all of these test files will be executed. πŸ¦‹

EXAMPLE 3 πŸ‘‘

Our third extension will take one argument as its input, round off that value, and set the argument to the rounded value.

Add the following to the end of Mytest.xs:

void
round(arg)
        double  arg
    CODE:
        if (arg > 0.0) {
                arg = floor(arg + 0.5);
        } else if (arg < 0.0) {
                arg = ceil(arg - 0.5);
        } else {
                arg = 0.0;
        }
    OUTPUT:
        arg

Edit the Makefile.PL file so that the corresponding line looks like this:

LIBS      => ['-lm'],   # e.g., '-lm'

Generate the Makefile and run make. Change the test number in Mytest.t to 9 and add the following tests:

my $i;

$i = -1.5;
Mytest::round($i);
is( $i, -2.0, 'Rounding -1.5 to -2.0' );

$i = -1.1;
Mytest::round($i);
is( $i, -1.0, 'Rounding -1.1 to -1.0' );

$i = 0.0;
Mytest::round($i);
is( $i, 0.0, 'Rounding 0.0 to 0.0' );

$i = 0.5;
Mytest::round($i);
is( $i, 1.0, 'Rounding 0.5 to 1.0' );

$i = 1.2;
Mytest::round($i);
is( $i, 1.0, 'Rounding 1.2 to 1.0' );

Running make test should now print out that all nine tests are okay. πŸŽ‰

Notice that in these new test cases, the argument passed to round was a scalar variable. You might be wondering if you can round a constant or literal. To see what happens, temporarily add the following line to Mytest.t:

Mytest::round(3);

Run make test and notice that Perl dies with a fatal error. Perl won't let you change the value of constants! πŸ’€

What's new here? 🧚

  • We've made some changes to Makefile.PL. In this case, we've specified an extra library to be linked into the extension's shared library, the math library libm in this case. We'll talk later about how to write XSUBs that can call every routine in a library.
  • The value of the function is not being passed back as the function's return value, but by changing the value of the variable that was passed into the function. You might have guessed that when you saw that the return value of round is of type void.

Input and Output Parameters 🌸

You specify the parameters that will be passed into the XSUB on the line(s) after you declare the function's return value and name. Each input parameter line starts with optional whitespace, and may have an optional terminating semicolon.

The list of output parameters occurs at the very end of the function, just after the OUTPUT: directive. The use of RETVAL tells Perl that you wish to send this value back as the return value of the XSUB function. In Example 3, we wanted the "return value" placed in the original variable which we passed in, so we listed it (and not RETVAL) in the OUTPUT: section.

The XSUBPP Program πŸ’…

The xsubpp program takes the XS code in the .xs file and translates it into C code, placing it in a file whose suffix is .c. The C code created makes heavy use of the C functions within Perl.

The TYPEMAP file 🌈

The xsubpp program uses rules to convert from Perl's data types (scalar, array, etc.) to C's data types (int, char, etc.). These rules are stored in the typemap file ($PERLLIB/ExtUtils/typemap). There's a brief discussion below, but all the nitty-gritty details can be found in perlxstypemap. If you have a new-enough version of perl (5.16 and up) or an upgraded XS compiler (ExtUtils::ParseXS 3.13_01 or better), then you can inline typemaps in your XS instead of writing separate files. Either way, this typemap thing is split into three parts:

The first section maps various C data types to a name, which corresponds somewhat with the various Perl types. The second section contains C code which xsubpp uses to handle input parameters. The third section contains C code which xsubpp uses to handle output parameters.

Let's take a look at a portion of the .c file created for our extension. The file name is Mytest.c:

XS(XS_Mytest_round)
{
    dXSARGS;
    if (items != 1)
        Perl_croak(aTHX_ "Usage: Mytest::round(arg)");
    PERL_UNUSED_VAR(cv); /* -W */
    {
        double  arg = (double)SvNV(ST(0));      /* XXXXX */
        if (arg > 0.0) {
                arg = floor(arg + 0.5);
        } else if (arg < 0.0) {
                arg = ceil(arg - 0.5);
        } else {
                arg = 0.0;
        }
        sv_setnv(ST(0), (double)arg);   /* XXXXX */
        SvSETMAGIC(ST(0));
    }
    XSRETURN_EMPTY;
}

Notice the two lines commented with XXXXX. If you check the first part of the typemap file (or section), you'll see that doubles are of type T_DOUBLE. In the INPUT part of the typemap, an argument that is T_DOUBLE is assigned to the variable arg by calling the routine SvNV on something, then casting it to double, then assigned to the variable arg. Similarly, in the OUTPUT section, once arg has its final value, it is passed to the sv_setnv function to be passed back to the calling subroutine. These two functions are explained in perlguts; we'll talk more later about what that ST(0) means in the section on the argument stack.

Warning about Output Arguments 😭

In general, it's not a good idea to write extensions that modify their input parameters, as in Example 3. Instead, you should probably return multiple values in an array and let the caller handle them (we'll do this in a later example). However, in order to better accommodate calling pre-existing C routines, which often do modify their input parameters, this behavior is tolerated.

Lowkey a red flag pattern, but we tolerate it for the sake of old C code. Bestie, if you're writing something fresh β€” return an array instead. 🫢

EXAMPLE 4 πŸ’œ

In this example, we'll now begin to write XSUBs that will interact with pre-defined C libraries. To begin with, we will build a small library of our own, then let h2xs write our .pm and .xs files for us.

Create a new directory called Mytest2 at the same level as the directory Mytest. In the Mytest2 directory, create another directory called mylib, and cd into that directory.

Here we'll create some files that will generate a test library. These will include a C source file and a header file. We'll also create a Makefile.PL in this directory. Then we'll make sure that running make at the Mytest2 level will automatically run this Makefile.PL file and the resulting Makefile.

In the mylib directory, create a file mylib.h that looks like this:

#define TESTVAL 4

extern double   foo(int, long, const char*);

Also create a file mylib.c that looks like this:

#include <stdlib.h>
#include "mylib.h"

double
foo(int a, long b, const char *c)
{
        return (a + b + atof(c) + TESTVAL);
}

And finally create a file Makefile.PL that looks like this:

use ExtUtils::MakeMaker;
$Verbose = 1;
WriteMakefile(
    NAME  => 'Mytest2::mylib',
    SKIP  => [qw(all static static_lib dynamic dynamic_lib)],
    clean => {'FILES' => 'libmylib$(LIB_EXT)'},
);

sub MY::top_targets {
        '
all :: static

pure_all :: static

static ::       libmylib$(LIB_EXT)

libmylib$(LIB_EXT): $(O_FILES)
        $(AR) cr libmylib$(LIB_EXT) $(O_FILES)
        $(RANLIB) libmylib$(LIB_EXT)
';
}

Okay bestie, listen UP, because this one's a whole thing πŸ’€ β€” you must use a tab and not spaces on the lines beginning with $(AR) and $(RANLIB). Make will simply not function properly if you use spaces. Fr fr, it will just sit there being broken and you'll be staring at it like πŸ‘οΈπŸ‘„πŸ‘οΈ. It has also been reported that the cr argument to $(AR) is unnecessary on Win32 systems. Noted, no cap. ✨


Now we're gonna create the main top-level Mytest2 files. Change to the directory above Mytest2 and run this lil beauty:

% h2xs -O -n Mytest2 Mytest2/mylib/mylib.h

This will print out a warning about overwriting Mytest2, but that's totally okay β€” our files are chillin' in Mytest2/mylib and will be left untouched. 🫢

The normal Makefile.PL that h2xs generates has no idea the mylib directory exists. Rude, honestly. So we gotta tell it: hey, there's a subdirectory and we're generating a library in it. Let's add the MYEXTLIB argument to the WriteMakefile call so it looks like this:

WriteMakefile(
    NAME         => 'Mytest2',
    VERSION_FROM => 'lib/Mytest2.pm', # finds $VERSION
    LIBS         => [''],   # e.g., '-lm'
    DEFINE       => '',     # e.g., '-DHAVE_SOMETHING'
    INC          => '',     # e.g., '-I/usr/include/other'
    MYEXTLIB     => 'mylib/libmylib$(LIB_EXT)',
);

and then at the end add a subroutine (which will override the pre-existing subroutine, main character energy only). Remember to use a tab character to indent the line beginning with cd! ⚠️

sub MY::postamble {
'
$(MYEXTLIB): mylib/Makefile
        cd mylib && $(MAKE) $(PASSTHRU)
';
}

Let's also fix the MANIFEST file by appending these three lines, periodt:

mylib/Makefile.PL
mylib/mylib.c
mylib/mylib.h

To keep our namespace nice and unpolluted (vibe check: passed ✨), edit the .pm file and change the variable @EXPORT to @EXPORT_OK. Finally, in the .xs file, edit the #include line to read:

#include "mylib/mylib.h"

And also add the following function definition to the end of the .xs file:

double
foo(a,b,c)
        int             a
        long            b
        const char *    c
    OUTPUT:
        RETVAL

Now we also need to create a typemap, because the default Perl doesn't currently support the const char * type. Smh. 😀 Include a new TYPEMAP section in your XS code before the above function:

TYPEMAP: <<END
const char *    T_PV
END

Now run perl on the top-level Makefile.PL. Notice that it also created a Makefile in the mylib directory. Iconic. πŸŽ€ Run make and watch it do a cd into the mylib directory and run make in there as well. Look at it gooo πŸ¦‹

Now edit the Mytest2.t script and change the number of tests to 5, and add the following lines to the end of the script:

is( Mytest2::foo( 1, 2, "Hello, world!" ), 7 );
is( Mytest2::foo( 1, 2, "0.0" ),           7 );
ok( abs( Mytest2::foo( 0, 0, "-3.4" ) - 0.6 ) <= 0.01 );

(When dealing with floating-point comparisons, it is best to not check for equality, but rather that the difference between the expected and actual result is below a certain amount β€” called epsilon β€” which is 0.01 in this case. This is like, the classic move, iykyk πŸ’…)

Run make test and all should be well. There are some warnings on missing tests for the Mytest2::mylib extension, but you can just ignore them. πŸ™ˆ


✨ What has happened here? ✨

Unlike previous examples, we've now run h2xs on a real include file. This has caused some extra goodies to appear in both the .pm and .xs files. She's got layers now. πŸ‘‘

  • In the .xs file, there's now a #include directive with the absolute path to the mylib.h header file. We changed this to a relative path so that we could move the extension directory if we wanted to. Flexibility, slay. πŸ’–
  • There's now some new C code that's been added to the .xs file. The purpose of the constant routine is to make the values that are #define'd in the header file accessible by the Perl script (by calling either TESTVAL or Mytest2::TESTVAL). There's also some XS code to allow calls to the constant routine.
  • If our include file had contained #include directives, these would not have been processed by h2xs. There is no good solution to this right now. 😭 Yeah. It's giving "known limitation."
  • We've also told Perl about the library that we built in the mylib subdirectory. That required only the addition of the MYEXTLIB variable to the WriteMakefile call and the replacement of the postamble subroutine to cd into the subdirectory and run make. The Makefile.PL for the library is a bit more complicated, but not excessively so. Again we replaced the postamble subroutine to insert our own code. This code simply specified that the library to be created here was a static archive library (as opposed to a dynamically loadable library) and provided the commands to build it.

🧚 Anatomy of .xs file 🧚

The .xs file of EXAMPLE 4 contained some new elements. To understand the meaning of these elements, pay attention to the line which reads

MODULE = Mytest2                PACKAGE = Mytest2

Anything before this line is plain C code which describes which headers to include, and defines some convenience functions. No translations are performed on this part, apart from having embedded POD documentation skipped over (see perlpod) β€” it goes into the generated output C file as is. Set it and forget it, basically. ✨

Anything after this line is the description of XSUB functions. These descriptions are translated by xsubpp into C code which implements these functions using Perl calling conventions, and which makes these functions visible from the Perl interpreter. That's the whole glow-up pipeline. πŸ’…

Pay special attention to the function constant. This name appears twice in the generated .xs file: once in the first part, as a static C function, then another time in the second part, when an XSUB interface to this static C function is defined. Two appearances, one iconic function. πŸ‘‘

This is quite typical for .xs files: usually the .xs file provides an interface to an existing C function. Then this C function is defined somewhere (either in an external library, or in the first part of the .xs file), and a Perl interface to this function (i.e. Perl glue) is described in the second part of the .xs file. The situation in EXAMPLE 1, EXAMPLE 2, and EXAMPLE 3 β€” when all the work is done inside the Perl glue β€” is somewhat of an exception rather than the rule. Not me realizing the first three were the weird ones 😭


πŸ”₯ Getting the fat out of XSUBs πŸ”₯

In EXAMPLE 4 the second part of the .xs file contained the following description of an XSUB:

double
foo(a,b,c)
        int             a
        long            b
        const char *    c
    OUTPUT:
        RETVAL

Note that in contrast with EXAMPLE 1, EXAMPLE 2 and EXAMPLE 3, this description does not contain the actual code for what is done during a call to Perl function foo(). To understand what is going on here, one can add a CODE section to this XSUB:

double
foo(a,b,c)
        int             a
        long            b
        const char *    c
    CODE:
        RETVAL = foo(a,b,c);
    OUTPUT:
        RETVAL

However β€” plot twist β€” these two XSUBs provide almost identical generated C code: the xsubpp compiler is smart enough to figure out the CODE: section from the first two lines of the description of the XSUB. She's reading your mind, bestie 🧠✨

What about the OUTPUT: section? In fact, that is absolutely the same! The OUTPUT: section can be removed as well, as far as the CODE: section or PPCODE: section is not specified: xsubpp can see that it needs to generate a function call section, and will autogenerate the OUTPUT section too. So lazy-girl-optimized, and we support it. 🫢 Thus one can shortcut the XSUB to become:

double
foo(a,b,c)
        int             a
        long            b
        const char *    c

Can we do the same with an XSUB

int
is_even(input)
        int     input
    CODE:
        RETVAL = (input % 2 == 0);
    OUTPUT:
        RETVAL

of EXAMPLE 2? To do this, one needs to define a C function int is_even(int input). As we saw in Anatomy of .xs file, a proper place for this definition is in the first part of the .xs file. In fact a C function

int
is_even(int arg)
{
        return (arg % 2 == 0);
}

is probably overkill for this. Something as simple as a #define will do too:

#define is_even(arg)    ((arg) % 2 == 0)

After having this in the first part of the .xs file, the Perl glue part becomes as simple as

int
is_even(input)
        int     input

This technique of separation of the glue part from the workhorse part has obvious tradeoffs: if you want to change a Perl interface, you need to change two places in your code. πŸ™ƒ However, it removes a lot of clutter, and makes the workhorse part independent from idiosyncrasies of the Perl calling convention. (In fact, there is nothing Perl-specific in the above description β€” a different version of xsubpp might have translated this to TCL glue or Python glue as well.) Multilingual king behavior. 🌈


πŸ’œ More about XSUB arguments πŸ’œ

With the completion of Example 4, we now have an easy way to simulate some real-life libraries whose interfaces may not be the cleanest in the world. We shall now continue with a discussion of the arguments passed to the xsubpp compiler.

When you specify arguments to routines in the .xs file, you are really passing three pieces of information for each argument listed:

  1. The order of that argument relative to the others (first, second, etc).
  2. The type of argument, consisting of the type declaration of the argument (e.g., int, char*, etc).
  3. The calling convention for the argument in the call to the library function.

While Perl passes arguments to functions by reference, C passes arguments by value; to implement a C function which modifies data of one of the "arguments", the actual argument of this C function would be a pointer to the data. Thus two C functions with declarations

int string_length(char *s);
int upper_case_char(char *cp);

may have completely different semantics: the first one may inspect an array of chars pointed by s, and the second one may immediately dereference cp and manipulate *cp only (using the return value as, say, a success indicator). From Perl one would use these functions in a completely different manner.

One conveys this info to xsubpp by replacing * before the argument by &. & means that the argument should be passed to a library function by its address. The above two functions may be XSUB-ified as

        int
        string_length(s)
                char *  s

        int
        upper_case_char(cp)
                char    &cp

Okay so like, real example, consider this:

        int
        foo(a,b)
                char    &a
                char *  b

Here's what happens: the first Perl argument that comes in gets treated as a char and assigned to the variable a, and then its address gets passed into the function foo. The second Perl argument gets treated as a string pointer and assigned to the variable b, and the value of b gets passed into foo. So the actual call that xsubpp generates literally looks like this:

        foo(&a, b);

And bestie, xsubpp is so chill about whitespace β€” it parses all three of these argument lists identically:

        char    &a
        char&a
        char    & a

But for the sake of your own sanity and everyone who has to read your code later, the suggestion is: put your & right up next to the variable name and far away from the variable type, and put your * near the variable type but away from the variable name (exactly like the foo call above πŸ’…). That way you can just glance at the last column and immediately know what's actually getting passed to the C function.

You should take great pains to try to hand the function the exact type of variable it wants, whenever you can. It'll save you SO much grief down the road, no cap.

✨ The Argument Stack ✨

If you peek at any of the C code that any example past example 1 generated, you'll notice a bunch of references to ST(n), where n is usually 0. ST is actually a macro that points to the n'th argument on the argument stack. So ST(0) is the first argument on the stack β€” which means it's the first argument passed to the XSUB β€” ST(1) is the second, and so on. It's giving very much indexed array energy.

When you list the arguments to your XSUB in the .xs file, that's what tells xsubpp which argument corresponds to which slot on the argument stack (like, first one listed = first argument, etc.). And bestie, you are inviting disaster if you don't list them in the exact same order the function expects them. πŸ’€

The actual values sitting on the argument stack are pointers to the values that were passed in. When an argument is listed as being an OUTPUT value, the value that corresponds to it on the stack (so ST(0) if it was the first argument) gets changed. You can literally verify this yourself by looking at the C code generated for Example 3 β€” the code for the round() XSUB routine contains lines that look like this:

        double  arg = (double)SvNV(ST(0));
        /* Round the contents of the variable arg */
        sv_setnv(ST(0), (double)arg);

So the arg variable starts off by grabbing the value out of ST(0), and then at the end of the routine it gets stored back into ST(0). Clean. Very demure.

XSUBs are also allowed to return lists, not just plain scalars! But to do that you have to manipulate stack values ST(0), ST(1), etc. in a subtly different way. See perlxs for the details.

XSUBs are also allowed to avoid the automatic conversion of Perl function arguments to C function arguments. See perlxs for the details on that too. Some people prefer doing the conversion manually by inspecting ST(i) even when automatic conversion would work fine, arguing that it makes the logic of an XSUB call easier to follow. Compare with "Getting the fat out of XSUBs" for a similar tradeoff involving completely separating the "Perl glue" parts of an XSUB from the "workhorse" parts.

Now, while the experts can argue about these idioms all day, a newbie to Perl guts might prefer a way that's as little Perl-guts-specific as possible β€” meaning automatic conversion and automatic call generation, exactly like in "Getting the fat out of XSUBs". And honestly? This approach has an extra little bonus: it protects the XSUB writer from future changes to the Perl API. 🫢


πŸŽ€ Extending your Extension πŸŽ€

Sometimes you'll want to provide some extra methods or subroutines to help make the interface between Perl and your extension simpler or easier to understand. Those routines should live in the .pm file. Whether they get automatically loaded when the extension itself loads, or only load when they're actually called, depends on where in the .pm file you put the subroutine definition. You can also consult AutoLoader for an alternate way to store and load your extra subroutines.


πŸ“ Documenting your Extension πŸ“

There is absolutely no excuse for not documenting your extension. Like, none. Zero. Documentation belongs in the .pm file. That file gets fed to pod2man, and the embedded documentation gets converted into manpage format, then dropped into the blib directory. It'll get copied into Perl's manpage directory when the extension is installed.

You may intersperse documentation and Perl code within the .pm file β€” in fact, if you want to use method autoloading, you must do this, as the comment inside the .pm file explains.

See perlpod for more info about the pod format. ✨


πŸ“¦ Installing your Extension πŸ“¦

Once your extension is complete and passes all its tests, installing it is genuinely so simple: you just run make install. You'll either need write permission into the directories where Perl is installed, or you can ask your system administrator to run the make for you.

Alternatively, you can specify the exact directory to place the extension's files by putting a PREFIX=/destination/directory after the make install (or in between the make and install if you have a brain-dead version of make, rip). This is super useful if you're building an extension that's eventually going to be distributed to multiple systems β€” you can just archive the files in the destination directory and distribute them to your destination systems. Slay.


🌸 EXAMPLE 5 🌸

In this example we're doing some more work with the argument stack. Every previous example only returned a single value β€” now we're gonna create an extension that returns an array. Growth. 🌱

This extension is very Unix-oriented (struct statfs and the statfs system call). If you're not running on a Unix system, you've got options: substitute any other function that returns multiple values for statfs, hard-code values to be returned to the caller (though that'll make the error case a bit harder to test), or just simply skip this example. And if you change the XSUB, be sure to fix the test cases to match the changes!

Head back to the Mytest directory and add this code to the end of Mytest.xs:

        void
        statfs(path)
                char *  path
            INIT:
                int i;
                struct statfs buf;

            PPCODE:
                i = statfs(path, &buf);
                if (i == 0) {
                        XPUSHs(sv_2mortal(newSVnv(buf.f_bavail)));
                        XPUSHs(sv_2mortal(newSVnv(buf.f_bfree)));
                        XPUSHs(sv_2mortal(newSVnv(buf.f_blocks)));
                        XPUSHs(sv_2mortal(newSVnv(buf.f_bsize)));
                        XPUSHs(sv_2mortal(newSVnv(buf.f_ffree)));
                        XPUSHs(sv_2mortal(newSVnv(buf.f_files)));
                        XPUSHs(sv_2mortal(newSVnv(buf.f_type)));
                } else {
                        XPUSHs(sv_2mortal(newSVnv(errno)));
                }

You'll also need to add this code to the top of the .xs file, just after the include of XSUB.h:

        #include <sys/vfs.h>

Also add this code segment to Mytest.t while incrementing the 9 tests to 11:

    my @a;

        @a = Mytest::statfs("/blech");
        ok( scalar(@a) == 1 && $a[0] == 2 );

        @a = Mytest::statfs("/");
        is( scalar(@a), 7 );

πŸ’– New Things in this Example πŸ’–

This example added quite a few new concepts, bestie. Let's take them one at a time.

  • The INIT: directive contains code that will be placed immediately after the argument stack is decoded. C doesn't allow variable declarations at arbitrary locations inside a function, so this is usually the best way to declare the local variables your XSUB needs. (Alternatively, you could put the whole PPCODE: section into braces and put those declarations on top.)
  • This routine also returns a different number of arguments depending on whether the statfs call succeeds or fails. If there's an error, the error number gets returned as a single-element array. If the call succeeds, a 7-element array gets returned. Since only one argument is passed into this function, we need room on the stack to hold those 7 values that might be returned.

We pull this off by using the PPCODE: directive rather than the CODE: directive. That tells xsubpp that we're handling the return values that get put on the argument stack ourselves.

  • When we want to place values to be returned to the caller onto the stack, we use that series of macros starting with XPUSH. There are five different versions, for placing integers, unsigned integers, doubles, strings, and Perl scalars on the stack. In our example, we placed a Perl scalar onto the stack. (In fact this is the only macro that can be used to return multiple values.)

The XPUSH* macros will automatically extend the return stack to keep it from being overrun. You push values onto the stack in the order you want the calling program to see them.

  • The values pushed onto the return stack of the XSUB are actually mortal SVs. They're made mortal so that once the calling program copies the values, the SVs that held those returned values can be deallocated. If they weren't mortal, they'd keep existing after the XSUB routine returned, but they'd be inaccessible. That's a memory leak. Not the vibe. πŸ™ˆ
  • If we cared about performance instead of code compactness, in the success branch we wouldn't use the XPUSHs macros β€” we'd use PUSHs macros, and pre-extend the stack before pushing the return values:
        EXTEND(SP, 7);

The tradeoff is that you'd need to calculate the number of return values in advance (though overextending the stack won't typically hurt anything except memory consumption).

Similarly, in the failure branch we could use PUSHs without extending the stack, because the Perl function reference comes to an XSUB on the stack β€” so the stack is always large enough to take one return value.


πŸ¦‹ EXAMPLE 6 πŸ¦‹

In this example, we'll accept a reference to an array as an input parameter, and return a reference to an array of hashes. This demonstrates manipulation of complex Perl data types from an XSUB. Main character data-structure energy, honestly.

This extension is kind of contrived. It's based on the code from the previous example. It calls the statfs function multiple times, accepting a reference to an array of filenames as input, and returning a reference to an array of hashes containing the data for each of the filesystems.

Okay bestie, we're in the final stretch and honestly this is where it gets so good. πŸ’…

Go back to the Mytest directory and yeet the following code onto the end of Mytest.xs:

SV *
multi_statfs(paths)
        SV * paths
    INIT:
        AV * results;
        SSize_t numpaths = 0, n;
        int i;
        struct statfs buf;

        SvGETMAGIC(paths);
        if ((!SvROK(paths))
            || (SvTYPE(SvRV(paths)) != SVt_PVAV)
            || ((numpaths = av_top_index((AV *)SvRV(paths))) < 0))
        {
            XSRETURN_UNDEF;
        }
        results = (AV *)sv_2mortal((SV *)newAV());
    CODE:
        for (n = 0; n <= numpaths; n++) {
            HV * rh;
            STRLEN l;
            SV * path = *av_fetch((AV *)SvRV(paths), n, 0);
            char * fn = SvPVbyte(path, l);

            i = statfs(fn, &buf);
            if (i != 0) {
                av_push(results, newSVnv(errno));
                continue;
            }

            rh = (HV *)sv_2mortal((SV *)newHV());

            hv_store(rh, "f_bavail", 8, newSVnv(buf.f_bavail), 0);
            hv_store(rh, "f_bfree",  7, newSVnv(buf.f_bfree),  0);
            hv_store(rh, "f_blocks", 8, newSVnv(buf.f_blocks), 0);
            hv_store(rh, "f_bsize",  7, newSVnv(buf.f_bsize),  0);
            hv_store(rh, "f_ffree",  7, newSVnv(buf.f_ffree),  0);
            hv_store(rh, "f_files",  7, newSVnv(buf.f_files),  0);
            hv_store(rh, "f_type",   6, newSVnv(buf.f_type),   0);

            av_push(results, newRV_inc((SV *)rh));
        }
        RETVAL = newRV_inc((SV *)results);
    OUTPUT:
        RETVAL

And then add this to Mytest.t, while bumping that "11" tests up to "13":

my $results = Mytest::multi_statfs([ '/', '/blech' ]);
ok( ref $results->[0] );
ok( ! ref $results->[1] );

New Things in this Example ✨

Okay there is a lot of new lore here, so let's go bullet by bullet, no skimming:

  • This function does not use a typemap. Nope. Instead, we declare it as accepting one SV* (scalar) parameter, and returning an SV* value, and then we take care of populating these scalars within the code. And because we are only returning one value, we don't need a "PPCODE:" directive β€” instead, we use "CODE:" and "OUTPUT:" directives. πŸŽ€
  • When you're dealing with references, it is important to handle them with caution. The "INIT:" block first calls SvGETMAGIC(paths), in case paths is a tied variable. Then it checks that "SvROK" returns true, which indicates that paths is a valid reference. (Simply checking "SvROK" won't trigger FETCH on a tied variable.) It then verifies that the object referenced by paths is an array, using "SvRV" to dereference paths, and "SvTYPE" to discover its type. As an added test, it checks that the array referenced by paths is non-empty, using the "av_top_index" function (which returns -1 if the array is empty). The XSRETURN_UNDEF macro is used to abort the XSUB and return the undefined value whenever all three of these conditions are not met. πŸ‘‘
  • We manipulate several arrays in this XSUB. Note that an array is represented internally by an AV* pointer. The functions and macros for manipulating arrays are similar to the functions in Perl: "av_top_index" returns the highest index in an AV*, much like $#array; "av_fetch" fetches a single scalar value from an array, given its index; "av_push" pushes a scalar value onto the end of the array, automatically extending the array as necessary. πŸ¦‹

Specifically, we read pathnames one at a time from the input array, and store the results in an output array (results) in the same order. If statfs fails, the element pushed onto the return array is the value of errno after the failure. If statfs succeeds, though, the value pushed onto the return array is a reference to a hash containing some of the information in the statfs structure.

As with the return stack, it would be possible (and a small performance win) to pre-extend the return array before pushing data into it, since we know how many elements we will return:

av_extend(results, numpaths);
  • We are performing only one hash operation in this function, which is storing a new scalar under a key using "hv_store". A hash is represented by an HV* pointer. Like arrays, the functions for manipulating hashes from an XSUB mirror the functionality available from Perl. See perlguts and perlapi for details. 🫢
  • To create a reference, we use the "newRV_inc" function. Note that you can cast an AV* or an HV* to type SV* in this case (and many others). This allows you to take references to arrays, hashes and scalars with the same function. Conversely, the "SvRV" function always returns an SV*, which may need to be cast to the appropriate type if it is something other than a scalar (check with "SvTYPE"). πŸ’–
  • At this point, xsubpp is doing very little work β€” the differences between Mytest.xs and Mytest.c are minimal. πŸ”₯

EXAMPLE 7 (Coming Soon) 🚧

XPUSH args AND set RETVAL AND assign return value to array

EXAMPLE 8 (Coming Soon) 🚧

Setting $!


EXAMPLE 9 Passing open files to XSes 🌈

Okay so you'd think passing files to an XS is difficult, what with all the typeglobs and stuff. Well. Bestie. It isn't. πŸ’…

Suppose that for some strange reason we need a wrapper around the standard C library function fputs(). This is all we need:

#define PERLIO_NOT_STDIO 0  /* For co-existence with stdio only */
#define PERL_NO_GET_CONTEXT /* This is more efficient */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

#include <stdio.h>

int
fputs(s, stream)
  char *          s
  FILE *          stream

The real work is done in the standard typemap. ✨

For more details, see "Co-existence with stdio" in perlapio.

But β€” and this is the big but β€” you lose all the fine stuff done by the perlio layers. This calls the stdio function fputs(), which knows nothing about them. 😭

The standard typemap offers three variants of PerlIO *: "InputStream" (T_IN), "InOutStream" (T_INOUT) and "OutputStream" (T_OUT). A bare "PerlIO *" is considered a T_INOUT. If it matters in your code (see below for why it might) #define or typedef one of the specific names and use that as the argument or result type in your XS file.

The standard typemap does not contain PerlIO * before perl 5.7, but it has the three stream variants. Using a PerlIO * directly is not backwards compatible unless you provide your own typemap.

For streams coming from perl the main difference is that "OutputStream" will get the output PerlIO * β€” which may make a difference on a socket. Like in our example...

For streams being handed to perl a new file handle is created (i.e. a reference to a new glob) and associated with the PerlIO * provided. If the read/write state of the PerlIO * is not correct then you may get errors or warnings from when the file handle is used. So if you opened the PerlIO * as "w" it should really be an "OutputStream"; if open as "r" it should be an "InputStream". 🌸

Now, suppose you want to use perlio layers in your XS. We'll use the perlio PerlIO_puts() function as an example.

In the C part of the XS file (above the first MODULE line) you have

#define OutputStream    PerlIO *

or

typedef PerlIO *        OutputStream;

And this is the XS code:

int
perlioputs(s, stream)
        char *          s
        OutputStream    stream
CODE:
        RETVAL = PerlIO_puts(stream, s);
OUTPUT:
        RETVAL

We have to use a "CODE" section because PerlIO_puts() has the arguments reversed compared to fputs(), and we want to keep the arguments the same. 🧚

Wanting to explore this thoroughly, we want to use the stdio fputs() on a PerlIO *. This means we have to ask the perlio system for a stdio "FILE *":

int
perliofputs(s, stream)
        char *          s
        OutputStream    stream
PREINIT:
        FILE *fp = PerlIO_findFILE(stream);
CODE:
        if (fp != (FILE*) 0) {
                RETVAL = fputs(s, fp);
        } else {
                RETVAL = -1;
        }
OUTPUT:
        RETVAL
Note: PerlIO_findFILE() will search the layers for a stdio layer. If it can't find one, it will call PerlIO_exportFILE() to generate a new stdio "FILE". Please only call PerlIO_exportFILE() if you want a new "FILE". It will generate one on each call and push a new stdio layer. So don't call it repeatedly on the same file. PerlIO_findFILE() will retrieve the stdio layer once it has been generated by PerlIO_exportFILE(). πŸ’€

This applies to the perlio system only. For versions before 5.7, PerlIO_exportFILE() is equivalent to PerlIO_findFILE().


Troubleshooting these Examples 🩹

As mentioned at the top of this document, if you are having problems with these example extensions, you might see if any of these help you.

  • This document assumes that the executable named "perl" is Perl version 5. Some systems may have installed Perl version 5 as "perl5".

🌟 See also 🌟

For more information, consult perlguts, perlapi, perlclib, perlxs, perlmod, perlapio, and perlpod

πŸ’œ Author πŸ’œ

Jeff Okamoto <okamoto@corp.hp.com>

Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig, and Tim Bunce.

PerlIO material contributed by Lupe Christoph, with some clarification by Nick Ing-Simmons.

Changes for h2xs as of Perl 5.8.x by Renee Baecker

This document is now maintained as part of Perl itself.

Last Changed

2020-10-05


And that's a wrap on PERLXSTUT, bestie!! πŸŽ€βœ¨ You just read the whole thing and you literally know XS now. This page is from perl v5.44.0, dated 2026-10-17, and it lives in the manual as PERLXSTUT(1perl) β€” go forth and slay your extensions πŸ’…πŸ‘‘

πŸ“¦ where this page comes from
  • arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms