O'Reilly logo

Advanced Perl Programming by Sriram Srinivasan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Meaty Extensions

Having armed ourselves to the teeth with information, and having hand-built a few extensions, we are now ready to exploit SWIG and XS to their hilts. In this section, we’ll first look at the type of code produced by XS. As it happens, SWIG produces almost identical code, so the explanation should suffice for both tools. Then we will write typemaps and snippets of code to help XS deal with C structures, to wrap C structures with Perl objects, and, finally, to interface with C++ objects. Most of this discussion is relevant to SWIG also, which is why we need study only one SWIG example. That said, take note that the specific XS typemap examples described in the following pages are solved simply and elegantly using SWIG, without the need for user-defined typemaps.

Anatomy of an XS Extension

To understand XS typemaps, and the effect of keywords such as CODE and PPCODE, it pays to take a good look at the glue code generated by xsubpp. Consider the following XS declaration of a module, Test, containing a function that takes two arguments and returns an integer:

MODULE = Test  PACKAGE = Test
int
func_2_args(a, b)
   int    a
   char*  b

xsubpp translates it to the following (comments in italic have been added):

XS(XS_Test_func_2_args) /*  Mangled function name, with package name */
               /* added to make it unique                                 */
{
    dXSARGS;            /* declare "items", and init it with                     */
if (items != 2)     /* the number of items on the stack                    */
croak("Usage: Test::func_2_args(a, b)");

    {   /* Start a fresh block to allow ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required