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 (see below). BackgroundSubroutine 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 interpreterThe 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[why?] and highly technical, and using it requires some understanding of the interpreter. The earliest reference on the subject was the perlguts POD. WrappersIt is possible to write XS modules that wrap C++ code. Doing so is mostly a matter of configuring the module build system.[1] Example codeThe following shows an XS module that exposes a function #define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
SV* _do_sv_catsv (pTHX_ SV* one_sv, SV* two_sv ) {
SV* one_copy = newSVsv(one_sv);
sv_catsv(one_copy, two_sv);
return one_copy;
}
MODULE = Demo::XSModule PACKAGE = Demo::XSModule
SV*
concat (SV* one_sv, SV* two_sv)
CODE:
SV* to_return = _do_sv_catsv( aTHX_ one_sv, two_sv );
RETVAL = to_return;
OUTPUT:
RETVAL
The first four lines ( After then follow any number of plain C functions that are callable locally. The section that starts with Perl’s documentation explains the meaning and purpose of all of the “special” symbols (e.g., To make this module available to Perl it must be compiled. Build tools like ExtUtils::MakeMaker can do this automatically. (To build manually: the xsubpp tool parses an XS module and outputs C source code; that source code is then compiled to a shared library and placed in a directory where Perl can find it.) Perl code then uses a module like XSLoader to load the compiled XS module. At this point Perl can call Note that, for building Perl interfaces to preexisting C libraries, the h2xs[further explanation needed] can automate much of the creation of the XS file itself. DifficultiesCreation 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. See also
References
External links
|