XS Features

XS, as we mentioned earlier, is an interface definition language. Unlike SWIG, XS concentrates solely on C functions and #define‘d constants and does not provide any support for struct or class definitions (although there are plans for doing so in the future). In practice, I haven’t missed this support for structures and classes too much because I rarely export data structures, in keeping with encapsulation principles.

The XS approach allows you to modify the XS file and supply glue code (in C) in varying degrees. It is analogous to C or Pascal compilers that allow you to insert native assembly code within a program. This gives a lot of power if you know what you are doing, but requires you to be conversant with the internal Perl API and protocols.

By modifying the XS file, you can create write function wrappers that take a variable number of input parameters, modify some input parameters (as read does), and return an array of result values. Combine this with the ability to write custom typemaps and modify the Perl module (produced by h2xs), and you have several ways of creating extensions.

Let us take a brief look at XS syntax. Fractal.xs, from our earlier example, looks like this in its most essential form:

#include <mandel.h>

MODULE = Fractal    PACKAGE = Fractal

int 
draw_mandel (filename,width,height,origin_real,origin_imag,range,depth)
      char*  filename
      int    width
      int    height
      double origin_real
      double origin_imag
      double range
      double depth

All text preceding a MODULE statement ...

Get Advanced Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.