XS (Perl)
From Wikipedia, the free encyclopedia
XS is an interface through which a Perl program can call a C or C++ language subroutine. The letters stand for eXternal Subroutine, or xsub, where external means external to Perl, i.e. written in some other language.
It may be desirable for a Perl program to invoke a C subroutine in order to handle very CPU- or memory- intensive tasks, interface with hardware or low-level system facilities, or make use of existing C subroutine libraries.
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 using it requires some understanding of the interpreter. The earliest reference on the subject was the perlguts POD, the word guts suggesting the highly technical nature of the material.
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. To create an XS module, a programmer first runs h2xs
to create an empty module, adds the C subroutines, specifies the calling interfaces to the C subroutines, using a specialized glue language (also referred to as XS), and compiles, tests, and installs the module with make
Once an XS module is installed, it can be loaded into a Perl program with a use
statement, like an ordinary Perl module. Once the module is loaded, the C subroutines can be called from Perl code, as if they were written in Perl.
XS modules are not without drawbacks. They are difficult to write and maintain, may only be installed if a C compiler and the headers that the Perl interpreter were compiled against are available. Also of note is that new versions of Perl may break binary compatibility; if this happens, all XS modules must be recompiled.
It is also possible to write XS modules that wrap C++ code. Doing so is mostly a matter of wrestling with the module build system. Details on how to do this are given here.
[edit] References
- Jenness, Tim & Cozens, Simon (2002). "Extending and Embedding Perl". Greenwich: Manning Publications Co. ISBN 1-930110-82-0
[edit] External links
- perlxs Perl XS application programming interface
- perlxstut Perl XS tutorial
- perlguts Perl internal functions for those doing extensions
- perlapi Perl API listing (autogenerated)
- XS Mechanics tutorial
- Perl and C++ building XS modules for C++