MAN page from CentOS 7 rh-perl526-perl-devel-5.26.3-405.el7.x86_64.rpm
PERLXS
Section: Perl Programmers Reference Guide (1)
Updated: 2018-03-01
Index NAME
perlxs - XS language reference manual
DESCRIPTION
Introduction
XS is an interface description file format used to create an extensioninterface between Perl and C code (or a C library) which one wishesto use with Perl. The
XS interface is combined with the library tocreate a new library which can then be either dynamically loadedor statically linked into perl. The
XS interface description iswritten in the
XS language and is the core component of the Perlextension interface.
Before writing XS, read the ``CAVEATS'' section below.
An XSUB forms the basic unit of the XS interface. After compilationby the xsubpp compiler, each XSUB amounts to a C function definitionwhich will provide the glue between Perl calling conventions and Ccalling conventions.
The glue code pulls the arguments from the Perl stack, converts thesePerl values to the formats expected by a C function, call this C function,transfers the return values of the C function back to Perl.Return values here may be a conventional C return value or any Cfunction arguments that may serve as output parameters. These returnvalues may be passed back to Perl either by putting them on thePerl stack, or by modifying the arguments supplied from the Perl side.
The above is a somewhat simplified view of what really happens. SincePerl allows more flexible calling conventions than C, XSUBs may do muchmore in practice, such as checking input parameters for validity,throwing exceptions (or returning undef/empty list) if the return valuefrom the C function indicates failure, calling different C functionsbased on numbers and types of the arguments, providing an object-orientedinterface, etc.
Of course, one could write such glue code directly in C. However, thiswould be a tedious task, especially if one needs to write glue formultiple C functions, and/or one is not familiar enough with the Perlstack discipline and other such arcana. XS comes to the rescue here:instead of writing this glue C code in long-hand, one can writea more concise short-hand description of what should be done bythe glue, and let the XS compiler xsubpp handle the rest.
The XS language allows one to describe the mapping between how the Croutine is used, and how the corresponding Perl routine is used. Italso allows creation of Perl routines which are directly translated toC code and which are not related to a pre-existing C function. In caseswhen the C interface coincides with the Perl interface, the XSUBdeclaration is almost identical to a declaration of a C function (in K&Rstyle). In such circumstances, there is another tool called "h2xs"that is able to translate an entire C header file into a correspondingXS file that will provide glue to the functions/macros described inthe header file.
The XS compiler is called xsubpp. This compiler createsthe constructs necessary to let an XSUB manipulate Perl values, andcreates the glue necessary to let Perl call the XSUB. The compileruses typemaps to determine how to map C function parametersand output values to Perl values and back. The default typemap(which comes with Perl) handles many common C types. A supplementarytypemap may also be needed to handle any special structures and typesfor the library being linked. For more information on typemaps,see perlxstypemap.
A file in XS format starts with a C language section which goes until thefirst "MODULE =" directive. Other XS directives and XSUB definitionsmay follow this line. The ``language'' used in this part of the fileis usually referred to as the XS language. xsubpp recognizes andskips POD (see perlpod) in both the C and XS language sections, whichallows the XS file to contain embedded documentation.
See perlxstut for a tutorial on the whole extension creation process.
Note: For some extensions, Dave Beazley's SWIG system may provide asignificantly more convenient mechanism for creating the extensionglue code. See <http://www.swig.org/> for more information.
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, for"EXTERN.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. A #define for "PERL_NO_GET_CONTEXT"should be present to fetch the interpreter context more efficiently,see perlguts for details.
#define PERL_NO_GET_CONTEXT #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 "use"command 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 simplest XSUBs consist of 3 parts: a description of the returnvalue, the name of the
XSUB routine and the names of its arguments,and a description of types or formats of the arguments.
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
Optionally, one can merge the description of types and the list ofargument names, rewriting this as
double sin(double x)
This makes this XSUB look similar to an ANSI C declaration. An optionalsemicolon is allowed after the argument list, as in
double sin(double x);
Parameters with C pointer types can have different semantic: C functionswith similar declarations
bool string_looks_as_a_number(char *s); bool make_char_uppercase(char *c);
are used in absolutely incompatible manner. Parameters to these functionscould be described xsubpp like this:
char * s char &c
Both these XS declarations correspond to the "char*" C type, but they havedifferent semantics, see ``The & Unary Operator''.
It is convenient to think that the indirection operator"*" should be considered as a part of the type and the address operator "&"should be considered part of the variable. See perlxstypemapfor more info about handling qualifiers and unary operators in C types.
The function name and the return type must be placed onseparate lines and should be flush left-adjusted.
INCORRECT CORRECT double sin(x) double double x sin(x) double x
The rest of the function description may be indented or left-adjusted. Thefollowing example shows a function with its body left-adjusted. Mostexamples in this document will indent the body for better readability.
CORRECT double sin(x) double x
More complicated XSUBs may contain many other sections. Each section ofan XSUB starts with the corresponding keyword, such as INIT: or CLEANUP:.However, the first two lines of an XSUB always contain the same data:descriptions of the return type and the names of the function and itsparameters. Whatever immediately follows these is considered to bean INPUT: section unless explicitly marked with another keyword.(See ``The INPUT: Keyword''.)
An XSUB section continues until another section-start keyword is found.
The Argument Stack
The Perl argument stack is used to store the values which aresent as parameters to the
XSUB and to store the
XSUB'sreturn value(s). In reality all Perl functions (including non-XSUBones) keep their values on this stack all the same time, each limitedto its own 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 special C variable that is declared automaticallyfor you. The C type of
RETVAL matches the return type of the C libraryfunction. The
xsubpp compiler will declare this variable in each
XSUBwith non-
"void" return type. By default the generated C functionwill use
RETVAL to hold the return value of the C library function beingcalled. In simple cases the value of
RETVAL will be placed in
ST(0) ofthe argument stack where it can be received by Perl as the return valueof the
XSUB.If the XSUB has a return type of "void" then the compiler willnot declare a RETVAL variable for that function. When usinga PPCODE: section no manipulation of the RETVAL variable is required, thesection may use direct stack manipulation to place output values on the stack.
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 truly "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 ``truly-void''and ``old-practice-declared-as-void'' functions. Hence your code is atmercy of this heuristics unless you use "SV *" as return value.)
Returning SVs, AVs and HVs through RETVAL
When you're using
RETVAL to return an
"SV *", there's some magicgoing on behind the scenes that should be mentioned. When you'remanipulating the argument stack using the
ST(x) macro, for example,you usually have to pay special attention to reference counts. (Formore about reference counts, see perlguts.) To make your lifeeasier, the typemap file automatically makes
"RETVAL" mortal whenyou're returning an
"SV *". Thus, the following two XSUBs are moreor less equivalent:
void alpha() PPCODE: ST(0) = newSVpv("Hello World",0); sv_2mortal(ST(0)); XSRETURN(1); SV * beta() CODE: RETVAL = newSVpv("Hello World",0); OUTPUT: RETVAL
This is quite useful as it usually improves readability. Whilethis works fine for an "SV *", it's unfortunately not as easyto have "AV *" or "HV *" as a return value. You should beable to write:
AV * array() CODE: RETVAL = newAV(); /* do something with RETVAL */ OUTPUT: RETVAL
But due to an unfixable bug (fixing it would break lots of existingCPAN modules) in the typemap file, the reference count of the "AV *"is not properly decremented. Thus, the above XSUB would leak memorywhenever it is being called. The same problem exists for "HV *","CV *", and "SVREF" (which indicates a scalar reference, nota general "SV *").In XS code on perls starting with perl 5.16, you can override thetypemaps for any of these types with a version that has properhandling of refcounts. In your "TYPEMAP" section, do
AV* T_AVREF_REFCOUNT_FIXED
to get the repaired variant. For backward compatibility with olderversions of perl, you can instead decrement the reference countmanually when you're returning one of the aforementionedtypes using "sv_2mortal":
AV * array() CODE: RETVAL = newAV(); sv_2mortal((SV*)RETVAL); /* do something with RETVAL */ OUTPUT: RETVAL
Remember that you don't have to do this for an "SV *". The referencedocumentation for all core typemaps can be found in perlxstypemap.
The MODULE Keyword
The
MODULE keyword is used to start the
XS code and to specify the packageof the functions which are being defined. All text preceding the first
MODULE keyword is considered C code and is passed through to the output with
POD stripped, but otherwise untouched. Every
XS module will have abootstrap function which is used to hook the XSUBs into Perl. The packagename of this bootstrap function will match the value of the last
MODULEstatement in the
XS source files. The value of
MODULE should always remainconstant within the same
XS file, 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 ]
The same package name can be used more than once, allowing fornon-contiguous code. This is useful if you have a stronger orderingprinciple than package names.
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 is
"rpcb_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 which have no
CODE: or
PPCODE: section,such as the
sin() function above, the
RETVAL variable isautomatically designated as an output value. For 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);
xsubpp emits an automatic "SvSETMAGIC()" for all parameters in theOUTPUT section of the XSUB, except RETVAL. This is the usually desiredbehavior, as it takes care of properly invoking 'set' magic on outputparameters (needed for hash or array element parameters that must becreated if they didn't exist). If for some reason, this behavior isnot desired, the OUTPUT section may contain a "SETMAGIC: DISABLE" lineto disable it for the remainder of the parameters in the OUTPUT section.Likewise, "SETMAGIC: ENABLE" can be used to reenable it for theremainder of the OUTPUT section. See perlguts for more detailsabout 'set' magic.
The NO_OUTPUT Keyword
The
NO_OUTPUT can be placed as the first token of the
XSUB. This keywordindicates that while the C subroutine we provide an interface to hasa non-
"void" return type, the return value of this C subroutine should notbe returned from the generated Perl subroutine.
With this keyword present ``The RETVAL Variable'' is created, and in thegenerated call to the subroutine this variable is assigned to, but the valueof this variable is not going to be used in the auto-generated code.
This keyword makes sense only if "RETVAL" is going to be accessed by theuser-supplied code. It is especially useful to make a function interfacemore Perl-like, especially when the C return value is just an error conditionindicator. For example,
NO_OUTPUT int delete_file(char *name) POSTCALL: if (RETVAL != 0) croak("Error %d while deleting file '%s'", RETVAL, name);
Here the generated XS function returns nothing on success, and will die()with a meaningful error message on error.
The CODE: Keyword
This keyword is used in more complicated XSUBs which requirespecial handling for the C function. The
RETVAL variable isstill declared, but it will not be returned unless it is specifiedin the
OUTPUT: section.
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
Another use for the INIT: section is to check for preconditions beforemaking a call to the C function:
long long lldiv(a,b) long long a long long b INIT: if (a == 0 && b == 0) XSRETURN_UNDEF; if (b == 0) croak("lldiv: cannot divide by 0");
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
The TYPEMAP: Keyword
Starting with Perl 5.16, you can embed typemaps into your
XS codeinstead of or in addition to typemaps in a separate file. Multiplesuch embedded typemaps will be processed in order of appearance inthe
XS code and like local typemap files take precedence over thedefault typemap, the embedded typemaps may overwrite previousdefinitions of
TYPEMAP, INPUT, and
OUTPUT stanzas. The syntax forembedded typemaps is
TYPEMAP: <<HERE ... your typemap code here ... HERE
where the "TYPEMAP" keyword must appear in the first column of anew line.
Refer to perlxstypemap for details on writing typemaps.
Initializing Function Parameters
C function parameters are normally initialized with their values fromthe argument stack (which in turn contains the parameters that werepassed to the
XSUB from Perl). The typemaps contain thecode segments which are used to translate the Perl values tothe C parameters. The programmer, however, is allowed tooverride the typemaps and supply alternate (or additional)initialization code. Initialization code starts with the first
"=",
";" or
"+" on a line in the
INPUT: section. The onlyexception happens if this
";" terminates the line, then this
";"is quietly ignored.
The following code demonstrates how to supply initialization code forfunction parameters. The initialization code is eval'ed within doublequotes by the compiler before it is added to the output so anythingwhich should be interpreted literally [mainly "$", "@", or "\\"]must be protected with backslashes. The variables $var, $arg,and $type can be used as in typemaps.
bool_t rpcb_gettime(host,timep) char *host = (char *)SvPV_nolen($arg); 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.
If the initialization begins with "=", then it is output inthe declaration for the input variable, replacing the initializationsupplied by the typemap. If the initializationbegins with ";" or "+", then it is performed afterall of the input variables have been declared. In the ";"case the initialization normally supplied by the typemap is not performed.For the "+" case, the declaration for the variable will include theinitialization from the typemap. A globalvariable, %v, is available for the truly rare case whereinformation from one initialization is needed in anotherinitialization.
Here's a truly obscure example:
bool_t rpcb_gettime(host,timep) time_t &timep; /* \$v{timep}=@{[$v{timep}=$arg]} */ char *host + SvOK($v{timep}) ? SvPV_nolen($arg) : NULL; OUTPUT: timep
The construct "\$v{timep}=@{[$v{timep}=$arg]}" used in the aboveexample has a two-fold purpose: first, when this line is processed byxsubpp, the Perl snippet "$v{timep}=$arg" is evaluated. Second,the text of the evaluated snippet is output into the generated C file(inside a C comment)! During the processing of "char *host" line,$arg will evaluate to ST(0), and $v{timep} will evaluate toST(1).
Default Parameter Values
Default values for
XSUB arguments can be specified by placing anassignment statement in the parameter list. The default value maybe a number, a string or the special string
"NO_INIT". 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. This XSUB can be calledfrom Perl 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 immediatelybefore or after the declarations of the parameters from the
INPUT: sectionare emitted.
If a variable is declared inside a CODE: section it will follow any typemapcode that is emitted for the input parameters. This may result in thedeclaration ending up after C code, which is C syntax error. Similarerrors may happen with an explicit ";"-type or "+"-type initialization ofparameters is used (see ``Initializing Function Parameters''). Declaringthese variables in an INIT: section will not help.
In such cases, to force an additional variable to be declared togetherwith declarations of other variables, place the declaration into aPREINIT: section. The PREINIT: keyword may be used one or more timeswithin 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
For this particular case an INIT: keyword would generate thesame C code as the PREINIT: keyword. Another 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
Another way to declare "host" is to use a C block in the CODE: section:
bool_t rpcb_gettime(timep) time_t timep = NO_INIT CODE: { char *host = "localhost"; RETVAL = rpcb_gettime( host, &timep ); } OUTPUT: timep RETVAL
The ability to put additional declarations before the typemap entries areprocessed is very handy in the cases when typemap conversions manipulatesome global state:
MyObject mutate(o) PREINIT: MyState st = global_state; INPUT: MyObject o; CLEANUP: reset_to(global_state, st);
Here we suppose that conversion to "MyObject" in the INPUT: section and fromMyObject when processing RETVAL will modify a global variable "global_state".After these conversions are performed, we restore the old value of"global_state" (to avoid memory leaks, for example).
There is another way to trade clarity for compactness: INPUT sections allowdeclaration of C variables which do not appear in the parameter list ofa subroutine. Thus the above code for mutate() can be rewritten as
MyObject mutate(o) MyState st = global_state; MyObject o; CLEANUP: reset_to(global_state, st);
and the code for rpcb_gettime() can be rewritten as
bool_t rpcb_gettime(timep) time_t timep = NO_INIT char *host = "localhost"; C_ARGS: 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 an XSUB contains a comment like "/*scope*/" then scoping willbe automatically 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 the
XSUB. 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
Since INPUT sections allow declaration of C variables which do not appearin the parameter list of a subroutine, this may be shortened to:
bool_t rpcb_gettime(host,timep) time_t tt; char *host; char *h = host; time_t timep; CODE: RETVAL = rpcb_gettime( h, &tt ); timep = tt; OUTPUT: timep RETVAL
(We used our knowledge that input conversion for "char *" is a ``simple'' one,thus "host" is initialized on the declaration line, and our assignment"h = host" is not performed too early. Otherwise one would need to have theassignment "h = host" in a CODE: or INIT: section.)
The IN/OUTLIST/IN_OUTLIST/OUT/IN_OUT Keywords
In the list of parameters for an
XSUB, one can precede parameter namesby the
"IN"/
"OUTLIST"/
"IN_OUTLIST"/
"OUT"/
"IN_OUT" keywords.
"IN" keyword is the default, the other keywords indicate how the Perlinterface should differ from the C interface.
Parameters preceded by "OUTLIST"/"IN_OUTLIST"/"OUT"/"IN_OUT"keywords are considered to be used by the C subroutine viapointers. "OUTLIST"/"OUT" keywords indicate that the C subroutinedoes not inspect the memory pointed by this parameter, but will writethrough this pointer to provide additional return values.
Parameters preceded by "OUTLIST" keyword do not appear in the usagesignature of the generated Perl function.
Parameters preceded by "IN_OUTLIST"/"IN_OUT"/"OUT" do appear asparameters to the Perl function. With the exception of"OUT"-parameters, these parameters are converted to the correspondingC type, then pointers to these data are given as arguments to the Cfunction. It is expected that the C function will write through thesepointers.
The return list of the generated Perl function consists of the C return valuefrom the function (unless the XSUB is of "void" return type or"The NO_OUTPUT Keyword" was used) followed by all the "OUTLIST"and "IN_OUTLIST" parameters (in the order of appearance). On thereturn from the XSUB the "IN_OUT"/"OUT" Perl parameter will bemodified to have the values written by the C function.
For example, an XSUB
void day_month(OUTLIST day, IN unix_time, OUTLIST month) int day int unix_time int month
should be used from Perl as
my ($day, $month) = day_month(time);
The C signature of the corresponding function should be
void day_month(int *day, int unix_time, int *month);
The "IN"/"OUTLIST"/"IN_OUTLIST"/"IN_OUT"/"OUT" keywords can bemixed with ANSI-style declarations, as in
void day_month(OUTLIST int day, int unix_time, OUTLIST int month)
(here the optional "IN" keyword is omitted).
The "IN_OUT" parameters are identical with parameters introduced with``The & Unary Operator'' and put into the "OUTPUT:" section (see``The OUTPUT: Keyword''). The "IN_OUTLIST" parameters are very similar,the only difference being that the value C function writes through thepointer would not modify the Perl parameter, but is put in the outputlist.
The "OUTLIST"/"OUT" parameter differ from "IN_OUTLIST"/"IN_OUT"parameters only by the initial value of the Perl parameter notbeing read (and not being given to the C function - which gets somegarbage instead). For example, the same C function as above can beinterfaced with as
void day_month(OUT int day, int unix_time, OUT int month);
or
void day_month(day, unix_time, month) int &day = NO_INIT int unix_time int &month = NO_INIT OUTPUT: day month
However, the generated Perl function is called in very C-ish style:
my ($day, $month); day_month($day, time, $month);
The length(NAME) Keyword
If one of the input arguments to the C function is the length of a stringargument
"NAME", one can substitute the name of the length-argument by
"length(NAME)" in the
XSUB declaration. This argument must be omitted whenthe generated Perl function is called. E.g.,
void dump_chars(char *s, short l) { short n = 0; while (n < l) { printf("s[%d] = \"\\%#03o\"\n", n, (int)s[n]); n++; } } MODULE = x PACKAGE = x void dump_chars(char *s, short length(s))
should be called as "dump_chars($string)".
This directive is supported with ANSI-type function declarations only.
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 the
xsubpp 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_nolen(ST(1)); RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL
The C_ARGS: Keyword
The C_ARGS: keyword allows creating of
XSUBS which have differentcalling sequence from Perl than from C, without a need to write
CODE: or
PPCODE: section. The contents of the C_ARGS: paragraph isput as the argument to the called C function without any change.
For example, suppose that a C function is declared as
symbolic nth_derivative(int n, symbolic function, int flags);
and that the default flags are kept in a global C variable"default_flags". Suppose that you want to create an interface whichis called as
$second_deriv = $function->nth_derivative(2);
To do this, declare the XSUB as
symbolic nth_derivative(function, n) symbolic function int n C_ARGS: n, function, default_flags
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 should not be usedtogether within the same
XSUB.The actual difference between PPCODE: and CODE: sections is in theinitialization of "SP" macro (which stands for the current Perlstack pointer), and in the handling of data on the stack when returningfrom an XSUB. In CODE: sections SP preserves the value which was onentry to the XSUB: SP is on the function pointer (which follows thelast parameter). In PPCODE: sections SP is moved backward to thebeginning of the parameter list, which allows "PUSH*()" macrosto place output values in the place Perl expects them to be whenthe XSUB returns back to Perl.
The generated trailer for a CODE: section ensures that the number of returnvalues Perl will see is either 0 or 1 (depending on the "void"ness of thereturn value of the C function, and heuristics mentioned in``The RETVAL Variable''). The trailer generated for a PPCODE: sectionis based on the number of return values and on the number of times"SP" was updated by "[X]PUSH*()" macros.
Note that macros ST(i), "XST_m*()" and "XSRETURN*()" work equallywell in CODE: sections and PPCODE: sections.
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 available as "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");
When handling output parameters with a PPCODE section, be sure to handle'set' magic properly. See perlguts for details about 'set' magic.
Returning Undef And Empty Lists
Occasionally the programmer will want to return simply
"undef" 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 mnemonic 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: if( rpcb_gettime( host, &timep ) ){ ST(0) = sv_newmortal(); sv_setnv( ST(0), (double)timep); } else{ ST(0) = &PL_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 perlapi for other"XSRETURN" macros.
Since "XSRETURN_*" macros can be used with CODE blocks as well, one canrewrite this example as:
int rpcb_gettime(host) char *host PREINIT: time_t timep; CODE: RETVAL = rpcb_gettime( host, &timep ); if (RETVAL == 0) XSRETURN_UNDEF; OUTPUT: RETVAL
In fact, one can put this check into a POSTCALL: section as well. Togetherwith PREINIT: simplifications, this leads to:
int rpcb_gettime(host) char *host time_t timep; POSTCALL: if (RETVAL == 0) XSRETURN_UNDEF;
The REQUIRE: Keyword
The
REQUIRE: keyword is used to indicate the minimum version of the
xsubpp 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:, or
OUTPUT: blocks which are present in the
XSUB. The codespecified for the cleanup block will be added as the last statements inthe
XSUB. The POSTCALL: Keyword
This keyword can be used when an
XSUB requires special proceduresexecuted after the C subroutine call is performed. When the
POSTCALL:keyword is used it must precede
OUTPUT: and
CLEANUP: blocks which arepresent in the
XSUB.See examples in ``The NO_OUTPUT Keyword'' and ``Returning Undef And Empty Lists''.
The POSTCALL: block does not make a lot of sense when the C subroutinecall is supplied by user by providing either CODE: or PPCODE: section.
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
Note that if the version of the PM module is an NV (a floating pointnumber), it will be stringified with a possible loss of precision(currently chopping to nine decimal places) so that it may not matchthe version of the XS module anymore. Quoting the $VERSION declarationto make it a string is recommended if long version numbers are used.
The PROTOTYPES: Keyword
The
PROTOTYPES: keyword corresponds to
xsubpp's
"-prototypes" and
"-noprototypes" options. This keyword overrides the command line options.Prototypes are disabled 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.Note that
xsubpp will nag you if you don't explicitly enable or disableprototypes, with:
Please specify prototyping behavior for Foo.xs (see perlxs manual)
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 ``Prototypes'' in perlsub 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_nolen(ST(1)); RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL
If the prototypes are enabled, you can disable it locally for a givenXSUB as in the following example:
void rpcb_gettime_noproto() PROTOTYPE: DISABLE ...
The ALIAS: Keyword
The
ALIAS: keyword allows an
XSUB to have two or 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()" and"BAR::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 OVERLOAD: Keyword
Instead of writing an overloaded interface using pure Perl, youcan also use the
OVERLOAD keyword to define additional Perl namesfor your functions (like the
ALIAS: keyword above). However, theoverloaded functions must be defined with three parameters (exceptfor the
nomethod() function which needs four parameters). If anyfunction has the
OVERLOAD: keyword, several additional lineswill be defined in the c file generated by xsubpp in order toregister with the overload magic.
Since blessed objects are actually stored as RV's, it is usefulto use the typemap features to preprocess parameters and extractthe actual SV stored within the blessed RV. See the sample forT_PTROBJ_SPECIAL below.
To use the OVERLOAD: keyword, create an XS function which takesthree input parameters ( or use the c style '...' definition) likethis:
SV * cmp (lobj, robj, swap) My_Module_obj lobj My_Module_obj robj IV swap OVERLOAD: cmp <=> { /* function defined here */}
In this case, the function will overload both of the three waycomparison operators. For all overload operations using non-alphacharacters, you must type the parameter without quoting, separatingmultiple overloads with whitespace. Note that "`` (the stringifyoverload) should be entered as \''\" (i.e. escaped).
The FALLBACK: Keyword
In addition to the
OVERLOAD keyword, if you need to control howPerl autogenerates missing overloaded operators, you can set the
FALLBACK keyword in the module header section, like this:
MODULE = RPC PACKAGE = RPC FALLBACK: TRUE ...
where FALLBACK can take any of the three values TRUE, FALSE, orUNDEF. If you do not set any FALLBACK value when using OVERLOAD,it defaults to UNDEF. FALLBACK is not used except when one ormore functions using OVERLOAD have been defined. Please see``fallback'' in overload for more details.
The INTERFACE: Keyword
This keyword declares the current
XSUB as a keeper of the givencalling signature. If some text follows this keyword, it isconsidered as a list of functions which have this signature, andshould be attached to the current
XSUB.For example, if you have 4 C functions multiply(), divide(), add(),subtract() all having the signature:
symbolic f(symbolic, symbolic);
you can make them all to use the same XSUB using this:
symbolic interface_s_ss(arg1, arg2) symbolic arg1 symbolic arg2 INTERFACE: multiply divide add subtract
(This is th