SEARCH
NEW RPMS
DIRECTORIES
ABOUT
FAQ
VARIOUS
BLOG

BotDetect - Real-Time Bot Detection API
 
 

MAN page from Old RedHat 5.X perl-5.004-4.i386.rpm

PERLXS

Section: Perl Programmers Reference Guide (1)
Updated: perl 5.004, patch 04
Index 

NAME

perlxs - XS language reference manual 

DESCRIPTION

 

Introduction

XS is a language used to create an extension interfacebetween Perl and some C library which one wishes to use withPerl. The XS interface is combined with the library tocreate a new library which can be linked to Perl. An XSUBis a function in the XS language and is the core componentof the Perl application interface.

The XS compiler is called xsubpp. This compiler will embedthe constructs necessary to let an XSUB, which is really a Cfunction in disguise, manipulate Perl values and creates theglue necessary to let Perl access the XSUB. The compileruses typemaps to determine how to map C function parametersand variables to Perl values. The default typemap handlesmany common C types. A supplement typemap must be createdto handle special structures and types for the library beinglinked.

See the perlxstut manpage for a tutorial on the whole extension creation process. 

On The Road

Many of the examples which follow will concentrate on creating an interfacebetween Perl and the ONC+ RPC bind library functions. The rpcb_gettime()function is used to demonstrate many features of the XS language. Thisfunction has two parameters; the first is an input parameter and the secondis an output parameter. The function also returns a status value.

        bool_t rpcb_gettime(const char *host, time_t *timep);
From C this function will be called with the followingstatements.

     #include <rpc/rpc.h>     bool_t status;     time_t timep;     status = rpcb_gettime( "localhost", &timep );
If an XSUB is created to offer a direct translation between this functionand Perl, then this XSUB will be used from Perl with the following code.The $status and $timep variables will contain the output of the function.

     use RPC;     $status = rpcb_gettime( "localhost", $timep );
The following XS file shows an XS subroutine, or XSUB, whichdemonstrates one possible interface to the rpcb_gettime()function. This XSUB represents a direct translation betweenC and Perl and so preserves the interface even from Perl.This XSUB will be invoked from Perl with the usage shownabove. Note that the first three #include statements, forEXTERN.h, perl.h, and XSUB.h, will always be present at thebeginning of an XS file. This approach and others will beexpanded later in this document.

     #include "EXTERN.h"     #include "perl.h"     #include "XSUB.h"     #include <rpc/rpc.h>
     MODULE = RPC  PACKAGE = RPC
     bool_t     rpcb_gettime(host,timep)          char *host          time_t &timep          OUTPUT:          timep
Any extension to Perl, including those containing XSUBs,should have a Perl module to serve as the bootstrap whichpulls the extension into Perl. This module will export theextension's functions and variables to the Perl program andwill cause the extension's XSUBs to be linked into Perl.The following module will be used for most of the examplesin this document and should be used from Perl with the usecommand as shown earlier. Perl modules are explained inmore detail later in this document.

     package RPC;
     require Exporter;     require DynaLoader;     @ISA = qw(Exporter DynaLoader);     @EXPORT = qw( rpcb_gettime );
     bootstrap RPC;     1;
Throughout this document a variety of interfaces to the rpcb_gettime()XSUB will be explored. The XSUBs will take their parameters in differentorders or will take different numbers of parameters. In each case theXSUB is an abstraction between Perl and the real C rpcb_gettime()function, and the XSUB must always ensure that the real rpcb_gettime()function is called with the correct parameters. This abstraction willallow the programmer to create a more Perl-like interface to the Cfunction. 

The Anatomy of an XSUB

The following XSUB allows a Perl program to access a C library functioncalled sin(). The XSUB will imitate the C function which takes a singleargument and returns a single value.

     double     sin(x)       double x
When using C pointers the indirection operator * should be consideredpart of the type and the address operator & should be considered part ofthe variable, as is demonstrated in the rpcb_gettime() function above. Seethe section on typemaps for more about handling qualifiers and unaryoperators in C types.

The function name and the return type must be placed onseparate lines.

  INCORRECT                        CORRECT
  double sin(x)                    double    double x                       sin(x)                                     double x
The function body may be indented or left-adjusted. The following exampleshows a function with its body left-adjusted. Most examples in thisdocument will indent the body.

  CORRECT
  double  sin(x)  double x
 

The Argument Stack

The argument stack is used to store the values which aresent as parameters to the XSUB and to store the XSUB'sreturn value. In reality all Perl functions keep theirvalues on this stack at the same time, each limited to itsown range of positions on the stack. In this document thefirst position on that stack which belongs to the activefunction will be referred to as position 0 for that function.

XSUBs refer to their stack arguments with the macro ST(x), where xrefers to a position in this XSUB's part of the stack. Position 0 for thatfunction would be known to the XSUB as ST(0). The XSUB's incomingparameters and outgoing return values always begin at ST(0). For manysimple cases the xsubpp compiler will generate the code necessary tohandle the argument stack by embedding code fragments found in thetypemaps. In more complex cases the programmer must supply the code. 

The RETVAL Variable

The RETVAL variable is a magic variable which always matchesthe return type of the C library function. The xsubpp compiler willsupply this variable in each XSUB and by default will use it to hold thereturn value of the C library function being called. In simple cases thevalue of RETVAL will be placed in ST(0) of the argument stack where it canbe received by Perl as the return value of the XSUB.

If the XSUB has a return type of void then the compiler willnot supply a RETVAL variable for that function. When usingthe PPCODE: directive the RETVAL variable is not needed, unless usedexplicitly.

If PPCODE: directive is not used, void return value should be usedonly for subroutines which do not return a value, even if CODE:directive is used which sets ST(0) explicitly.

Older versions of this document recommended to use void returnvalue in such cases. It was discovered that this could lead tosegfaults in cases when XSUB was truely void. This practice isnow deprecated, and may be not supported at some future version. Usethe return value SV * in such cases. (Currently xsubpp containssome heuristic code which tries to disambiguate between ``truely-void''and ``old-practice-declared-as-void'' functions. Hence your code is atmercy of this heuristics unless you use SV * as return value.) 

The MODULE Keyword

The MODULE keyword is used to start the XS code and tospecify the package of the functions which are beingdefined. All text preceding the first MODULE keyword isconsidered C code and is passed through to the outputuntouched. Every XS module will have a bootstrap functionwhich is used to hook the XSUBs into Perl. The package nameof this bootstrap function will match the value of the lastMODULE statement in the XS source files. The value ofMODULE should always remain constant within the same XSfile, though this is not required.

The following example will start the XS code and will placeall functions in a package named RPC.

     MODULE = RPC
 

The PACKAGE Keyword

When functions within an XS source file must be separated into packagesthe PACKAGE keyword should be used. This keyword is used with the MODULEkeyword and must follow immediately after it when used.

     MODULE = RPC  PACKAGE = RPC
     [ XS code in package RPC ]
     MODULE = RPC  PACKAGE = RPCB
     [ XS code in package RPCB ]
     MODULE = RPC  PACKAGE = RPC
     [ XS code in package RPC ]
Although this keyword is optional and in some cases provides redundantinformation it should always be used. This keyword will ensure that theXSUBs appear in the desired package. 

The PREFIX Keyword

The PREFIX keyword designates prefixes which should beremoved from the Perl function names. If the C function isrpcb_gettime() and the PREFIX value is rpcb_ then Perl willsee this function as gettime().

This keyword should follow the PACKAGE keyword when used.If PACKAGE is not used then PREFIX should follow the MODULEkeyword.

     MODULE = RPC  PREFIX = rpc_
     MODULE = RPC  PACKAGE = RPCB  PREFIX = rpcb_
 

The OUTPUT: Keyword

The OUTPUT: keyword indicates that certain function parameters should beupdated (new values made visible to Perl) when the XSUB terminates or thatcertain values should be returned to the calling Perl function. Forsimple functions, such as the sin() function above, the RETVAL variable isautomatically designated as an output value. In more complex functionsthe xsubpp compiler will need help to determine which variables are outputvariables.

This keyword will normally be used to complement the CODE: keyword.The RETVAL variable is not recognized as an output variable when theCODE: keyword is present. The OUTPUT: keyword is used in thissituation to tell the compiler that RETVAL really is an outputvariable.

The OUTPUT: keyword can also be used to indicate that function parametersare output variables. This may be necessary when a parameter has beenmodified within the function and the programmer would like the update tobe seen by Perl.

     bool_t     rpcb_gettime(host,timep)          char *host          time_t &timep          OUTPUT:          timep
The OUTPUT: keyword will also allow an output parameter tobe mapped to a matching piece of code rather than to atypemap.

     bool_t     rpcb_gettime(host,timep)          char *host          time_t &timep          OUTPUT:          timep sv_setnv(ST(1), (double)timep);
 

The CODE: Keyword

This keyword is used in more complicated XSUBs which requirespecial handling for the C function. The RETVAL variable isavailable but will not be returned unless it is specifiedunder the OUTPUT: keyword.

The following XSUB is for a C function which requires special handling ofits parameters. The Perl usage is given first.

     $status = rpcb_gettime( "localhost", $timep );
The XSUB follows.

     bool_t     rpcb_gettime(host,timep)          char *host          time_t timep          CODE:               RETVAL = rpcb_gettime( host, &timep );          OUTPUT:          timep          RETVAL
 

The INIT: Keyword

The INIT: keyword allows initialization to be inserted into the XSUB beforethe compiler generates the call to the C function. Unlike the CODE: keywordabove, this keyword does not affect the way the compiler handles RETVAL.

    bool_t    rpcb_gettime(host,timep)          char *host          time_t &timep          INIT:          printf("# Host is %s\n", host );          OUTPUT:          timep
 

The NO_INIT Keyword

The NO_INIT keyword is used to indicate that a functionparameter is being used only as an output value. The xsubppcompiler will normally generate code to read the values ofall function parameters from the argument stack and assignthem to C variables upon entry to the function. NO_INITwill tell the compiler that some parameters will be used foroutput rather than for input and that they will be handledbefore the function terminates.

The following example shows a variation of the rpcb_gettime() function.This function uses the timep variable only as an output variable and doesnot care about its initial contents.

     bool_t     rpcb_gettime(host,timep)          char *host          time_t &timep = NO_INIT          OUTPUT:          timep
 

Initializing Function Parameters

Function parameters are normally initialized with theirvalues from the argument stack. The typemaps contain thecode segments which are used to transfer the Perl values tothe C parameters. The programmer, however, is allowed tooverride the typemaps and supply alternate initializationcode.

The following code demonstrates how to supply initialization code forfunction parameters. The initialization code is eval'd by the compilerbefore it is added to the output so anything which should be interpretedliterally, such as double quotes, must be protected with backslashes.

     bool_t     rpcb_gettime(host,timep)          char *host = (char *)SvPV(ST(0),na);          time_t &timep = 0;          OUTPUT:          timep
This should not be used to supply default values for parameters. Onewould normally use this when a function parameter must be processed byanother library function before it can be used. Default parameters arecovered in the next section. 

Default Parameter Values

Default values can be specified for function parameters byplacing an assignment statement in the parameter list. Thedefault value may be a number or a string. Defaults shouldalways be used on the right-most parameters only.

To allow the XSUB for rpcb_gettime() to have a default hostvalue the parameters to the XSUB could be rearranged. TheXSUB will then call the real rpcb_gettime() function withthe parameters in the correct order. Perl will call thisXSUB with either of the following statements.

     $status = rpcb_gettime( $timep, $host );
     $status = rpcb_gettime( $timep );
The XSUB will look like the code which follows. A CODE:block is used to call the real rpcb_gettime() function withthe parameters in the correct order for that function.

     bool_t     rpcb_gettime(timep,host="localhost")          char *host          time_t timep = NO_INIT          CODE:               RETVAL = rpcb_gettime( host, &timep );          OUTPUT:          timep          RETVAL
 

The PREINIT: Keyword

The PREINIT: keyword allows extra variables to be declared before thetypemaps are expanded. If a variable is declared in a CODE: block then thatvariable will follow any typemap code. This may result in a C syntaxerror. To force the variable to be declared before the typemap code, placeit into a PREINIT: block. The PREINIT: keyword may be used one or moretimes within an XSUB.

The following examples are equivalent, but if the code is using complextypemaps then the first example is safer.

     bool_t     rpcb_gettime(timep)          time_t timep = NO_INIT          PREINIT:          char *host = "localhost";          CODE:          RETVAL = rpcb_gettime( host, &timep );          OUTPUT:          timep          RETVAL
A correct, but error-prone example.

     bool_t     rpcb_gettime(timep)          time_t timep = NO_INIT          CODE:          char *host = "localhost";          RETVAL = rpcb_gettime( host, &timep );          OUTPUT:          timep          RETVAL
 

The SCOPE: Keyword

The SCOPE: keyword allows scoping to be enabled for a particular XSUB. Ifenabled, the XSUB will invoke ENTER and LEAVE automatically.

To support potentially complex type mappings, if a typemap entry usedby this XSUB contains a comment like /*scope*/ then scoping willautomatically be enabled for that XSUB.

To enable scoping:

    SCOPE: ENABLE
To disable scoping:

    SCOPE: DISABLE
 

The INPUT: Keyword

The XSUB's parameters are usually evaluated immediately after entering theXSUB. The INPUT: keyword can be used to force those parameters to beevaluated a little later. The INPUT: keyword can be used multiple timeswithin an XSUB and can be used to list one or more input variables. Thiskeyword is used with the PREINIT: keyword.

The following example shows how the input parameter timep can beevaluated late, after a PREINIT.

    bool_t    rpcb_gettime(host,timep)          char *host          PREINIT:          time_t tt;          INPUT:          time_t timep          CODE:               RETVAL = rpcb_gettime( host, &tt );               timep = tt;          OUTPUT:          timep          RETVAL
The next example shows each input parameter evaluated late.

    bool_t    rpcb_gettime(host,timep)          PREINIT:          time_t tt;          INPUT:          char *host          PREINIT:          char *h;          INPUT:          time_t timep          CODE:               h = host;               RETVAL = rpcb_gettime( h, &tt );               timep = tt;          OUTPUT:          timep          RETVAL
 

Variable-length Parameter Lists

XSUBs can have variable-length parameter lists by specifying an ellipsis(...) in the parameter list. This use of the ellipsis is similar to thatfound in ANSI C. The programmer is able to determine the number ofarguments passed to the XSUB by examining the items variable which thexsubpp compiler supplies for all XSUBs. By using this mechanism one cancreate an XSUB which accepts a list of parameters of unknown length.

The host parameter for the rpcb_gettime() XSUB can beoptional so the ellipsis can be used to indicate that theXSUB will take a variable number of parameters. Perl shouldbe able to call this XSUB with either of the following statements.

     $status = rpcb_gettime( $timep, $host );
     $status = rpcb_gettime( $timep );
The XS code, with ellipsis, follows.

     bool_t     rpcb_gettime(timep, ...)          time_t timep = NO_INIT          PREINIT:          char *host = "localhost";          CODE:                  if( items > 1 )                       host = (char *)SvPV(ST(1), na);                  RETVAL = rpcb_gettime( host, &timep );          OUTPUT:          timep          RETVAL
 

The PPCODE: Keyword

The PPCODE: keyword is an alternate form of the CODE: keyword and is usedto tell the xsubpp compiler that the programmer is supplying the code tocontrol the argument stack for the XSUBs return values. Occasionally onewill want an XSUB to return a list of values rather than a single value.In these cases one must use PPCODE: and then explicitly push the list ofvalues on the stack. The PPCODE: and CODE: keywords are not usedtogether within the same XSUB.

The following XSUB will call the C rpcb_gettime() functionand will return its two output values, timep and status, toPerl as a single list.

     void     rpcb_gettime(host)          char *host          PREINIT:          time_t  timep;          bool_t  status;          PPCODE:          status = rpcb_gettime( host, &timep );          EXTEND(sp, 2);          PUSHs(sv_2mortal(newSViv(status)));          PUSHs(sv_2mortal(newSViv(timep)));
Notice that the programmer must supply the C code necessaryto have the real rpcb_gettime() function called and to havethe return values properly placed on the argument stack.

The void return type for this function tells the xsubpp compiler thatthe RETVAL variable is not needed or used and that it should not be created.In most scenarios the void return type should be used with the PPCODE:directive.

The EXTEND() macro is used to make room on the argumentstack for 2 return values. The PPCODE: directive causes thexsubpp compiler to create a stack pointer called sp, and itis this pointer which is being used in the EXTEND() macro.The values are then pushed onto the stack with the PUSHs()macro.

Now the rpcb_gettime() function can be used from Perl withthe following statement.

     ($status, $timep) = rpcb_gettime("localhost");
 

Returning Undef And Empty Lists

Occasionally the programmer will want to return simplyundef or an empty list if a function fails rather than aseparate status value. The rpcb_gettime() function offersjust this situation. If the function succeeds we would liketo have it return the time and if it fails we would like tohave undef returned. In the following Perl code the valueof $timep will either be undef or it will be a valid time.

     $timep = rpcb_gettime( "localhost" );
The following XSUB uses the SV * return type as a mneumonic only,and uses a CODE: block to indicate to the compilerthat the programmer has supplied all the necessary code. Thesv_newmortal() call will initialize the return value to undef, making thatthe default return value.

     SV *     rpcb_gettime(host)          char *  host          PREINIT:          time_t  timep;          bool_t x;          CODE:          ST(0) = sv_newmortal();          if( rpcb_gettime( host, &timep ) )               sv_setnv( ST(0), (double)timep);
The next example demonstrates how one would place an explicit undef in thereturn value, should the need arise.

     SV *     rpcb_gettime(host)          char *  host          PREINIT:          time_t  timep;          bool_t x;          CODE:          ST(0) = sv_newmortal();          if( rpcb_gettime( host, &timep ) ){               sv_setnv( ST(0), (double)timep);          }          else{               ST(0) = &sv_undef;          }
To return an empty list one must use a PPCODE: block andthen not push return values on the stack.

     void     rpcb_gettime(host)          char *host          PREINIT:          time_t  timep;          PPCODE:          if( rpcb_gettime( host, &timep ) )               PUSHs(sv_2mortal(newSViv(timep)));          else{          /* Nothing pushed on stack, so an empty */          /* list is implicitly returned. */          }
Some people may be inclined to include an explicit return in the aboveXSUB, rather than letting control fall through to the end. In thosesituations XSRETURN_EMPTY should be used, instead. This will ensure thatthe XSUB stack is properly adjusted. Consult the section on API LISTING in the perlguts manpage forother XSRETURN macros. 

The REQUIRE: Keyword

The REQUIRE: keyword is used to indicate the minimum version of thexsubpp compiler needed to compile the XS module. An XS module whichcontains the following statement will compile with only xsubpp version1.922 or greater:

        REQUIRE: 1.922
 

The CLEANUP: Keyword

This keyword can be used when an XSUB requires special cleanup proceduresbefore it terminates. When the CLEANUP: keyword is used it must followany CODE:, PPCODE:, or OUTPUT: blocks which are present in the XSUB. Thecode specified for the cleanup block will be added as the last statementsin the XSUB. 

The BOOT: Keyword

The BOOT: keyword is used to add code to the extension's bootstrapfunction. The bootstrap function is generated by the xsubpp compiler andnormally holds the statements necessary to register any XSUBs with Perl.With the BOOT: keyword the programmer can tell the compiler to add extrastatements to the bootstrap function.

This keyword may be used any time after the first MODULE keyword and shouldappear on a line by itself. The first blank line after the keyword willterminate the code block.

     BOOT:     # The following message will be printed when the     # bootstrap function executes.     printf("Hello from the bootstrap!\n");
 

The VERSIONCHECK: Keyword

The VERSIONCHECK: keyword corresponds to xsubpp's -versioncheck and-noversioncheck options. This keyword overrides the command lineoptions. Version checking is enabled by default. When version checking isenabled the XS module will attempt to verify that its version matches theversion of the PM module.

To enable version checking:

    VERSIONCHECK: ENABLE
To disable version checking:

    VERSIONCHECK: DISABLE
 

The PROTOTYPES: Keyword

The PROTOTYPES: keyword corresponds to xsubpp's -prototypes and-noprototypes options. This keyword overrides the command line options.Prototypes are enabled by default. When prototypes are enabled XSUBs willbe given Perl prototypes. This keyword may be used multiple times in an XSmodule to enable and disable prototypes for different parts of the module.

To enable prototypes:

    PROTOTYPES: ENABLE
To disable prototypes:

    PROTOTYPES: DISABLE
 

The PROTOTYPE: Keyword

This keyword is similar to the PROTOTYPES: keyword above but can be used toforce xsubpp to use a specific prototype for the XSUB. This keywordoverrides all other prototype options and keywords but affects only thecurrent XSUB. Consult the Prototypes entry in the perlsub manpage for information about Perlprototypes.

    bool_t    rpcb_gettime(timep, ...)          time_t timep = NO_INIT          PROTOTYPE: $;$          PREINIT:          char *host = "localhost";          CODE:                  if( items > 1 )                       host = (char *)SvPV(ST(1), na);                  RETVAL = rpcb_gettime( host, &timep );          OUTPUT:          timep          RETVAL
 

The ALIAS: Keyword

The ALIAS: keyword allows an XSUB to have two more unique Perl namesand to know which of those names was used when it was invoked. The Perlnames may be fully-qualified with package names. Each alias is given anindex. The compiler will setup a variable called ix which contain theindex of the alias which was used. When the XSUB is called with itsdeclared name ix will be 0.

The following example will create aliases FOO::gettime() andBAR::getit() for this function.

    bool_t    rpcb_gettime(host,timep)          char *host          time_t &timep          ALIAS:            FOO::gettime = 1            BAR::getit = 2          INIT:          printf("# ix = %d\n", ix );          OUTPUT:          timep
 

The INCLUDE: Keyword

This keyword can be used to pull other files into the XS module. The otherfiles may have XS code. INCLUDE: can also be used to run a command togenerate the XS code to be pulled into the module.

The file Rpcb1.xsh contains our rpcb_gettime() function:

    bool_t    rpcb_gettime(host,timep)          char *host          time_t &timep          OUTPUT:          timep
The XS module can use INCLUDE: to pull that file into it.

    INCLUDE: Rpcb1.xsh
If the parameters to the INCLUDE: keyword are followed by a pipe (|) thenthe compiler will interpret the parameters as a command.

    INCLUDE: cat Rpcb1.xsh |
 

The CASE: Keyword

The CASE: keyword allows an XSUB to have multiple distinct parts with eachpart acting as a virtual XSUB. CASE: is greedy and if it is used then allother XS keywords must be contained within a CASE:. This means nothing mayprecede the first CASE: in the XSUB and anything following the last CASE: isincluded in that case.

A CASE: might switch via a parameter of the XSUB, via the ix ALIAS:variable (see the section on The ALIAS: Keyword), or maybe via the items variable(see the section on Variable-length Parameter Lists). The last CASE: becomes thedefault case if it is not associated with a conditional. The followingexample shows CASE switched via ix with a function rpcb_gettime()having an alias x_gettime(). When the function is called asrpcb_gettime() its parameters are the usual (char *host, time_t *timep),but when the function is called as x_gettime() its parameters arereversed, (time_t *timep, char *host).

    long    rpcb_gettime(a,b)      CASE: ix == 1          ALIAS:          x_gettime = 1          INPUT:          # 'a' is timep, 'b' is host          char *b          time_t a = NO_INIT          CODE:               RETVAL = rpcb_gettime( b, &a );          OUTPUT:          a          RETVAL      CASE:          # 'a' is host, 'b' is timep          char *a          time_t &b = NO_INIT          OUTPUT:          b          RETVAL
That function can be called with either of the following statements. Notethe different argument lists.

        $status = rpcb_gettime( $host, $timep );
        $status = x_gettime( $timep, $host );
 

The & Unary Operator

The & unary operator is used to tell the compiler that it should dereferencethe object when it calls the C function. This is used when a CODE: block isnot used and the object is a not a pointer type (the object is an int orlong but not a int* or long*).

The following XSUB will generate incorrect C code. The xsubpp compiler willturn this into code which calls rpcb_gettime() with parameters (char*host, time_t timep), but the real rpcb_gettime() wants the timepparameter to be of type time_t* rather than time_t.

    bool_t    rpcb_gettime(host,timep)          char *host          time_t timep          OUTPUT:          timep
That problem is corrected by using the & operator. The xsubpp compilerwill now turn this into code which calls rpcb_gettime() correctly withparameters (char *host, time_t *timep). It does this by carrying the& through, so the function call looks like rpcb_gettime(host, &timep).

    bool_t    rpcb_gettime(host,timep)          char *host          time_t &timep          OUTPUT:          timep
 

Inserting Comments and C Preprocessor Directives

C preprocessor directives are allowed within BOOT:, PREINIT: INIT:,CODE:, PPCODE:, and CLEANUP: blocks, as well as outside the functions.Comments are allowed anywhere after the MODULE keyword. The compilerwill pass the preprocessor directives through untouched and will removethe commented lines.

Comments can be added to XSUBs by placing a # as the firstnon-whitespace of a line. Care should be taken to avoid making thecomment look like a C preprocessor directive, lest it be interpreted assuch. The simplest way to prevent this is to put whitespace in front ofthe #.

If you use preprocessor directives to choose one of twoversions of a function, use

    #if ... version1    #else /* ... version2  */    #endif
and not

    #if ... version1    #endif    #if ... version2    #endif
because otherwise xsubpp will believe that you made a duplicatedefinition of the function. Also, put a blank line before the#else/#endif so it will not be seen as part of the function body. 

Using XS With C++

If a function is defined as a C++ method then it will assumeits first argument is an object pointer. The object pointerwill be stored in a variable called THIS. The object shouldhave been created by C++ with the new() function and shouldbe blessed by Perl with the sv_setref_pv() macro. Theblessing of the object by Perl can be handled by a typemap. An exampletypemap is shown at the end of this section.

If the method is defined as static it will call the C++function using the class::method() syntax. If the method is not staticthe function will be called using the THIS->method() syntax.

The next examples will use the following C++ class.

     class color {          public:          color();          ~color();          int blue();          void set_blue( int );
          private:          int c_blue;     };
The XSUBs for the blue() and set_blue() methods are defined with the classname but the parameter for the object (THIS, or ``self") is implicit and isnot listed.

     int     color::blue()
     void     color::set_blue( val )          int val
Both functions will expect an object as the first parameter. The xsubppcompiler will call that object THIS and will use it to call the specifiedmethod. So in the C++ code the blue() and set_blue() methods will be calledin the following manner.

     RETVAL = THIS->blue();
     THIS->set_blue( val );
If the function's name is DESTROY then the C++ delete function will becalled and THIS will be given as its parameter.

     void     color::DESTROY()
The C++ code will call delete.

     delete THIS;
If the function's name is new then the C++ new function will be calledto create a dynamic C++ object. The XSUB will expect the class name, whichwill be kept in a variable called CLASS, to be given as the firstargument.

     color *     color::new()
The C++ code will call new.

        RETVAL = new color();
The following is an example of a typemap that could be used for this C++example.

    TYPEMAP    color *             O_OBJECT
    OUTPUT    # The Perl object is blessed into 'CLASS', which should be a    # char* having the name of the package for the blessing.    O_OBJECT        sv_setref_pv( $arg, CLASS, (void*)$var );
    INPUT    O_OBJECT        if( sv_isobject($arg) && (SvTYPE(SvRV($arg)) == SVt_PVMG) )                $var = ($type)SvIV((SV*)SvRV( $arg ));        else{                warn( \"${Package}::$func_name() -- $var is not a blessed SV reference\" );                XSRETURN_UNDEF;        }
 

Interface Strategy

When designing an interface between Perl and a C library a straighttranslation from C to XS is often sufficient. The interface will often bevery C-like and occasionally nonintuitive, especially when the C functionmodifies one of its parameters. In cases where the programmer wishes tocreate a more Perl-like interface the following strategy may help toidentify the more critical parts of the interface.

Identify the C functions which modify their parameters. The XSUBs forthese functions may be able to return lists to Perl, or may becandidates to return undef or an empty list in case of failure.

Identify which values are used by only the C and XSUB functionsthemselves. If Perl does not need to access the contents of the valuethen it may not be necessary to provide a translation for that valuefrom C to Perl.

Identify the pointers in the C function parameter lists and returnvalues. Some pointers can be handled in XS with the & unary operator onthe variable name while others will require the use of the * operator onthe type name. In general it is easier to work with the & operator.

Identify the structures used by the C functions. In manycases it may be helpful to use the T_PTROBJ typemap forthese structures so they can be manipulated by Perl asblessed objects. 

Perl Objects And C Structures

When dealing with C structures one should select eitherT_PTROBJ or T_PTRREF for the XS type. Both types aredesigned to handle pointers to complex objects. TheT_PTRREF type will allow the Perl object to be unblessedwhile the T_PTROBJ type requires that the object be blessed.By using T_PTROBJ one can achieve a form of type-checkingbecause the XSUB will attempt to verify that the Perl objectis of the expected type.

The following XS code shows the getnetconfigent() function which is usedwith ONC+ TIRPC. The getnetconfigent() function will return a pointer to aC structure and has the C prototype shown below. The example willdemonstrate how the C pointer will become a Perl reference. Perl willconsider this reference to be a pointer to a blessed object and willattempt to call a destructor for the object. A destructor will beprovided in the XS source to free the memory used by getnetconfigent().Destructors in XS can be created by specifying an XSUB function whose nameends with the word DESTROY. XS destructors can be used to free memorywhich may have been malloc'd by another XSUB.

     struct netconfig *getnetconfigent(const char *netid);
A typedef will be created for struct netconfig. The Perlobject will be blessed in a class matching the name of the Ctype, with the tag Ptr appended, and the name should nothave embedded spaces if it will be a Perl package name. Thedestructor will be placed in a class corresponding to theclass of the object and the PREFIX keyword will be used totrim the name to the word DESTROY as Perl will expect.

     typedef struct netconfig Netconfig;
     MODULE = RPC  PACKAGE = RPC
     Netconfig *     getnetconfigent(netid)          char *netid
     MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_
     void     rpcb_DESTROY(netconf)          Netconfig *netconf          CODE:          printf("Now in NetconfigPtr::DESTROY\n");          free( netconf );
This example requires the following typemap entry. Consult the typemapsection for more information about adding new typemaps for an extension.

     TYPEMAP     Netconfig *  T_PTROBJ
This example will be used with the following Perl statements.

     use RPC;     $netconf = getnetconfigent("udp");
When Perl destroys the object referenced by $netconf it will send theobject to the supplied XSUB DESTROY function. Perl cannot determine, anddoes not care, that this object is a C struct and not a Perl object. Inthis sense, there is no difference between the object created by thegetnetconfigent() XSUB and an object created by a normal Perl subroutine. 

The Typemap

The typemap is a collection of code fragments which are used by the xsubppcompiler to map C function parameters and values to Perl values. Thetypemap file may consist of three sections labeled TYPEMAP, INPUT, andOUTPUT. The INPUT section tells the compiler how to translate Perl valuesinto variables of certain C types. The OUTPUT section tells the compilerhow to translate the values from certain C types into values Perl canunderstand. The TYPEMAP section tells the compiler which of the INPUT andOUTPUT code fragments should be used to map a given C type to a Perl value.Each of the sections of the typemap must be preceded by one of the TYPEMAP,INPUT, or OUTPUT keywords.

The default typemap in the ext directory of the Perl source contains manyuseful types which can be used by Perl extensions. Some extensions defineadditional typemaps which they keep in their own directory. Theseadditional typemaps may reference INPUT and OUTPUT maps in the maintypemap. The xsubpp compiler will allow the extension's own typemap tooverride any mappings which are in the default typemap.

Most extensions which require a custom typemap will need only the TYPEMAPsection of the typemap file. The custom typemap used in thegetnetconfigent() example shown earlier demonstrates what may be the typicaluse of extension typemaps. That typemap is used to equate a C structurewith the T_PTROBJ typemap. The typemap used by getnetconfigent() is shownhere. Note that the C type is separated from the XS type with a tab andthat the C unary operator * is considered to be a part of the C type name.

     TYPEMAP     Netconfig *<tab>T_PTROBJ
Here's a more complicated example: suppose that you wanted structnetconfig to be blessed into the class Net::Config. One way to dothis is to use underscores (_) to separate package names, as follows:

        typedef struct netconfig * Net_Config;
And then provide a typemap entry T_PTROBJ_SPECIAL that maps underscores todouble-colons (::), and declare Net_Config to be of that type:

        TYPEMAP        Net_Config      T_PTROBJ_SPECIAL
        INPUT        T_PTROBJ_SPECIAL                if (sv_derived_from($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")) {                        IV tmp = SvIV((SV*)SvRV($arg));                $var = ($type) tmp;                }                else                        croak(\"$var is not of type ${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")
        OUTPUT        T_PTROBJ_SPECIAL                sv_setref_pv($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\",                (void*)$var);
The INPUT and OUTPUT sections substitute underscores for double-colonson the fly, giving the desired effect. This example demonstrates someof the power and versatility of the typemap facility. 

EXAMPLES

File RPC.xs: Interface to some ONC+ RPC bind library functions.

     #include "EXTERN.h"     #include "perl.h"     #include "XSUB.h"
     #include <rpc/rpc.h>
     typedef struct netconfig Netconfig;
     MODULE = RPC  PACKAGE = RPC
     SV *     rpcb_gettime(host="localhost")          char *host          PREINIT:          time_t  timep;          CODE:          ST(0) = sv_newmortal();          if( rpcb_gettime( host, &timep ) )               sv_setnv( ST(0), (double)timep );
     Netconfig *     getnetconfigent(netid="udp")          char *netid
     MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_
     void     rpcb_DESTROY(netconf)          Netconfig *netconf          CODE:          printf("NetconfigPtr::DESTROY\n");          free( netconf );
File typemap: Custom typemap for RPC.xs.

     TYPEMAP     Netconfig *  T_PTROBJ
File RPC.pm: Perl module for the RPC extension.

     package RPC;
     require Exporter;     require DynaLoader;     @ISA = qw(Exporter DynaLoader);     @EXPORT = qw(rpcb_gettime getnetconfigent);
     bootstrap RPC;     1;
File rpctest.pl: Perl test program for the RPC extension.

     use RPC;
     $netconf = getnetconfigent();     $a = rpcb_gettime();     print "time = $a\n";     print "netconf = $netconf\n";
     $netconf = getnetconfigent("tcp");     $a = rpcb_gettime("poplar");     print "time = $a\n";     print "netconf = $netconf\n";
 

XS VERSION

This document covers features supported by xsubpp 1.935. 

AUTHOR

Dean Roehrich <roehrichAATTcray.com>Jul 8, 1996


 

Index

NAME
DESCRIPTION
Introduction
On The Road
The Anatomy of an XSUB
The Argument Stack
The RETVAL Variable
The MODULE Keyword
The PACKAGE Keyword
The PREFIX Keyword
The OUTPUT: Keyword
The CODE: Keyword
The INIT: Keyword
The NO_INIT Keyword
Initializing Function Parameters
Default Parameter Values
The PREINIT: Keyword
The SCOPE: Keyword
The INPUT: Keyword
Variable-length Parameter Lists
The PPCODE: Keyword
Returning Undef And Empty Lists
The REQUIRE: Keyword
The CLEANUP: Keyword
The BOOT: Keyword
The VERSIONCHECK: Keyword
The PROTOTYPES: Keyword
The PROTOTYPE: Keyword
The ALIAS: Keyword
The INCLUDE: Keyword
The CASE: Keyword
The & Unary Operator
Inserting Comments and C Preprocessor Directives
Using XS With C++
Interface Strategy
Perl Objects And C Structures
The Typemap
EXAMPLES
XS VERSION
AUTHOR

This document was created byman2html,using the manual pages.
 
ICM Bot detect detector