You are viewing the version of this documentation from Perl 5.36.2. View the latest version

CONTENTS

NAME

perlxstut - Tutorial for writing XSUBs

DESCRIPTION

This tutorial will educate the reader on the steps involved in creating a Perl extension. The reader is assumed to have access to perlguts, perlapi and perlxs.

This tutorial starts with very simple examples and becomes more complex, with each new example adding new features. Certain concepts may not be completely explained until later in the tutorial in order to slowly ease the reader into building extensions.

This tutorial was written from a Unix point of view. Where I know them to be otherwise different for other platforms (e.g. Win32), I will list them. If you find something that was missed, please let me know.

SPECIAL NOTES

make

This tutorial assumes that the make program that Perl is configured to use is called make. Instead of running "make" in the examples that follow, you may have to substitute whatever make program Perl has been configured to use. Running perl -V:make should tell you what it is.

Version caveat

When writing a Perl extension for general consumption, one should expect that the extension will be used with versions of Perl different from the version available on your machine. Since you are reading this document, the version of Perl on your machine is probably 5.005 or later, but the users of your extension may have more ancient versions.

To understand what kinds of incompatibilities one may expect, and in the rare case that the version of Perl on your machine is older than this document, see the section on "Troubleshooting these Examples" for more information.

If your extension uses some features of Perl which are not available on older releases of Perl, your users would appreciate an early meaningful warning. You would probably put this information into the README file, but nowadays installation of extensions may be performed automatically, guided by CPAN.pm module or other tools.

In MakeMaker-based installations, Makefile.PL provides the earliest opportunity to perform version checks. One can put something like this in Makefile.PL for this 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

It is commonly thought that if a system does not have the capability to dynamically load a library, you cannot build XSUBs. This is incorrect. You can build them, but you must link the XSUBs subroutines with the rest of Perl, creating a new executable. This situation is similar to Perl 4.

This tutorial can still be used on such a system. The XSUB build mechanism will check the system and build a dynamically-loadable library if possible, or else a static library and then, optionally, a new statically-linked executable with that static library linked in.

Should you wish to build a statically-linked executable on a system which can dynamically load libraries, you may, in all the following examples, where the command "make" with no arguments is executed, run the command "make perl" instead.

If you have generated such a statically-linked executable by choice, then instead of saying "make test", you should say "make test_static". On systems that cannot build dynamically-loadable libraries at all, simply saying "make test" is sufficient.

Threads and PERL_NO_GET_CONTEXT

For threaded builds, perl requires 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 will be very simple. When we call the routine in the extension, it will print out a well-known message and return.

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 will be 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 => '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 is suggested that you indent CODE: one level and the lines following one more level.

Now we'll run "perl Makefile.PL". This will create 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 is explained in "The PROTOTYPES: Keyword" in perlxs.

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:

#! /opt/perl5/bin/perl

use ExtUtils::testlib;

use Mytest;

Mytest::hello();

Now we make the script executable (chmod +x hello), run the script and we should see the following output:

% ./hello
Hello, world!
%

EXAMPLE 2

Now let's add to our extension a subroutine that will take a single numeric argument as input and return 1 if the number is even or 0 if the number is odd.

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 is 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.

Now perform the same steps as before, generating a Makefile from the Makefile.PL file, and running make.

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 is not.

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.

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!