XS (Perl)

From Wikipedia, the free encyclopedia
Jump to: navigation, search

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 "eXternal Subroutine", where external refers to programming languages external to Perl.

XS also refers to a glue language for specifying calling interfaces supporting such interfaces (see below).

Background[edit]

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[why?] 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[edit]

Main article: calling convention

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

Wrappers[edit]

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

XS module creation[edit]

Main article: Perl module

To create an XS module, h2xs[further explanation needed] is first used[why?] to create an empty module. Next[why?], C subroutines are added, and the calling interfaces to the C subroutines are specified with a specialized glue language. Finally[why?], the module is compiled, tested, and installed 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.

Difficulties[edit]

XS modules are difficult[why?] to write and maintain, and they 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[edit]

  • SWIG, an alternative to XS which also supports calling C and C++ functions from several other languages.

References[edit]

  1. ^ "Gluing C++ And Perl Together". johnkeiser.com. August 27, 2001. 

External links[edit]