Cari di Perl 
    Perl User Manual
Daftar Isi
(Sebelumnya) Guts of Perl debuggingPerl XS C/Perl type mapping (Berikutnya)
Internals and C language interface

XS language reference manual

Daftar Isi

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.

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 h2xsthat 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.

  1. bool_t rpcb_gettime(const char *host, time_t *timep);

From C this function will be called with the followingstatements.

  1. #include <rpc/rpc.h>
  2. bool_t status;
  3. time_t timep;
  4. 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.

  1. use RPC;
  2. $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.

  1. #include "EXTERN.h"
  2. #include "perl.h"
  3. #include "XSUB.h"
  4. #include <rpc/rpc.h>
  5. MODULE = RPC PACKAGE = RPC
  6. bool_t
  7. rpcb_gettime(host,timep)
  8. char *host
  9. time_t &timep
  10. OUTPUT:
  11. 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.

  1. package RPC;
  2. require Exporter;
  3. require DynaLoader;
  4. @ISA = qw(Exporter DynaLoader);
  5. @EXPORT = qw( rpcb_gettime );
  6. bootstrap RPC;
  7. 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.

  1. double
  2. sin(x)
  3. double x

Optionally, one can merge the description of types and the list ofargument names, rewriting this as

  1. double
  2. sin(double x)

This makes this XSUB look similar to an ANSI C declaration. An optionalsemicolon is allowed after the argument list, as in

  1. double
  2. sin(double x);

Parameters with C pointer types can have different semantic: C functionswith similar declarations

  1. bool string_looks_as_a_number(char *s);
  2. bool make_char_uppercase(char *c);

are used in absolutely incompatible manner. Parameters to these functionscould be described xsubpp like this:

  1. char * s
  2. 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.

  1. INCORRECT CORRECT
  2. double sin(x) double
  3. double x sin(x)
  4. 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.

  1. CORRECT
  2. double
  3. sin(x)
  4. 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:

  1. void
  2. alpha()
  3. PPCODE:
  4. ST(0) = newSVpv("Hello World",0);
  5. sv_2mortal(ST(0));
  6. XSRETURN(1);
  7. SV *
  8. beta()
  9. CODE:
  10. RETVAL = newSVpv("Hello World",0);
  11. OUTPUT:
  12. 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:

  1. AV *
  2. array()
  3. CODE:
  4. RETVAL = newAV();
  5. /* do something with RETVAL */
  6. OUTPUT:
  7. 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

  1. 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:

  1. AV *
  2. array()
  3. CODE:
  4. RETVAL = newAV();
  5. sv_2mortal((SV*)RETVAL);
  6. /* do something with RETVAL */
  7. OUTPUT:
  8. 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 firstMODULE keyword is considered C code and is passed through to the output withPOD 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.

  1. 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.

  1. MODULE = RPC PACKAGE = RPC
  2. [ XS code in package RPC ]
  3. MODULE = RPC PACKAGE = RPCB
  4. [ XS code in package RPCB ]
  5. MODULE = RPC PACKAGE = RPC
  6. [ 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 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.

  1. MODULE = RPC PREFIX = rpc_
  2. 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.

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. char *host
  4. time_t &timep
  5. OUTPUT:
  6. timep

The OUTPUT: keyword will also allow an output parameter tobe mapped to a matching piece of code rather than to atypemap.

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. char *host
  4. time_t &timep
  5. OUTPUT:
  6. 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,

  1. NO_OUTPUT int
  2. delete_file(char *name)
  3. POSTCALL:
  4. if (RETVAL != 0)
  5. 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.

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

The XSUB follows.

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. char *host
  4. time_t timep
  5. CODE:
  6. RETVAL = rpcb_gettime( host, &timep );
  7. OUTPUT:
  8. timep
  9. 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.

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. char *host
  4. time_t &timep
  5. INIT:
  6. printf("# Host is %s\n", host );
  7. OUTPUT:
  8. timep

Another use for the INIT: section is to check for preconditions beforemaking a call to the C function:

  1. long long
  2. lldiv(a,b)
  3. long long a
  4. long long b
  5. INIT:
  6. if (a == 0 && b == 0)
  7. XSRETURN_UNDEF;
  8. if (b == 0)
  9. 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.

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. char *host
  4. time_t &timep = NO_INIT
  5. OUTPUT:
  6. 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 precendence over thedefault typemap, the embedded typemaps may overwrite previousdefinitions of TYPEMAP, INPUT, and OUTPUT stanzas. The syntax forembedded typemaps is

  1. TYPEMAP: <<HERE
  2. ... your typemap code here ...
  3. 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.

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. char *host = (char *)SvPV_nolen($arg);
  4. time_t &timep = 0;
  5. OUTPUT:
  6. 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:

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. time_t &timep; /* \$v{timep}=@{[$v{timep}=$arg]} */
  4. char *host + SvOK($v{timep}) ? SvPV_nolen($arg) : NULL;
  5. OUTPUT:
  6. 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:

  1. $status = rpcb_gettime( $timep, $host );
  2. $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.

  1. bool_t
  2. rpcb_gettime(timep,host="localhost")
  3. char *host
  4. time_t timep = NO_INIT
  5. CODE:
  6. RETVAL = rpcb_gettime( host, &timep );
  7. OUTPUT:
  8. timep
  9. 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.

  1. bool_t
  2. rpcb_gettime(timep)
  3. time_t timep = NO_INIT
  4. PREINIT:
  5. char *host = "localhost";
  6. CODE:
  7. RETVAL = rpcb_gettime( host, &timep );
  8. OUTPUT:
  9. timep
  10. RETVAL

For this particular case an INIT: keyword would generate thesame C code as the PREINIT: keyword. Another correct, but error-prone example:

  1. bool_t
  2. rpcb_gettime(timep)
  3. time_t timep = NO_INIT
  4. CODE:
  5. char *host = "localhost";
  6. RETVAL = rpcb_gettime( host, &timep );
  7. OUTPUT:
  8. timep
  9. RETVAL

Another way to declare host is to use a C block in the CODE: section:

  1. bool_t
  2. rpcb_gettime(timep)
  3. time_t timep = NO_INIT
  4. CODE:
  5. {
  6. char *host = "localhost";
  7. RETVAL = rpcb_gettime( host, &timep );
  8. }
  9. OUTPUT:
  10. timep
  11. RETVAL

The ability to put additional declarations before the typemap entries areprocessed is very handy in the cases when typemap conversions manipulatesome global state:

  1. MyObject
  2. mutate(o)
  3. PREINIT:
  4. MyState st = global_state;
  5. INPUT:
  6. MyObject o;
  7. CLEANUP:
  8. 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 ofglobal_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

  1. MyObject
  2. mutate(o)
  3. MyState st = global_state;
  4. MyObject o;
  5. CLEANUP:
  6. reset_to(global_state, st);

and the code for rpcb_gettime() can be rewritten as

  1. bool_t
  2. rpcb_gettime(timep)
  3. time_t timep = NO_INIT
  4. char *host = "localhost";
  5. C_ARGS:
  6. host, &timep
  7. OUTPUT:
  8. timep
  9. 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:

  1. SCOPE: ENABLE

To disable scoping:

  1. 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.

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. char *host
  4. PREINIT:
  5. time_t tt;
  6. INPUT:
  7. time_t timep
  8. CODE:
  9. RETVAL = rpcb_gettime( host, &tt );
  10. timep = tt;
  11. OUTPUT:
  12. timep
  13. RETVAL

The next example shows each input parameter evaluated late.

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. PREINIT:
  4. time_t tt;
  5. INPUT:
  6. char *host
  7. PREINIT:
  8. char *h;
  9. INPUT:
  10. time_t timep
  11. CODE:
  12. h = host;
  13. RETVAL = rpcb_gettime( h, &tt );
  14. timep = tt;
  15. OUTPUT:
  16. timep
  17. RETVAL

Since INPUT sections allow declaration of C variables which do not appearin the parameter list of a subroutine, this may be shortened to:

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. time_t tt;
  4. char *host;
  5. char *h = host;
  6. time_t timep;
  7. CODE:
  8. RETVAL = rpcb_gettime( h, &tt );
  9. timep = tt;
  10. OUTPUT:
  11. timep
  12. RETVAL

(We used our knowledge that input conversion for char * is a "simple" one,thus host is initialized on the declaration line, and our assignmenth = 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_OUTkeywords 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 ofOUT-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 orThe NO_OUTPUT Keyword was used) followed by all the OUTLISTand 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

  1. void
  2. day_month(OUTLIST day, IN unix_time, OUTLIST month)
  3. int day
  4. int unix_time
  5. int month

should be used from Perl as

  1. my ($day, $month) = day_month(time);

The C signature of the corresponding function should be

  1. 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

  1. void
  2. 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 withThe & Unary Operator and put into the OUTPUT: section (seeThe 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_OUTparameters 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

  1. void day_month(OUT int day, int unix_time, OUT int month);

or

  1. void
  2. day_month(day, unix_time, month)
  3. int &day = NO_INIT
  4. int unix_time
  5. int &month = NO_INIT
  6. OUTPUT:
  7. day
  8. month

However, the generated Perl function is called in very C-ish style:

  1. my ($day, $month);
  2. 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 bylength(NAME) in the XSUB declaration. This argument must be omitted whenthe generated Perl function is called. E.g.,

  1. void
  2. dump_chars(char *s, short l)
  3. {
  4. short n = 0;
  5. while (n < l) {
  6. printf("s[%d] = \"\%#03o\"\n", n, (int)s[n]);
  7. n++;
  8. }
  9. }
  10. MODULE = xPACKAGE = x
  11. 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 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.

  1. $status = rpcb_gettime( $timep, $host );
  2. $status = rpcb_gettime( $timep );

The XS code, with ellipsis, follows.

  1. bool_t
  2. rpcb_gettime(timep, ...)
  3. time_t timep = NO_INIT
  4. PREINIT:
  5. char *host = "localhost";
  6. CODE:
  7. if( items > 1 )
  8. host = (char *)SvPV_nolen(ST(1));
  9. RETVAL = rpcb_gettime( host, &timep );
  10. OUTPUT:
  11. timep
  12. 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 writeCODE: 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

  1. symbolic nth_derivative(int n, symbolic function, int flags);

and that the default flags are kept in a global C variabledefault_flags. Suppose that you want to create an interface whichis called as

  1. $second_deriv = $function->nth_derivative(2);

To do this, declare the XSUB as

  1. symbolic
  2. nth_derivative(function, n)
  3. symbolicfunction
  4. intn
  5. C_ARGS:
  6. 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 voidness of thereturn value of the C function, and heuristics mentioned inThe RETVAL Variable). The trailer generated for a PPCODE: sectionis based on the number of return values and on the number of timesSP 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.

  1. void
  2. rpcb_gettime(host)
  3. char *host
  4. PREINIT:
  5. time_t timep;
  6. bool_t status;
  7. PPCODE:
  8. status = rpcb_gettime( host, &timep );
  9. EXTEND(SP, 2);
  10. PUSHs(sv_2mortal(newSViv(status)));
  11. 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.

  1. ($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 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.

  1. $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.

  1. SV *
  2. rpcb_gettime(host)
  3. char * host
  4. PREINIT:
  5. time_t timep;
  6. bool_t x;
  7. CODE:
  8. ST(0) = sv_newmortal();
  9. if( rpcb_gettime( host, &timep ) )
  10. sv_setnv( ST(0), (double)timep);

The next example demonstrates how one would place an explicit undef in thereturn value, should the need arise.

  1. SV *
  2. rpcb_gettime(host)
  3. char * host
  4. PREINIT:
  5. time_t timep;
  6. bool_t x;
  7. CODE:
  8. if( rpcb_gettime( host, &timep ) ){
  9. ST(0) = sv_newmortal();
  10. sv_setnv( ST(0), (double)timep);
  11. }
  12. else{
  13. ST(0) = &PL_sv_undef;
  14. }

To return an empty list one must use a PPCODE: block andthen not push return values on the stack.

  1. void
  2. rpcb_gettime(host)
  3. char *host
  4. PREINIT:
  5. time_t timep;
  6. PPCODE:
  7. if( rpcb_gettime( host, &timep ) )
  8. PUSHs(sv_2mortal(newSViv(timep)));
  9. else{
  10. /* Nothing pushed on stack, so an empty
  11. * list is implicitly returned. */
  12. }

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 otherXSRETURN macros.

Since XSRETURN_* macros can be used with CODE blocks as well, one canrewrite this example as:

  1. int
  2. rpcb_gettime(host)
  3. char *host
  4. PREINIT:
  5. time_t timep;
  6. CODE:
  7. RETVAL = rpcb_gettime( host, &timep );
  8. if (RETVAL == 0)
  9. XSRETURN_UNDEF;
  10. OUTPUT:
  11. RETVAL

In fact, one can put this check into a POSTCALL: section as well. Togetherwith PREINIT: simplifications, this leads to:

  1. int
  2. rpcb_gettime(host)
  3. char *host
  4. time_t timep;
  5. POSTCALL:
  6. if (RETVAL == 0)
  7. XSRETURN_UNDEF;

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:

  1. 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 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.

  1. BOOT:
  2. # The following message will be printed when the
  3. # bootstrap function executes.
  4. 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:

  1. VERSIONCHECK: ENABLE

To disable version checking:

  1. 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 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:

  1. PROTOTYPES: ENABLE

To disable prototypes:

  1. 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.

  1. bool_t
  2. rpcb_gettime(timep, ...)
  3. time_t timep = NO_INIT
  4. PROTOTYPE: $;$
  5. PREINIT:
  6. char *host = "localhost";
  7. CODE:
  8. if( items > 1 )
  9. host = (char *)SvPV_nolen(ST(1));
  10. RETVAL = rpcb_gettime( host, &timep );
  11. OUTPUT:
  12. timep
  13. RETVAL

If the prototypes are enabled, you can disable it locally for a givenXSUB as in the following example:

  1. void
  2. rpcb_gettime_noproto()
  3. PROTOTYPE: DISABLE
  4. ...

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() andBAR::getit() for this function.

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. char *host
  4. time_t &timep
  5. ALIAS:
  6. FOO::gettime = 1
  7. BAR::getit = 2
  8. INIT:
  9. printf("# ix = %d\n", ix );
  10. OUTPUT:
  11. 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:

  1. SV *
  2. cmp (lobj, robj, swap)
  3. My_Module_obj lobj
  4. My_Module_obj robj
  5. IV swap
  6. OVERLOAD: cmp <=>
  7. { /* 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 theFALLBACK keyword in the module header section, like this:

  1. MODULE = RPC PACKAGE = RPC
  2. FALLBACK: TRUE
  3. ...

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 seefallback 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:

  1. symbolic f(symbolic, symbolic);

you can make them all to use the same XSUB using this:

  1. symbolic
  2. interface_s_ss(arg1, arg2)
  3. symbolicarg1
  4. symbolicarg2
  5. INTERFACE:
  6. multiply divide
  7. add subtract

(This is the complete XSUB code for 4 Perl functions!) Four generatedPerl function share names with corresponding C functions.

The advantage of this approach comparing to ALIAS: keyword is that thereis no need to code a switch statement, each Perl function (which sharesthe same XSUB) knows which C function it should call. Additionally, onecan attach an extra function remainder() at runtime by using

  1. CV *mycv = newXSproto("Symbolic::remainder",
  2. XS_Symbolic_interface_s_ss, __FILE__, "$$");
  3. XSINTERFACE_FUNC_SET(mycv, remainder);

say, from another XSUB. (This example supposes that there was noINTERFACE_MACRO: section, otherwise one needs to use something else instead ofXSINTERFACE_FUNC_SET, see the next section.)

The INTERFACE_MACRO: Keyword

This keyword allows one to define an INTERFACE using a different wayto extract a function pointer from an XSUB. The text which followsthis keyword should give the name of macros which would extract/set afunction pointer. The extractor macro is given return type, CV*,and XSANY.any_dptr for this CV*. The setter macro is given cv,and the function pointer.

The default value is XSINTERFACE_FUNC and XSINTERFACE_FUNC_SET.An INTERFACE keyword with an empty list of functions can be omitted ifINTERFACE_MACRO keyword is used.

Suppose that in the previous example functions pointers formultiply(), divide(), add(), subtract() are kept in a global C arrayfp[] with offsets being multiply_off, divide_off, add_off,subtract_off. Then one can use

  1. #define XSINTERFACE_FUNC_BYOFFSET(ret,cv,f) \
  2. ((XSINTERFACE_CVT_ANON(ret))fp[CvXSUBANY(cv).any_i32])
  3. #define XSINTERFACE_FUNC_BYOFFSET_set(cv,f) \
  4. CvXSUBANY(cv).any_i32 = CAT2( f, _off )

in C section,

  1. symbolic
  2. interface_s_ss(arg1, arg2)
  3. symbolicarg1
  4. symbolicarg2
  5. INTERFACE_MACRO:
  6. XSINTERFACE_FUNC_BYOFFSET
  7. XSINTERFACE_FUNC_BYOFFSET_set
  8. INTERFACE:
  9. multiply divide
  10. add subtract

in XSUB section.

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:

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. char *host
  4. time_t &timep
  5. OUTPUT:
  6. timep

The XS module can use INCLUDE: to pull that file into it.

  1. INCLUDE: Rpcb1.xsh

If the parameters to the INCLUDE: keyword are followed by a pipe (|) thenthe compiler will interpret the parameters as a command. This feature ismildly deprecated in favour of the INCLUDE_COMMAND: directive, as documentedbelow.

  1. INCLUDE: cat Rpcb1.xsh |

Do not use this to run perl: INCLUDE: perl | will run the perl thathappens to be the first in your path and not necessarily the same perl that isused to run xsubpp. See The INCLUDE_COMMAND: Keyword.

The INCLUDE_COMMAND: Keyword

Runs the supplied command and includes its output into the current XSdocument. INCLUDE_COMMAND assigns special meaning to the $^X tokenin that it runs the same perl interpreter that is running xsubpp:

  1. INCLUDE_COMMAND: cat Rpcb1.xsh
  2. INCLUDE_COMMAND: $^X -e ...

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 ALIAS: Keyword), or maybe via the items variable(see 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).

  1. long
  2. rpcb_gettime(a,b)
  3. CASE: ix == 1
  4. ALIAS:
  5. x_gettime = 1
  6. INPUT:
  7. # 'a' is timep, 'b' is host
  8. char *b
  9. time_t a = NO_INIT
  10. CODE:
  11. RETVAL = rpcb_gettime( b, &a );
  12. OUTPUT:
  13. a
  14. RETVAL
  15. CASE:
  16. # 'a' is host, 'b' is timep
  17. char *a
  18. time_t &b = NO_INIT
  19. OUTPUT:
  20. b
  21. RETVAL

That function can be called with either of the following statements. Notethe different argument lists.

  1. $status = rpcb_gettime( $host, $timep );
  2. $status = x_gettime( $timep, $host );

The EXPORT_XSUB_SYMBOLS: Keyword

The EXPORT_XSUB_SYMBOLS: keyword is likely something you will never need.In perl versions earlier than 5.16.0, this keyword does nothing. Startingwith 5.16, XSUB symbols are no longer exported by default. That is, theyare static functions. If you include

  1. EXPORT_XSUB_SYMBOLS: ENABLE

in your XS code, the XSUBs following this line will not be declared static.You can later disable this with

  1. EXPORT_XSUB_SYMBOLS: DISABLE

which, again, is the default that you should probably never change.You cannot use this keyword on versions of perl before 5.16 to makeXSUBs static.

The & Unary Operator

The & unary operator in the INPUT: section is used to tell xsubppthat it should convert a Perl value to/from C using the C type to the leftof &, but provide a pointer to this value when the C function is called.

This is useful to avoid a CODE: block for a C function which takes a parameterby reference. Typically, the parameter should be not a pointer type (anint or long but not an 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.

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. char *host
  4. time_t timep
  5. OUTPUT:
  6. 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).

  1. bool_t
  2. rpcb_gettime(host,timep)
  3. char *host
  4. time_t &timep
  5. OUTPUT:
  6. timep

Inserting POD, Comments and C Preprocessor Directives

C preprocessor directives are allowed within BOOT:, PREINIT: INIT:, CODE:,PPCODE:, POSTCALL:, and CLEANUP: blocks, as well as outside the functions.Comments are allowed anywhere after the MODULE keyword. The compiler willpass the preprocessor directives through untouched and will remove thecommented lines. POD documentation is allowed at any point, both in theC and XS language sections. POD must be terminated with a =cut command;xsubpp will exit with an error if it does not. It is very unlikely thathuman generated C code will be mistaken for POD, as most indenting stylesresult in whitespace in front of any line starting with =. Machinegenerated XS files may fall into this trap unless care is taken toensure that a space breaks the sequence "\n=".

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

  1. #if ... version1
  2. #else /* ... version2 */
  3. #endif

and not

  1. #if ... version1
  2. #endif
  3. #if ... version2
  4. #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 an XSUB name contains ::, it is considered to be a C++ method.The generated Perl function will assume thatits 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 return type of the XSUB includes static, the method is consideredto be a static method. 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.

  1. class color {
  2. public:
  3. color();
  4. ~color();
  5. int blue();
  6. void set_blue( int );
  7. private:
  8. int c_blue;
  9. };

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.

  1. int
  2. color::blue()
  3. void
  4. color::set_blue( val )
  5. int val

Both Perl functions will expect an object as the first parameter. In thegenerated C++ code the object is called THIS, and the method call willbe performed on this object. So in the C++ code the blue() and set_blue()methods will be called as this:

  1. RETVAL = THIS->blue();
  2. THIS->set_blue( val );

You could also write a single get/set method using an optional argument:

  1. int
  2. color::blue( val = NO_INIT )
  3. int val
  4. PROTOTYPE $;$
  5. CODE:
  6. if (items > 1)
  7. THIS->set_blue( val );
  8. RETVAL = THIS->blue();
  9. OUTPUT:
  10. RETVAL

If the function's name is DESTROY then the C++ delete function will becalled and THIS will be given as its parameter. The generated C++ code for

  1. void
  2. color::DESTROY()

will look like this:

  1. color *THIS = ...;// Initialized as in typemap
  2. 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.

  1. color *
  2. color::new()

The generated C++ code will call new.

  1. RETVAL = new color();

The following is an example of a typemap that could be used for this C++example.

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

Interface Strategy

When designing an interface between Perl and a C library a straighttranslation from C to XS (such as created by h2xs -x) is often sufficient.However, sometimes the interface will lookvery C-like and occasionally nonintuitive, especially when the C functionmodifies one of its parameters, or returns failure inband (as in "negativereturn values mean failure"). 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 with input/output or output parameters. The XSUBs forthese functions may be able to return lists to Perl.

Identify the C functions which use some inband info as an indicationof failure. They may becandidates to return undef or an empty list in case of failure. If thefailure may be detected without a call to the C function, you may want to usean INIT: section to report the failure. For failures detectable after the Cfunction returns one may want to use a POSTCALL: section to process thefailure. In more complicated cases use CODE: or PPCODE: sections.

If many functions use the same failure indication based on the return value,you may want to create a special typedef to handle this situation. Put

  1. typedef int negative_is_failure;

near the beginning of XS file, and create an OUTPUT typemap entryfor negative_is_failure which converts negative values to undef, ormaybe croak()s. After this the return value of type negative_is_failurewill create more Perl-like interface.

Identify which values are used by only the C and XSUB functionsthemselves, say, when a parameter to a function should be a contents of aglobal variable. 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 may be used to implement input/output oroutput parameters, they can be handled in XS with the & unary operator,and, possibly, using the NO_INIT keyword.Some others will require handling of types like int *, and one needsto decide what a useful Perl translation will do in such a case. Whenthe semantic is clear, it is advisable to put the translation into a typemapfile.

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. (This is handled automatically by h2xs -x.)

If the same C type is used in several different contexts which requiredifferent translations, typedef several new types mapped to this C type,and create separate typemap entries for these new types. Use thesetypes in declarations of return type and parameters to XSUBs.

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.

  1. 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.

  1. typedef struct netconfig Netconfig;
  2. MODULE = RPC PACKAGE = RPC
  3. Netconfig *
  4. getnetconfigent(netid)
  5. char *netid
  6. MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
  7. void
  8. rpcb_DESTROY(netconf)
  9. Netconfig *netconf
  10. CODE:
  11. printf("Now in NetconfigPtr::DESTROY\n");
  12. free( netconf );

This example requires the following typemap entry. Consultperlxstypemap for more information about adding new typemapsfor an extension.

  1. TYPEMAP
  2. Netconfig * T_PTROBJ

This example will be used with the following Perl statements.

  1. use RPC;
  2. $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.

Safely Storing Static Data in XS

Starting with Perl 5.8, a macro framework has been defined to allowstatic data to be safely stored in XS modules that will be accessed froma multi-threaded Perl.

Although primarily designed for use with multi-threaded Perl, the macroshave been designed so that they will work with non-threaded Perl as well.

It is therefore strongly recommended that these macros be used by allXS modules that make use of static data.

The easiest way to get a template set of macros to use is by specifyingthe -g (--global) option with h2xs (see h2xs).

Below is an example module that makes use of the macros.

  1. #include "EXTERN.h"
  2. #include "perl.h"
  3. #include "XSUB.h"
  4. /* Global Data */
  5. #define MY_CXT_KEY "BlindMice::_guts" XS_VERSION
  6. typedef struct {
  7. int count;
  8. char name[3][100];
  9. } my_cxt_t;
  10. START_MY_CXT
  11. MODULE = BlindMice PACKAGE = BlindMice
  12. BOOT:
  13. {
  14. MY_CXT_INIT;
  15. MY_CXT.count = 0;
  16. strcpy(MY_CXT.name[0], "None");
  17. strcpy(MY_CXT.name[1], "None");
  18. strcpy(MY_CXT.name[2], "None");
  19. }
  20. int
  21. newMouse(char * name)
  22. char * name;
  23. PREINIT:
  24. dMY_CXT;
  25. CODE:
  26. if (MY_CXT.count >= 3) {
  27. warn("Already have 3 blind mice");
  28. RETVAL = 0;
  29. }
  30. else {
  31. RETVAL = ++ MY_CXT.count;
  32. strcpy(MY_CXT.name[MY_CXT.count - 1], name);
  33. }
  34. char *
  35. get_mouse_name(index)
  36. int index
  37. CODE:
  38. dMY_CXT;
  39. RETVAL = MY_CXT.lives ++;
  40. if (index > MY_CXT.count)
  41. croak("There are only 3 blind mice.");
  42. else
  43. RETVAL = newSVpv(MY_CXT.name[index - 1]);
  44. void
  45. CLONE(...)
  46. CODE:
  47. MY_CXT_CLONE;

REFERENCE

  • MY_CXT_KEY

    This macro is used to define a unique key to refer to the static datafor an XS module. The suggested naming scheme, as used by h2xs, is touse a string that consists of the module name, the string "::_guts"and the module version number.

    1. #define MY_CXT_KEY "MyModule::_guts" XS_VERSION
  • typedef my_cxt_t

    This struct typedef must always be called my_cxt_t. The otherCXT* macros assume the existence of the my_cxt_t typedef name.

    Declare a typedef named my_cxt_t that is a structure that containsall the data that needs to be interpreter-local.

    1. typedef struct {
    2. int some_value;
    3. } my_cxt_t;
  • START_MY_CXT

    Always place the START_MY_CXT macro directly after the declarationof my_cxt_t.

  • MY_CXT_INIT

    The MY_CXT_INIT macro initialises storage for the my_cxt_t struct.

    It must be called exactly once, typically in a BOOT: section. If youare maintaining multiple interpreters, it should be called once in eachinterpreter instance, except for interpreters cloned from existing ones.(But see MY_CXT_CLONE below.)

  • dMY_CXT

    Use the dMY_CXT macro (a declaration) in all the functions that accessMY_CXT.

  • MY_CXT

    Use the MY_CXT macro to access members of the my_cxt_t struct. Forexample, if my_cxt_t is

    1. typedef struct {
    2. int index;
    3. } my_cxt_t;

    then use this to access the index member

    1. dMY_CXT;
    2. MY_CXT.index = 2;
  • aMY_CXT/pMY_CXT

    dMY_CXT may be quite expensive to calculate, and to avoid the overheadof invoking it in each function it is possible to pass the declarationonto other functions using the aMY_CXT/pMY_CXT macros, eg

    1. void sub1() {
    2. dMY_CXT;
    3. MY_CXT.index = 1;
    4. sub2(aMY_CXT);
    5. }
    6. void sub2(pMY_CXT) {
    7. MY_CXT.index = 2;
    8. }

    Analogously to pTHX, there are equivalent forms for when the macro is thefirst or last in multiple arguments, where an underscore represents acomma, i.e. _aMY_CXT, aMY_CXT_, _pMY_CXT and pMY_CXT_.

  • MY_CXT_CLONE

    By default, when a new interpreter is created as a copy of an existing one(eg via threads->create()), both interpreters share the same physicalmy_cxt_t structure. Calling MY_CXT_CLONE (typically via the package'sCLONE() function), causes a byte-for-byte copy of the structure to betaken, and any future dMY_CXT will cause the copy to be accessed instead.

  • MY_CXT_INIT_INTERP(my_perl)
  • dMY_CXT_INTERP(my_perl)

    These are versions of the macros which take an explicit interpreter as anargument.

Note that these macros will only work together within the same sourcefile; that is, a dMY_CTX in one source file will access a different structurethan a dMY_CTX in another source file.

Thread-aware system interfaces

Starting from Perl 5.8, in C/C++ level Perl knows how to wrapsystem/library interfaces that have thread-aware versions(e.g. getpwent_r()) into frontend macros (e.g. getpwent()) thatcorrectly handle the multithreaded interaction with the Perlinterpreter. This will happen transparently, the only thingyou need to do is to instantiate a Perl interpreter.

This wrapping happens always when compiling Perl core source(PERL_CORE is defined) or the Perl core extensions (PERL_EXT isdefined). When compiling XS code outside of Perl core the wrappingdoes not take place. Note, however, that intermixing the _r-forms(as Perl compiled for multithreaded operation will do) and the _r-lessforms is neither well-defined (inconsistent results, data corruption,or even crashes become more likely), nor is it very portable.

EXAMPLES

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

  1. #include "EXTERN.h"
  2. #include "perl.h"
  3. #include "XSUB.h"
  4. #include <rpc/rpc.h>
  5. typedef struct netconfig Netconfig;
  6. MODULE = RPC PACKAGE = RPC
  7. SV *
  8. rpcb_gettime(host="localhost")
  9. char *host
  10. PREINIT:
  11. time_t timep;
  12. CODE:
  13. ST(0) = sv_newmortal();
  14. if( rpcb_gettime( host, &timep ) )
  15. sv_setnv( ST(0), (double)timep );
  16. Netconfig *
  17. getnetconfigent(netid="udp")
  18. char *netid
  19. MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
  20. void
  21. rpcb_DESTROY(netconf)
  22. Netconfig *netconf
  23. CODE:
  24. printf("NetconfigPtr::DESTROY\n");
  25. free( netconf );

File typemap: Custom typemap for RPC.xs. (cf. perlxstypemap)

  1. TYPEMAP
  2. Netconfig * T_PTROBJ

File RPC.pm: Perl module for the RPC extension.

  1. package RPC;
  2. require Exporter;
  3. require DynaLoader;
  4. @ISA = qw(Exporter DynaLoader);
  5. @EXPORT = qw(rpcb_gettime getnetconfigent);
  6. bootstrap RPC;
  7. 1;

File rpctest.pl: Perl test program for the RPC extension.

  1. use RPC;
  2. $netconf = getnetconfigent();
  3. $a = rpcb_gettime();
  4. print "time = $a\n";
  5. print "netconf = $netconf\n";
  6. $netconf = getnetconfigent("tcp");
  7. $a = rpcb_gettime("poplar");
  8. print "time = $a\n";
  9. print "netconf = $netconf\n";

XS VERSION

This document covers features supported by ExtUtils::ParseXS(also known as xsubpp) 3.13_01.

AUTHOR

Originally written by Dean Roehrich <[email protected]>.

Maintained since 1996 by The Perl Porters <[email protected]>.

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Guts of Perl debuggingPerl XS C/Perl type mapping (Berikutnya)