XS (Perl)


XS is a Perl foreign function interface through which a program can call a C or C++ subroutine. XS or xsub is an abbreviation of "eXtendable Subroutine".
XS also refers to a glue language for specifying calling interfaces supporting such interfaces.

Background

Subroutine libraries in Perl are called modules, and modules that contain xsubs are called XS modules. Perl provides a framework for developing, packaging, distributing, and installing modules.
It may be desirable for a Perl program to invoke a C subroutine in order to handle very CPU or memory intensive tasks, to interface with hardware or low-level system facilities, or to make use of existing C subroutine libraries.

Perl interpreter

The Perl interpreter is a C program, so in principle there is no obstacle to calling from Perl to C. However, the XS interface is complex and highly technical, and using it requires some understanding of the interpreter. The earliest reference on the subject was the POD.

Wrappers

It is possible to write XS modules that wrap C++ code. Doing so is mostly a matter of configuring the module build system.

Example code

The following shows an XS module that exposes a function concat to concatenate two strings.

  1. define PERL_NO_GET_CONTEXT
  2. include "EXTERN.h"
  3. include "perl.h"
  4. include "XSUB.h"
SV* _do_sv_catsv


MODULE = Demo::XSModule PACKAGE = Demo::XSModule
SV*
concat
CODE:
SV* to_return = _do_sv_catsv;
RETVAL = to_return;
OUTPUT:
RETVAL

The first four lines are standard boilerplate.
After then follow any number of plain C functions that are callable locally.
The section that starts with MODULE = Demo::XSModule defines the Perl interface to this code using the actual XS macro language. Note that the C code under the CODE: section calls the _do_sv_catsv pure-C function that was defined in the prior section.
Perl’s documentation explains the meaning and purpose of all of the “special” symbols shown above.
To make this module available to Perl it must be compiled. Build tools like can do this automatically. Perl code then uses a module like to load the compiled XS module. At this point Perl can call Demo::XSModule::concat and receive back a string foobar, as if concat were itself written in Perl.
Note that, for building Perl interfaces to preexisting C libraries, the h2xs can automate much of the creation of the XS file itself.

Difficulties

Creation and maintenance of XS modules requires expertise with C itself as well as Perl’s extensive C API. XS modules may only be installed if a C compiler and the header files that the Perl interpreter was compiled against are available. Also, new versions of Perl may break binary compatibility requiring XS modules to be recompiled.