Xsub style

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I'm working on a Perl extension written in C and have been reading the  
Perl man pages on xsubs (perlxs and perlxstut). I've found the  
documentation very hard to follow, to be honest. The style outlined for  
creating Perl xsubs is different from C coding in other languages, cf:

           ST(0) = newSVpv("Hello World",0);
   SV *
           RETVAL = newSVpv("Hello World",0);

In looking for various examples of Perl extensions using the xsub API, I  
ran across a very different style that seems much easier to understand,  
as referenced here:


Here's a small example:

XS(hello) {
     NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
     [pool drain];

This example creates a Perl subroutine called "hello," calls into C code  
(Objective-C, in this case), and then returns.

The second example is much easier for me to model in my head. I want a  
C-based subroutine  in Perl called "hello," and so I wrap the command in  
an XS { } call, and then call it from Perl; it offers a very clean  
mapping from Perl to C.

Is there any reason this style of extending Perl in C is not outlined in  
any of the official docs, as far as I can find? Have I missed something?  
The canonical example above is opaque, at least to my eye, while the  
latter example is much easier to grok.

If anyone knows of some additional referneces that highlight the latter  
style of xsub programming, I'd love to see them.


Kevin Walzer
Code by Kevin/Mobile Code by Kevin

Re: Xsub style

Quoted text here. Click to load it

This examples ignores most of the XS macros in favour of writing
corresponding C code by hand. That's surely a point in favour of "real
men dig tunnels with tea spoons and clean the floor with a tooth brush[*]"
(and suggesting that they don't know how to use any other tools would be
disingenious) but I can see little else in it.

Quoted text here. Click to load it

For the sake of example, let's assume the POSIX fsync call is to be made
available to perl (not as useless as it may sound because POSIX::fsync
doesn't call fsync). As XS routine, this looks like this:

    int fd

This even won't be over unfamiliar to someone knowing C as the 'put the
return value on a lines of its own' is not that uncommon as convention
and the other parts is just a K&R-style function preamble. The
corresponding C code is (for perl 5.10.1 and 5.14.2)

XS(XS__fsync); /* prototype to pass -Wmissing-prototypes */
#ifdef dVAR
    dVAR; dXSARGS;
    if (items != 1)
       croak_xs_usage(cv,  "fd");
        int     fd = (int)SvIV(ST(0));
        int     RETVAL;

        RETVAL = fsync(fd);
        XSprePUSH; PUSHi((IV)RETVAL);

In case writing all of this suits you better, no one's going to stop you
from it, you're just working more than necessary in order to perform
worse ...
[*] ... and put their underpants in the diswasher ...

Site Timeline