Perl and XS: Introduction


  1. Introduction
  2. Concepts
  3. Example 1: Geometry
  4. The typemap
  5. Example 2: Math::Ackermann
  6. Example 3: Set::Bit

What it is

XS stands for eXternal Subroutine. XS specifies how to call C subroutines from Perl.

Learning XS

Learning XS from perlxs and perlguts is difficult, because the documentation omits background information.

XS is a collection of macros processed by a program called xsubpp. Xsubpp expands XS macros into C code.

To learn XS, you have to learn the Perl C API, Perl's internal data structures, the Perl stack, and how a C subroutine gets access to it. Once you understand all this, you don't need XS: you can code directly to the Perl C API.

However, the Perl C API is repetitive. You have to keep writing the same little bits of code to move parameters on and off the Perl stack; to convert data from Perl's internal representation to C variables; to check for null pointers and other Bad Things. When you make a mistake, you don't get bad output: you crash the interpreter. The advantage of wrapping these little bits of code in macros is that you can write them once and then stop worrying about them. And what do you know, someone has already written some macros for you; there is even this macro expander called xsubpp.


  1. Introduction
  2. Concepts
  3. Example 1: Geometry
  4. The typemap
  5. Example 2: Math::Ackermann
  6. Example 3: Set::Bit

Notes on these adapted articles

These pages are an adaptation of articles written in 2000 by Steven W. McDougall. My goal in modifying these articles is to simplify and update them. I hope you find these adapted versions of the articles useful. You can find the original articles at the link at the bottom of this page. The major changes in this update are:

This adaptation is a work in progress and many of the links on these pages may not work.


Creative Commons License
XS Mechanics by Steven W. McDougall is licensed under a Creative Commons Attribution 3.0 Unported License.

For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer