1N/A=head1 NAME
1N/A
1N/Aperlxs - XS language reference manual
1N/A
1N/A=head1 DESCRIPTION
1N/A
1N/A=head2 Introduction
1N/A
1N/AXS is an interface description file format used to create an extension
1N/Ainterface between Perl and C code (or a C library) which one wishes
1N/Ato use with Perl. The XS interface is combined with the library to
1N/Acreate a new library which can then be either dynamically loaded
1N/Aor statically linked into perl. The XS interface description is
1N/Awritten in the XS language and is the core component of the Perl
1N/Aextension interface.
1N/A
1N/AAn B<XSUB> forms the basic unit of the XS interface. After compilation
1N/Aby the B<xsubpp> compiler, each XSUB amounts to a C function definition
1N/Awhich will provide the glue between Perl calling conventions and C
1N/Acalling conventions.
1N/A
1N/AThe glue code pulls the arguments from the Perl stack, converts these
1N/APerl values to the formats expected by a C function, call this C function,
1N/Atransfers the return values of the C function back to Perl.
1N/AReturn values here may be a conventional C return value or any C
1N/Afunction arguments that may serve as output parameters. These return
1N/Avalues may be passed back to Perl either by putting them on the
1N/APerl stack, or by modifying the arguments supplied from the Perl side.
1N/A
1N/AThe above is a somewhat simplified view of what really happens. Since
1N/APerl allows more flexible calling conventions than C, XSUBs may do much
1N/Amore in practice, such as checking input parameters for validity,
1N/Athrowing exceptions (or returning undef/empty list) if the return value
1N/Afrom the C function indicates failure, calling different C functions
1N/Abased on numbers and types of the arguments, providing an object-oriented
1N/Ainterface, etc.
1N/A
1N/AOf course, one could write such glue code directly in C. However, this
1N/Awould be a tedious task, especially if one needs to write glue for
1N/Amultiple C functions, and/or one is not familiar enough with the Perl
1N/Astack discipline and other such arcana. XS comes to the rescue here:
1N/Ainstead of writing this glue C code in long-hand, one can write
1N/Aa more concise short-hand I<description> of what should be done by
1N/Athe glue, and let the XS compiler B<xsubpp> handle the rest.
1N/A
1N/AThe XS language allows one to describe the mapping between how the C
1N/Aroutine is used, and how the corresponding Perl routine is used. It
1N/Aalso allows creation of Perl routines which are directly translated to
1N/AC code and which are not related to a pre-existing C function. In cases
1N/Awhen the C interface coincides with the Perl interface, the XSUB
1N/Adeclaration is almost identical to a declaration of a C function (in K&R
1N/Astyle). In such circumstances, there is another tool called C<h2xs>
1N/Athat is able to translate an entire C header file into a corresponding
1N/AXS file that will provide glue to the functions/macros described in
1N/Athe header file.
1N/A
1N/AThe XS compiler is called B<xsubpp>. This compiler creates
1N/Athe constructs necessary to let an XSUB manipulate Perl values, and
1N/Acreates the glue necessary to let Perl call the XSUB. The compiler
1N/Auses B<typemaps> to determine how to map C function parameters
1N/Aand output values to Perl values and back. The default typemap
1N/A(which comes with Perl) handles many common C types. A supplementary
1N/Atypemap may also be needed to handle any special structures and types
1N/Afor the library being linked.
1N/A
1N/AA file in XS format starts with a C language section which goes until the
1N/Afirst C<MODULE =Z<>> directive. Other XS directives and XSUB definitions
1N/Amay follow this line. The "language" used in this part of the file
1N/Ais usually referred to as the XS language. B<xsubpp> recognizes and
1N/Askips POD (see L<perlpod>) in both the C and XS language sections, which
1N/Aallows the XS file to contain embedded documentation.
1N/A
1N/ASee L<perlxstut> for a tutorial on the whole extension creation process.
1N/A
1N/ANote: For some extensions, Dave Beazley's SWIG system may provide a
1N/Asignificantly more convenient mechanism for creating the extension
1N/Aglue code. See http://www.swig.org/ for more information.
1N/A
1N/A=head2 On The Road
1N/A
1N/AMany of the examples which follow will concentrate on creating an interface
1N/Abetween Perl and the ONC+ RPC bind library functions. The rpcb_gettime()
1N/Afunction is used to demonstrate many features of the XS language. This
1N/Afunction has two parameters; the first is an input parameter and the second
1N/Ais an output parameter. The function also returns a status value.
1N/A
1N/A bool_t rpcb_gettime(const char *host, time_t *timep);
1N/A
1N/AFrom C this function will be called with the following
1N/Astatements.
1N/A
1N/A #include <rpc/rpc.h>
1N/A bool_t status;
1N/A time_t timep;
1N/A status = rpcb_gettime( "localhost", &timep );
1N/A
1N/AIf an XSUB is created to offer a direct translation between this function
1N/Aand Perl, then this XSUB will be used from Perl with the following code.
1N/AThe $status and $timep variables will contain the output of the function.
1N/A
1N/A use RPC;
1N/A $status = rpcb_gettime( "localhost", $timep );
1N/A
1N/AThe following XS file shows an XS subroutine, or XSUB, which
1N/Ademonstrates one possible interface to the rpcb_gettime()
1N/Afunction. This XSUB represents a direct translation between
1N/AC and Perl and so preserves the interface even from Perl.
1N/AThis XSUB will be invoked from Perl with the usage shown
1N/Aabove. Note that the first three #include statements, for
1N/AC<EXTERN.h>, C<perl.h>, and C<XSUB.h>, will always be present at the
1N/Abeginning of an XS file. This approach and others will be
1N/Aexpanded later in this document.
1N/A
1N/A #include "EXTERN.h"
1N/A #include "perl.h"
1N/A #include "XSUB.h"
1N/A #include <rpc/rpc.h>
1N/A
1N/A MODULE = RPC PACKAGE = RPC
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A char *host
1N/A time_t &timep
1N/A OUTPUT:
1N/A timep
1N/A
1N/AAny extension to Perl, including those containing XSUBs,
1N/Ashould have a Perl module to serve as the bootstrap which
1N/Apulls the extension into Perl. This module will export the
1N/Aextension's functions and variables to the Perl program and
1N/Awill cause the extension's XSUBs to be linked into Perl.
1N/AThe following module will be used for most of the examples
1N/Ain this document and should be used from Perl with the C<use>
1N/Acommand as shown earlier. Perl modules are explained in
1N/Amore detail later in this document.
1N/A
1N/A package RPC;
1N/A
1N/A require Exporter;
1N/A require DynaLoader;
1N/A @ISA = qw(Exporter DynaLoader);
1N/A @EXPORT = qw( rpcb_gettime );
1N/A
1N/A bootstrap RPC;
1N/A 1;
1N/A
1N/AThroughout this document a variety of interfaces to the rpcb_gettime()
1N/AXSUB will be explored. The XSUBs will take their parameters in different
1N/Aorders or will take different numbers of parameters. In each case the
1N/AXSUB is an abstraction between Perl and the real C rpcb_gettime()
1N/Afunction, and the XSUB must always ensure that the real rpcb_gettime()
1N/Afunction is called with the correct parameters. This abstraction will
1N/Aallow the programmer to create a more Perl-like interface to the C
1N/Afunction.
1N/A
1N/A=head2 The Anatomy of an XSUB
1N/A
1N/AThe simplest XSUBs consist of 3 parts: a description of the return
1N/Avalue, the name of the XSUB routine and the names of its arguments,
1N/Aand a description of types or formats of the arguments.
1N/A
1N/AThe following XSUB allows a Perl program to access a C library function
1N/Acalled sin(). The XSUB will imitate the C function which takes a single
1N/Aargument and returns a single value.
1N/A
1N/A double
1N/A sin(x)
1N/A double x
1N/A
1N/AOptionally, one can merge the description of types and the list of
1N/Aargument names, rewriting this as
1N/A
1N/A double
1N/A sin(double x)
1N/A
1N/AThis makes this XSUB look similar to an ANSI C declaration. An optional
1N/Asemicolon is allowed after the argument list, as in
1N/A
1N/A double
1N/A sin(double x);
1N/A
1N/AParameters with C pointer types can have different semantic: C functions
1N/Awith similar declarations
1N/A
1N/A bool string_looks_as_a_number(char *s);
1N/A bool make_char_uppercase(char *c);
1N/A
1N/Aare used in absolutely incompatible manner. Parameters to these functions
1N/Acould be described B<xsubpp> like this:
1N/A
1N/A char * s
1N/A char &c
1N/A
1N/ABoth these XS declarations correspond to the C<char*> C type, but they have
1N/Adifferent semantics, see L<"The & Unary Operator">.
1N/A
1N/AIt is convenient to think that the indirection operator
1N/AC<*> should be considered as a part of the type and the address operator C<&>
1N/Ashould be considered part of the variable. See L<"The Typemap">
1N/Afor more info about handling qualifiers and unary operators in C types.
1N/A
1N/AThe function name and the return type must be placed on
1N/Aseparate lines and should be flush left-adjusted.
1N/A
1N/A INCORRECT CORRECT
1N/A
1N/A double sin(x) double
1N/A double x sin(x)
1N/A double x
1N/A
1N/AThe rest of the function description may be indented or left-adjusted. The
1N/Afollowing example shows a function with its body left-adjusted. Most
1N/Aexamples in this document will indent the body for better readability.
1N/A
1N/A CORRECT
1N/A
1N/A double
1N/A sin(x)
1N/A double x
1N/A
1N/AMore complicated XSUBs may contain many other sections. Each section of
1N/Aan XSUB starts with the corresponding keyword, such as INIT: or CLEANUP:.
1N/AHowever, the first two lines of an XSUB always contain the same data:
1N/Adescriptions of the return type and the names of the function and its
1N/Aparameters. Whatever immediately follows these is considered to be
1N/Aan INPUT: section unless explicitly marked with another keyword.
1N/A(See L<The INPUT: Keyword>.)
1N/A
1N/AAn XSUB section continues until another section-start keyword is found.
1N/A
1N/A=head2 The Argument Stack
1N/A
1N/AThe Perl argument stack is used to store the values which are
1N/Asent as parameters to the XSUB and to store the XSUB's
1N/Areturn value(s). In reality all Perl functions (including non-XSUB
1N/Aones) keep their values on this stack all the same time, each limited
1N/Ato its own range of positions on the stack. In this document the
1N/Afirst position on that stack which belongs to the active
1N/Afunction will be referred to as position 0 for that function.
1N/A
1N/AXSUBs refer to their stack arguments with the macro B<ST(x)>, where I<x>
1N/Arefers to a position in this XSUB's part of the stack. Position 0 for that
1N/Afunction would be known to the XSUB as ST(0). The XSUB's incoming
1N/Aparameters and outgoing return values always begin at ST(0). For many
1N/Asimple cases the B<xsubpp> compiler will generate the code necessary to
1N/Ahandle the argument stack by embedding code fragments found in the
1N/Atypemaps. In more complex cases the programmer must supply the code.
1N/A
1N/A=head2 The RETVAL Variable
1N/A
1N/AThe RETVAL variable is a special C variable that is declared automatically
1N/Afor you. The C type of RETVAL matches the return type of the C library
1N/Afunction. The B<xsubpp> compiler will declare this variable in each XSUB
1N/Awith non-C<void> return type. By default the generated C function
1N/Awill use RETVAL to hold the return value of the C library function being
1N/Acalled. In simple cases the value of RETVAL will be placed in ST(0) of
1N/Athe argument stack where it can be received by Perl as the return value
1N/Aof the XSUB.
1N/A
1N/AIf the XSUB has a return type of C<void> then the compiler will
1N/Anot declare a RETVAL variable for that function. When using
1N/Aa PPCODE: section no manipulation of the RETVAL variable is required, the
1N/Asection may use direct stack manipulation to place output values on the stack.
1N/A
1N/AIf PPCODE: directive is not used, C<void> return value should be used
1N/Aonly for subroutines which do not return a value, I<even if> CODE:
1N/Adirective is used which sets ST(0) explicitly.
1N/A
1N/AOlder versions of this document recommended to use C<void> return
1N/Avalue in such cases. It was discovered that this could lead to
1N/Asegfaults in cases when XSUB was I<truly> C<void>. This practice is
1N/Anow deprecated, and may be not supported at some future version. Use
1N/Athe return value C<SV *> in such cases. (Currently C<xsubpp> contains
1N/Asome heuristic code which tries to disambiguate between "truly-void"
1N/Aand "old-practice-declared-as-void" functions. Hence your code is at
1N/Amercy of this heuristics unless you use C<SV *> as return value.)
1N/A
1N/A=head2 Returning SVs, AVs and HVs through RETVAL
1N/A
1N/AWhen you're using RETVAL to return an C<SV *>, there's some magic
1N/Agoing on behind the scenes that should be mentioned. When you're
1N/Amanipulating the argument stack using the ST(x) macro, for example,
1N/Ayou usually have to pay special attention to reference counts. (For
1N/Amore about reference counts, see L<perlguts>.) To make your life
1N/Aeasier, the typemap file automatically makes C<RETVAL> mortal when
1N/Ayou're returning an C<SV *>. Thus, the following two XSUBs are more
1N/Aor less equivalent:
1N/A
1N/A void
1N/A alpha()
1N/A PPCODE:
1N/A ST(0) = newSVpv("Hello World",0);
1N/A sv_2mortal(ST(0));
1N/A XSRETURN(1);
1N/A
1N/A SV *
1N/A beta()
1N/A CODE:
1N/A RETVAL = newSVpv("Hello World",0);
1N/A OUTPUT:
1N/A RETVAL
1N/A
1N/AThis is quite useful as it usually improves readability. While
1N/Athis works fine for an C<SV *>, it's unfortunately not as easy
1N/Ato have C<AV *> or C<HV *> as a return value. You I<should> be
1N/Aable to write:
1N/A
1N/A AV *
1N/A array()
1N/A CODE:
1N/A RETVAL = newAV();
1N/A /* do something with RETVAL */
1N/A OUTPUT:
1N/A RETVAL
1N/A
1N/ABut due to an unfixable bug (fixing it would break lots of existing
1N/ACPAN modules) in the typemap file, the reference count of the C<AV *>
1N/Ais not properly decremented. Thus, the above XSUB would leak memory
1N/Awhenever it is being called. The same problem exists for C<HV *>.
1N/A
1N/AWhen you're returning an C<AV *> or a C<HV *>, you have make sure
1N/Atheir reference count is decremented by making the AV or HV mortal:
1N/A
1N/A AV *
1N/A array()
1N/A CODE:
1N/A RETVAL = newAV();
1N/A sv_2mortal((SV*)RETVAL);
1N/A /* do something with RETVAL */
1N/A OUTPUT:
1N/A RETVAL
1N/A
1N/AAnd also remember that you don't have to do this for an C<SV *>.
1N/A
1N/A=head2 The MODULE Keyword
1N/A
1N/AThe MODULE keyword is used to start the XS code and to specify the package
1N/Aof the functions which are being defined. All text preceding the first
1N/AMODULE keyword is considered C code and is passed through to the output with
1N/APOD stripped, but otherwise untouched. Every XS module will have a
1N/Abootstrap function which is used to hook the XSUBs into Perl. The package
1N/Aname of this bootstrap function will match the value of the last MODULE
1N/Astatement in the XS source files. The value of MODULE should always remain
1N/Aconstant within the same XS file, though this is not required.
1N/A
1N/AThe following example will start the XS code and will place
1N/Aall functions in a package named RPC.
1N/A
1N/A MODULE = RPC
1N/A
1N/A=head2 The PACKAGE Keyword
1N/A
1N/AWhen functions within an XS source file must be separated into packages
1N/Athe PACKAGE keyword should be used. This keyword is used with the MODULE
1N/Akeyword and must follow immediately after it when used.
1N/A
1N/A MODULE = RPC PACKAGE = RPC
1N/A
1N/A [ XS code in package RPC ]
1N/A
1N/A MODULE = RPC PACKAGE = RPCB
1N/A
1N/A [ XS code in package RPCB ]
1N/A
1N/A MODULE = RPC PACKAGE = RPC
1N/A
1N/A [ XS code in package RPC ]
1N/A
1N/AThe same package name can be used more than once, allowing for
1N/Anon-contiguous code. This is useful if you have a stronger ordering
1N/Aprinciple than package names.
1N/A
1N/AAlthough this keyword is optional and in some cases provides redundant
1N/Ainformation it should always be used. This keyword will ensure that the
1N/AXSUBs appear in the desired package.
1N/A
1N/A=head2 The PREFIX Keyword
1N/A
1N/AThe PREFIX keyword designates prefixes which should be
1N/Aremoved from the Perl function names. If the C function is
1N/AC<rpcb_gettime()> and the PREFIX value is C<rpcb_> then Perl will
1N/Asee this function as C<gettime()>.
1N/A
1N/AThis keyword should follow the PACKAGE keyword when used.
1N/AIf PACKAGE is not used then PREFIX should follow the MODULE
1N/Akeyword.
1N/A
1N/A MODULE = RPC PREFIX = rpc_
1N/A
1N/A MODULE = RPC PACKAGE = RPCB PREFIX = rpcb_
1N/A
1N/A=head2 The OUTPUT: Keyword
1N/A
1N/AThe OUTPUT: keyword indicates that certain function parameters should be
1N/Aupdated (new values made visible to Perl) when the XSUB terminates or that
1N/Acertain values should be returned to the calling Perl function. For
1N/Asimple functions which have no CODE: or PPCODE: section,
1N/Asuch as the sin() function above, the RETVAL variable is
1N/Aautomatically designated as an output value. For more complex functions
1N/Athe B<xsubpp> compiler will need help to determine which variables are output
1N/Avariables.
1N/A
1N/AThis keyword will normally be used to complement the CODE: keyword.
1N/AThe RETVAL variable is not recognized as an output variable when the
1N/ACODE: keyword is present. The OUTPUT: keyword is used in this
1N/Asituation to tell the compiler that RETVAL really is an output
1N/Avariable.
1N/A
1N/AThe OUTPUT: keyword can also be used to indicate that function parameters
1N/Aare output variables. This may be necessary when a parameter has been
1N/Amodified within the function and the programmer would like the update to
1N/Abe seen by Perl.
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A char *host
1N/A time_t &timep
1N/A OUTPUT:
1N/A timep
1N/A
1N/AThe OUTPUT: keyword will also allow an output parameter to
1N/Abe mapped to a matching piece of code rather than to a
1N/Atypemap.
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A char *host
1N/A time_t &timep
1N/A OUTPUT:
1N/A timep sv_setnv(ST(1), (double)timep);
1N/A
1N/AB<xsubpp> emits an automatic C<SvSETMAGIC()> for all parameters in the
1N/AOUTPUT section of the XSUB, except RETVAL. This is the usually desired
1N/Abehavior, as it takes care of properly invoking 'set' magic on output
1N/Aparameters (needed for hash or array element parameters that must be
1N/Acreated if they didn't exist). If for some reason, this behavior is
1N/Anot desired, the OUTPUT section may contain a C<SETMAGIC: DISABLE> line
1N/Ato disable it for the remainder of the parameters in the OUTPUT section.
1N/ALikewise, C<SETMAGIC: ENABLE> can be used to reenable it for the
1N/Aremainder of the OUTPUT section. See L<perlguts> for more details
1N/Aabout 'set' magic.
1N/A
1N/A=head2 The NO_OUTPUT Keyword
1N/A
1N/AThe NO_OUTPUT can be placed as the first token of the XSUB. This keyword
1N/Aindicates that while the C subroutine we provide an interface to has
1N/Aa non-C<void> return type, the return value of this C subroutine should not
1N/Abe returned from the generated Perl subroutine.
1N/A
1N/AWith this keyword present L<The RETVAL Variable> is created, and in the
1N/Agenerated call to the subroutine this variable is assigned to, but the value
1N/Aof this variable is not going to be used in the auto-generated code.
1N/A
1N/AThis keyword makes sense only if C<RETVAL> is going to be accessed by the
1N/Auser-supplied code. It is especially useful to make a function interface
1N/Amore Perl-like, especially when the C return value is just an error condition
1N/Aindicator. For example,
1N/A
1N/A NO_OUTPUT int
1N/A delete_file(char *name)
1N/A POSTCALL:
1N/A if (RETVAL != 0)
1N/A croak("Error %d while deleting file '%s'", RETVAL, name);
1N/A
1N/AHere the generated XS function returns nothing on success, and will die()
1N/Awith a meaningful error message on error.
1N/A
1N/A=head2 The CODE: Keyword
1N/A
1N/AThis keyword is used in more complicated XSUBs which require
1N/Aspecial handling for the C function. The RETVAL variable is
1N/Astill declared, but it will not be returned unless it is specified
1N/Ain the OUTPUT: section.
1N/A
1N/AThe following XSUB is for a C function which requires special handling of
1N/Aits parameters. The Perl usage is given first.
1N/A
1N/A $status = rpcb_gettime( "localhost", $timep );
1N/A
1N/AThe XSUB follows.
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A char *host
1N/A time_t timep
1N/A CODE:
1N/A RETVAL = rpcb_gettime( host, &timep );
1N/A OUTPUT:
1N/A timep
1N/A RETVAL
1N/A
1N/A=head2 The INIT: Keyword
1N/A
1N/AThe INIT: keyword allows initialization to be inserted into the XSUB before
1N/Athe compiler generates the call to the C function. Unlike the CODE: keyword
1N/Aabove, this keyword does not affect the way the compiler handles RETVAL.
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A char *host
1N/A time_t &timep
1N/A INIT:
1N/A printf("# Host is %s\n", host );
1N/A OUTPUT:
1N/A timep
1N/A
1N/AAnother use for the INIT: section is to check for preconditions before
1N/Amaking a call to the C function:
1N/A
1N/A long long
1N/A lldiv(a,b)
1N/A long long a
1N/A long long b
1N/A INIT:
1N/A if (a == 0 && b == 0)
1N/A XSRETURN_UNDEF;
1N/A if (b == 0)
1N/A croak("lldiv: cannot divide by 0");
1N/A
1N/A=head2 The NO_INIT Keyword
1N/A
1N/AThe NO_INIT keyword is used to indicate that a function
1N/Aparameter is being used only as an output value. The B<xsubpp>
1N/Acompiler will normally generate code to read the values of
1N/Aall function parameters from the argument stack and assign
1N/Athem to C variables upon entry to the function. NO_INIT
1N/Awill tell the compiler that some parameters will be used for
1N/Aoutput rather than for input and that they will be handled
1N/Abefore the function terminates.
1N/A
1N/AThe following example shows a variation of the rpcb_gettime() function.
1N/AThis function uses the timep variable only as an output variable and does
1N/Anot care about its initial contents.
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A char *host
1N/A time_t &timep = NO_INIT
1N/A OUTPUT:
1N/A timep
1N/A
1N/A=head2 Initializing Function Parameters
1N/A
1N/AC function parameters are normally initialized with their values from
1N/Athe argument stack (which in turn contains the parameters that were
1N/Apassed to the XSUB from Perl). The typemaps contain the
1N/Acode segments which are used to translate the Perl values to
1N/Athe C parameters. The programmer, however, is allowed to
1N/Aoverride the typemaps and supply alternate (or additional)
1N/Ainitialization code. Initialization code starts with the first
1N/AC<=>, C<;> or C<+> on a line in the INPUT: section. The only
1N/Aexception happens if this C<;> terminates the line, then this C<;>
1N/Ais quietly ignored.
1N/A
1N/AThe following code demonstrates how to supply initialization code for
1N/Afunction parameters. The initialization code is eval'd within double
1N/Aquotes by the compiler before it is added to the output so anything
1N/Awhich should be interpreted literally [mainly C<$>, C<@>, or C<\\>]
1N/Amust be protected with backslashes. The variables $var, $arg,
1N/Aand $type can be used as in typemaps.
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A char *host = (char *)SvPV($arg,PL_na);
1N/A time_t &timep = 0;
1N/A OUTPUT:
1N/A timep
1N/A
1N/AThis should not be used to supply default values for parameters. One
1N/Awould normally use this when a function parameter must be processed by
1N/Aanother library function before it can be used. Default parameters are
1N/Acovered in the next section.
1N/A
1N/AIf the initialization begins with C<=>, then it is output in
1N/Athe declaration for the input variable, replacing the initialization
1N/Asupplied by the typemap. If the initialization
1N/Abegins with C<;> or C<+>, then it is performed after
1N/Aall of the input variables have been declared. In the C<;>
1N/Acase the initialization normally supplied by the typemap is not performed.
1N/AFor the C<+> case, the declaration for the variable will include the
1N/Ainitialization from the typemap. A global
1N/Avariable, C<%v>, is available for the truly rare case where
1N/Ainformation from one initialization is needed in another
1N/Ainitialization.
1N/A
1N/AHere's a truly obscure example:
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A time_t &timep ; /* \$v{timep}=@{[$v{timep}=$arg]} */
1N/A char *host + SvOK($v{timep}) ? SvPV($arg,PL_na) : NULL;
1N/A OUTPUT:
1N/A timep
1N/A
1N/AThe construct C<\$v{timep}=@{[$v{timep}=$arg]}> used in the above
1N/Aexample has a two-fold purpose: first, when this line is processed by
1N/AB<xsubpp>, the Perl snippet C<$v{timep}=$arg> is evaluated. Second,
1N/Athe text of the evaluated snippet is output into the generated C file
1N/A(inside a C comment)! During the processing of C<char *host> line,
1N/A$arg will evaluate to C<ST(0)>, and C<$v{timep}> will evaluate to
1N/AC<ST(1)>.
1N/A
1N/A=head2 Default Parameter Values
1N/A
1N/ADefault values for XSUB arguments can be specified by placing an
1N/Aassignment statement in the parameter list. The default value may
1N/Abe a number, a string or the special string C<NO_INIT>. Defaults should
1N/Aalways be used on the right-most parameters only.
1N/A
1N/ATo allow the XSUB for rpcb_gettime() to have a default host
1N/Avalue the parameters to the XSUB could be rearranged. The
1N/AXSUB will then call the real rpcb_gettime() function with
1N/Athe parameters in the correct order. This XSUB can be called
1N/Afrom Perl with either of the following statements:
1N/A
1N/A $status = rpcb_gettime( $timep, $host );
1N/A
1N/A $status = rpcb_gettime( $timep );
1N/A
1N/AThe XSUB will look like the code which follows. A CODE:
1N/Ablock is used to call the real rpcb_gettime() function with
1N/Athe parameters in the correct order for that function.
1N/A
1N/A bool_t
1N/A rpcb_gettime(timep,host="localhost")
1N/A char *host
1N/A time_t timep = NO_INIT
1N/A CODE:
1N/A RETVAL = rpcb_gettime( host, &timep );
1N/A OUTPUT:
1N/A timep
1N/A RETVAL
1N/A
1N/A=head2 The PREINIT: Keyword
1N/A
1N/AThe PREINIT: keyword allows extra variables to be declared immediately
1N/Abefore or after the declarations of the parameters from the INPUT: section
1N/Aare emitted.
1N/A
1N/AIf a variable is declared inside a CODE: section it will follow any typemap
1N/Acode that is emitted for the input parameters. This may result in the
1N/Adeclaration ending up after C code, which is C syntax error. Similar
1N/Aerrors may happen with an explicit C<;>-type or C<+>-type initialization of
1N/Aparameters is used (see L<"Initializing Function Parameters">). Declaring
1N/Athese variables in an INIT: section will not help.
1N/A
1N/AIn such cases, to force an additional variable to be declared together
1N/Awith declarations of other variables, place the declaration into a
1N/APREINIT: section. The PREINIT: keyword may be used one or more times
1N/Awithin an XSUB.
1N/A
1N/AThe following examples are equivalent, but if the code is using complex
1N/Atypemaps then the first example is safer.
1N/A
1N/A bool_t
1N/A rpcb_gettime(timep)
1N/A time_t timep = NO_INIT
1N/A PREINIT:
1N/A char *host = "localhost";
1N/A CODE:
1N/A RETVAL = rpcb_gettime( host, &timep );
1N/A OUTPUT:
1N/A timep
1N/A RETVAL
1N/A
1N/AFor this particular case an INIT: keyword would generate the
1N/Asame C code as the PREINIT: keyword. Another correct, but error-prone example:
1N/A
1N/A bool_t
1N/A rpcb_gettime(timep)
1N/A time_t timep = NO_INIT
1N/A CODE:
1N/A char *host = "localhost";
1N/A RETVAL = rpcb_gettime( host, &timep );
1N/A OUTPUT:
1N/A timep
1N/A RETVAL
1N/A
1N/AAnother way to declare C<host> is to use a C block in the CODE: section:
1N/A
1N/A bool_t
1N/A rpcb_gettime(timep)
1N/A time_t timep = NO_INIT
1N/A CODE:
1N/A {
1N/A char *host = "localhost";
1N/A RETVAL = rpcb_gettime( host, &timep );
1N/A }
1N/A OUTPUT:
1N/A timep
1N/A RETVAL
1N/A
1N/AThe ability to put additional declarations before the typemap entries are
1N/Aprocessed is very handy in the cases when typemap conversions manipulate
1N/Asome global state:
1N/A
1N/A MyObject
1N/A mutate(o)
1N/A PREINIT:
1N/A MyState st = global_state;
1N/A INPUT:
1N/A MyObject o;
1N/A CLEANUP:
1N/A reset_to(global_state, st);
1N/A
1N/AHere we suppose that conversion to C<MyObject> in the INPUT: section and from
1N/AMyObject when processing RETVAL will modify a global variable C<global_state>.
1N/AAfter these conversions are performed, we restore the old value of
1N/AC<global_state> (to avoid memory leaks, for example).
1N/A
1N/AThere is another way to trade clarity for compactness: INPUT sections allow
1N/Adeclaration of C variables which do not appear in the parameter list of
1N/Aa subroutine. Thus the above code for mutate() can be rewritten as
1N/A
1N/A MyObject
1N/A mutate(o)
1N/A MyState st = global_state;
1N/A MyObject o;
1N/A CLEANUP:
1N/A reset_to(global_state, st);
1N/A
1N/Aand the code for rpcb_gettime() can be rewritten as
1N/A
1N/A bool_t
1N/A rpcb_gettime(timep)
1N/A time_t timep = NO_INIT
1N/A char *host = "localhost";
1N/A C_ARGS:
1N/A host, &timep
1N/A OUTPUT:
1N/A timep
1N/A RETVAL
1N/A
1N/A=head2 The SCOPE: Keyword
1N/A
1N/AThe SCOPE: keyword allows scoping to be enabled for a particular XSUB. If
1N/Aenabled, the XSUB will invoke ENTER and LEAVE automatically.
1N/A
1N/ATo support potentially complex type mappings, if a typemap entry used
1N/Aby an XSUB contains a comment like C</*scope*/> then scoping will
1N/Abe automatically enabled for that XSUB.
1N/A
1N/ATo enable scoping:
1N/A
1N/A SCOPE: ENABLE
1N/A
1N/ATo disable scoping:
1N/A
1N/A SCOPE: DISABLE
1N/A
1N/A=head2 The INPUT: Keyword
1N/A
1N/AThe XSUB's parameters are usually evaluated immediately after entering the
1N/AXSUB. The INPUT: keyword can be used to force those parameters to be
1N/Aevaluated a little later. The INPUT: keyword can be used multiple times
1N/Awithin an XSUB and can be used to list one or more input variables. This
1N/Akeyword is used with the PREINIT: keyword.
1N/A
1N/AThe following example shows how the input parameter C<timep> can be
1N/Aevaluated late, after a PREINIT.
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A char *host
1N/A PREINIT:
1N/A time_t tt;
1N/A INPUT:
1N/A time_t timep
1N/A CODE:
1N/A RETVAL = rpcb_gettime( host, &tt );
1N/A timep = tt;
1N/A OUTPUT:
1N/A timep
1N/A RETVAL
1N/A
1N/AThe next example shows each input parameter evaluated late.
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A PREINIT:
1N/A time_t tt;
1N/A INPUT:
1N/A char *host
1N/A PREINIT:
1N/A char *h;
1N/A INPUT:
1N/A time_t timep
1N/A CODE:
1N/A h = host;
1N/A RETVAL = rpcb_gettime( h, &tt );
1N/A timep = tt;
1N/A OUTPUT:
1N/A timep
1N/A RETVAL
1N/A
1N/ASince INPUT sections allow declaration of C variables which do not appear
1N/Ain the parameter list of a subroutine, this may be shortened to:
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A time_t tt;
1N/A char *host;
1N/A char *h = host;
1N/A time_t timep;
1N/A CODE:
1N/A RETVAL = rpcb_gettime( h, &tt );
1N/A timep = tt;
1N/A OUTPUT:
1N/A timep
1N/A RETVAL
1N/A
1N/A(We used our knowledge that input conversion for C<char *> is a "simple" one,
1N/Athus C<host> is initialized on the declaration line, and our assignment
1N/AC<h = host> is not performed too early. Otherwise one would need to have the
1N/Aassignment C<h = host> in a CODE: or INIT: section.)
1N/A
1N/A=head2 The IN/OUTLIST/IN_OUTLIST/OUT/IN_OUT Keywords
1N/A
1N/AIn the list of parameters for an XSUB, one can precede parameter names
1N/Aby the C<IN>/C<OUTLIST>/C<IN_OUTLIST>/C<OUT>/C<IN_OUT> keywords.
1N/AC<IN> keyword is the default, the other keywords indicate how the Perl
1N/Ainterface should differ from the C interface.
1N/A
1N/AParameters preceded by C<OUTLIST>/C<IN_OUTLIST>/C<OUT>/C<IN_OUT>
1N/Akeywords are considered to be used by the C subroutine I<via
1N/Apointers>. C<OUTLIST>/C<OUT> keywords indicate that the C subroutine
1N/Adoes not inspect the memory pointed by this parameter, but will write
1N/Athrough this pointer to provide additional return values.
1N/A
1N/AParameters preceded by C<OUTLIST> keyword do not appear in the usage
1N/Asignature of the generated Perl function.
1N/A
1N/AParameters preceded by C<IN_OUTLIST>/C<IN_OUT>/C<OUT> I<do> appear as
1N/Aparameters to the Perl function. With the exception of
1N/AC<OUT>-parameters, these parameters are converted to the corresponding
1N/AC type, then pointers to these data are given as arguments to the C
1N/Afunction. It is expected that the C function will write through these
1N/Apointers.
1N/A
1N/AThe return list of the generated Perl function consists of the C return value
1N/Afrom the function (unless the XSUB is of C<void> return type or
1N/AC<The NO_OUTPUT Keyword> was used) followed by all the C<OUTLIST>
1N/Aand C<IN_OUTLIST> parameters (in the order of appearance). On the
1N/Areturn from the XSUB the C<IN_OUT>/C<OUT> Perl parameter will be
1N/Amodified to have the values written by the C function.
1N/A
1N/AFor example, an XSUB
1N/A
1N/A void
1N/A day_month(OUTLIST day, IN unix_time, OUTLIST month)
1N/A int day
1N/A int unix_time
1N/A int month
1N/A
1N/Ashould be used from Perl as
1N/A
1N/A my ($day, $month) = day_month(time);
1N/A
1N/AThe C signature of the corresponding function should be
1N/A
1N/A void day_month(int *day, int unix_time, int *month);
1N/A
1N/AThe C<IN>/C<OUTLIST>/C<IN_OUTLIST>/C<IN_OUT>/C<OUT> keywords can be
1N/Amixed with ANSI-style declarations, as in
1N/A
1N/A void
1N/A day_month(OUTLIST int day, int unix_time, OUTLIST int month)
1N/A
1N/A(here the optional C<IN> keyword is omitted).
1N/A
1N/AThe C<IN_OUT> parameters are identical with parameters introduced with
1N/AL<The & Unary Operator> and put into the C<OUTPUT:> section (see
1N/AL<The OUTPUT: Keyword>). The C<IN_OUTLIST> parameters are very similar,
1N/Athe only difference being that the value C function writes through the
1N/Apointer would not modify the Perl parameter, but is put in the output
1N/Alist.
1N/A
1N/AThe C<OUTLIST>/C<OUT> parameter differ from C<IN_OUTLIST>/C<IN_OUT>
1N/Aparameters only by the initial value of the Perl parameter not
1N/Abeing read (and not being given to the C function - which gets some
1N/Agarbage instead). For example, the same C function as above can be
1N/Ainterfaced with as
1N/A
1N/A void day_month(OUT int day, int unix_time, OUT int month);
1N/A
1N/Aor
1N/A
1N/A void
1N/A day_month(day, unix_time, month)
1N/A int &day = NO_INIT
1N/A int unix_time
1N/A int &month = NO_INIT
1N/A OUTPUT:
1N/A day
1N/A month
1N/A
1N/AHowever, the generated Perl function is called in very C-ish style:
1N/A
1N/A my ($day, $month);
1N/A day_month($day, time, $month);
1N/A
1N/A=head2 The C<length(NAME)> Keyword
1N/A
1N/AIf one of the input arguments to the C function is the length of a string
1N/Aargument C<NAME>, one can substitute the name of the length-argument by
1N/AC<length(NAME)> in the XSUB declaration. This argument must be omited when
1N/Athe generated Perl function is called. E.g.,
1N/A
1N/A void
1N/A dump_chars(char *s, short l)
1N/A {
1N/A short n = 0;
1N/A while (n < l) {
1N/A printf("s[%d] = \"\\%#03o\"\n", n, (int)s[n]);
1N/A n++;
1N/A }
1N/A }
1N/A
1N/A MODULE = x PACKAGE = x
1N/A
1N/A void dump_chars(char *s, short length(s))
1N/A
1N/Ashould be called as C<dump_chars($string)>.
1N/A
1N/AThis directive is supported with ANSI-type function declarations only.
1N/A
1N/A=head2 Variable-length Parameter Lists
1N/A
1N/AXSUBs can have variable-length parameter lists by specifying an ellipsis
1N/AC<(...)> in the parameter list. This use of the ellipsis is similar to that
1N/Afound in ANSI C. The programmer is able to determine the number of
1N/Aarguments passed to the XSUB by examining the C<items> variable which the
1N/AB<xsubpp> compiler supplies for all XSUBs. By using this mechanism one can
1N/Acreate an XSUB which accepts a list of parameters of unknown length.
1N/A
1N/AThe I<host> parameter for the rpcb_gettime() XSUB can be
1N/Aoptional so the ellipsis can be used to indicate that the
1N/AXSUB will take a variable number of parameters. Perl should
1N/Abe able to call this XSUB with either of the following statements.
1N/A
1N/A $status = rpcb_gettime( $timep, $host );
1N/A
1N/A $status = rpcb_gettime( $timep );
1N/A
1N/AThe XS code, with ellipsis, follows.
1N/A
1N/A bool_t
1N/A rpcb_gettime(timep, ...)
1N/A time_t timep = NO_INIT
1N/A PREINIT:
1N/A char *host = "localhost";
1N/A STRLEN n_a;
1N/A CODE:
1N/A if( items > 1 )
1N/A host = (char *)SvPV(ST(1), n_a);
1N/A RETVAL = rpcb_gettime( host, &timep );
1N/A OUTPUT:
1N/A timep
1N/A RETVAL
1N/A
1N/A=head2 The C_ARGS: Keyword
1N/A
1N/AThe C_ARGS: keyword allows creating of XSUBS which have different
1N/Acalling sequence from Perl than from C, without a need to write
1N/ACODE: or PPCODE: section. The contents of the C_ARGS: paragraph is
1N/Aput as the argument to the called C function without any change.
1N/A
1N/AFor example, suppose that a C function is declared as
1N/A
1N/A symbolic nth_derivative(int n, symbolic function, int flags);
1N/A
1N/Aand that the default flags are kept in a global C variable
1N/AC<default_flags>. Suppose that you want to create an interface which
1N/Ais called as
1N/A
1N/A $second_deriv = $function->nth_derivative(2);
1N/A
1N/ATo do this, declare the XSUB as
1N/A
1N/A symbolic
1N/A nth_derivative(function, n)
1N/A symbolic function
1N/A int n
1N/A C_ARGS:
1N/A n, function, default_flags
1N/A
1N/A=head2 The PPCODE: Keyword
1N/A
1N/AThe PPCODE: keyword is an alternate form of the CODE: keyword and is used
1N/Ato tell the B<xsubpp> compiler that the programmer is supplying the code to
1N/Acontrol the argument stack for the XSUBs return values. Occasionally one
1N/Awill want an XSUB to return a list of values rather than a single value.
1N/AIn these cases one must use PPCODE: and then explicitly push the list of
1N/Avalues on the stack. The PPCODE: and CODE: keywords should not be used
1N/Atogether within the same XSUB.
1N/A
1N/AThe actual difference between PPCODE: and CODE: sections is in the
1N/Ainitialization of C<SP> macro (which stands for the I<current> Perl
1N/Astack pointer), and in the handling of data on the stack when returning
1N/Afrom an XSUB. In CODE: sections SP preserves the value which was on
1N/Aentry to the XSUB: SP is on the function pointer (which follows the
1N/Alast parameter). In PPCODE: sections SP is moved backward to the
1N/Abeginning of the parameter list, which allows C<PUSH*()> macros
1N/Ato place output values in the place Perl expects them to be when
1N/Athe XSUB returns back to Perl.
1N/A
1N/AThe generated trailer for a CODE: section ensures that the number of return
1N/Avalues Perl will see is either 0 or 1 (depending on the C<void>ness of the
1N/Areturn value of the C function, and heuristics mentioned in
1N/AL<"The RETVAL Variable">). The trailer generated for a PPCODE: section
1N/Ais based on the number of return values and on the number of times
1N/AC<SP> was updated by C<[X]PUSH*()> macros.
1N/A
1N/ANote that macros C<ST(i)>, C<XST_m*()> and C<XSRETURN*()> work equally
1N/Awell in CODE: sections and PPCODE: sections.
1N/A
1N/AThe following XSUB will call the C rpcb_gettime() function
1N/Aand will return its two output values, timep and status, to
1N/APerl as a single list.
1N/A
1N/A void
1N/A rpcb_gettime(host)
1N/A char *host
1N/A PREINIT:
1N/A time_t timep;
1N/A bool_t status;
1N/A PPCODE:
1N/A status = rpcb_gettime( host, &timep );
1N/A EXTEND(SP, 2);
1N/A PUSHs(sv_2mortal(newSViv(status)));
1N/A PUSHs(sv_2mortal(newSViv(timep)));
1N/A
1N/ANotice that the programmer must supply the C code necessary
1N/Ato have the real rpcb_gettime() function called and to have
1N/Athe return values properly placed on the argument stack.
1N/A
1N/AThe C<void> return type for this function tells the B<xsubpp> compiler that
1N/Athe RETVAL variable is not needed or used and that it should not be created.
1N/AIn most scenarios the void return type should be used with the PPCODE:
1N/Adirective.
1N/A
1N/AThe EXTEND() macro is used to make room on the argument
1N/Astack for 2 return values. The PPCODE: directive causes the
1N/AB<xsubpp> compiler to create a stack pointer available as C<SP>, and it
1N/Ais this pointer which is being used in the EXTEND() macro.
1N/AThe values are then pushed onto the stack with the PUSHs()
1N/Amacro.
1N/A
1N/ANow the rpcb_gettime() function can be used from Perl with
1N/Athe following statement.
1N/A
1N/A ($status, $timep) = rpcb_gettime("localhost");
1N/A
1N/AWhen handling output parameters with a PPCODE section, be sure to handle
1N/A'set' magic properly. See L<perlguts> for details about 'set' magic.
1N/A
1N/A=head2 Returning Undef And Empty Lists
1N/A
1N/AOccasionally the programmer will want to return simply
1N/AC<undef> or an empty list if a function fails rather than a
1N/Aseparate status value. The rpcb_gettime() function offers
1N/Ajust this situation. If the function succeeds we would like
1N/Ato have it return the time and if it fails we would like to
1N/Ahave undef returned. In the following Perl code the value
1N/Aof $timep will either be undef or it will be a valid time.
1N/A
1N/A $timep = rpcb_gettime( "localhost" );
1N/A
1N/AThe following XSUB uses the C<SV *> return type as a mnemonic only,
1N/Aand uses a CODE: block to indicate to the compiler
1N/Athat the programmer has supplied all the necessary code. The
1N/Asv_newmortal() call will initialize the return value to undef, making that
1N/Athe default return value.
1N/A
1N/A SV *
1N/A rpcb_gettime(host)
1N/A char * host
1N/A PREINIT:
1N/A time_t timep;
1N/A bool_t x;
1N/A CODE:
1N/A ST(0) = sv_newmortal();
1N/A if( rpcb_gettime( host, &timep ) )
1N/A sv_setnv( ST(0), (double)timep);
1N/A
1N/AThe next example demonstrates how one would place an explicit undef in the
1N/Areturn value, should the need arise.
1N/A
1N/A SV *
1N/A rpcb_gettime(host)
1N/A char * host
1N/A PREINIT:
1N/A time_t timep;
1N/A bool_t x;
1N/A CODE:
1N/A ST(0) = sv_newmortal();
1N/A if( rpcb_gettime( host, &timep ) ){
1N/A sv_setnv( ST(0), (double)timep);
1N/A }
1N/A else{
1N/A ST(0) = &PL_sv_undef;
1N/A }
1N/A
1N/ATo return an empty list one must use a PPCODE: block and
1N/Athen not push return values on the stack.
1N/A
1N/A void
1N/A rpcb_gettime(host)
1N/A char *host
1N/A PREINIT:
1N/A time_t timep;
1N/A PPCODE:
1N/A if( rpcb_gettime( host, &timep ) )
1N/A PUSHs(sv_2mortal(newSViv(timep)));
1N/A else{
1N/A /* Nothing pushed on stack, so an empty
1N/A * list is implicitly returned. */
1N/A }
1N/A
1N/ASome people may be inclined to include an explicit C<return> in the above
1N/AXSUB, rather than letting control fall through to the end. In those
1N/Asituations C<XSRETURN_EMPTY> should be used, instead. This will ensure that
1N/Athe XSUB stack is properly adjusted. Consult L<perlapi> for other
1N/AC<XSRETURN> macros.
1N/A
1N/ASince C<XSRETURN_*> macros can be used with CODE blocks as well, one can
1N/Arewrite this example as:
1N/A
1N/A int
1N/A rpcb_gettime(host)
1N/A char *host
1N/A PREINIT:
1N/A time_t timep;
1N/A CODE:
1N/A RETVAL = rpcb_gettime( host, &timep );
1N/A if (RETVAL == 0)
1N/A XSRETURN_UNDEF;
1N/A OUTPUT:
1N/A RETVAL
1N/A
1N/AIn fact, one can put this check into a POSTCALL: section as well. Together
1N/Awith PREINIT: simplifications, this leads to:
1N/A
1N/A int
1N/A rpcb_gettime(host)
1N/A char *host
1N/A time_t timep;
1N/A POSTCALL:
1N/A if (RETVAL == 0)
1N/A XSRETURN_UNDEF;
1N/A
1N/A=head2 The REQUIRE: Keyword
1N/A
1N/AThe REQUIRE: keyword is used to indicate the minimum version of the
1N/AB<xsubpp> compiler needed to compile the XS module. An XS module which
1N/Acontains the following statement will compile with only B<xsubpp> version
1N/A1.922 or greater:
1N/A
1N/A REQUIRE: 1.922
1N/A
1N/A=head2 The CLEANUP: Keyword
1N/A
1N/AThis keyword can be used when an XSUB requires special cleanup procedures
1N/Abefore it terminates. When the CLEANUP: keyword is used it must follow
1N/Aany CODE:, PPCODE:, or OUTPUT: blocks which are present in the XSUB. The
1N/Acode specified for the cleanup block will be added as the last statements
1N/Ain the XSUB.
1N/A
1N/A=head2 The POSTCALL: Keyword
1N/A
1N/AThis keyword can be used when an XSUB requires special procedures
1N/Aexecuted after the C subroutine call is performed. When the POSTCALL:
1N/Akeyword is used it must precede OUTPUT: and CLEANUP: blocks which are
1N/Apresent in the XSUB.
1N/A
1N/ASee examples in L<"The NO_OUTPUT Keyword"> and L<"Returning Undef And Empty Lists">.
1N/A
1N/AThe POSTCALL: block does not make a lot of sense when the C subroutine
1N/Acall is supplied by user by providing either CODE: or PPCODE: section.
1N/A
1N/A=head2 The BOOT: Keyword
1N/A
1N/AThe BOOT: keyword is used to add code to the extension's bootstrap
1N/Afunction. The bootstrap function is generated by the B<xsubpp> compiler and
1N/Anormally holds the statements necessary to register any XSUBs with Perl.
1N/AWith the BOOT: keyword the programmer can tell the compiler to add extra
1N/Astatements to the bootstrap function.
1N/A
1N/AThis keyword may be used any time after the first MODULE keyword and should
1N/Aappear on a line by itself. The first blank line after the keyword will
1N/Aterminate the code block.
1N/A
1N/A BOOT:
1N/A # The following message will be printed when the
1N/A # bootstrap function executes.
1N/A printf("Hello from the bootstrap!\n");
1N/A
1N/A=head2 The VERSIONCHECK: Keyword
1N/A
1N/AThe VERSIONCHECK: keyword corresponds to B<xsubpp>'s C<-versioncheck> and
1N/AC<-noversioncheck> options. This keyword overrides the command line
1N/Aoptions. Version checking is enabled by default. When version checking is
1N/Aenabled the XS module will attempt to verify that its version matches the
1N/Aversion of the PM module.
1N/A
1N/ATo enable version checking:
1N/A
1N/A VERSIONCHECK: ENABLE
1N/A
1N/ATo disable version checking:
1N/A
1N/A VERSIONCHECK: DISABLE
1N/A
1N/A=head2 The PROTOTYPES: Keyword
1N/A
1N/AThe PROTOTYPES: keyword corresponds to B<xsubpp>'s C<-prototypes> and
1N/AC<-noprototypes> options. This keyword overrides the command line options.
1N/APrototypes are enabled by default. When prototypes are enabled XSUBs will
1N/Abe given Perl prototypes. This keyword may be used multiple times in an XS
1N/Amodule to enable and disable prototypes for different parts of the module.
1N/A
1N/ATo enable prototypes:
1N/A
1N/A PROTOTYPES: ENABLE
1N/A
1N/ATo disable prototypes:
1N/A
1N/A PROTOTYPES: DISABLE
1N/A
1N/A=head2 The PROTOTYPE: Keyword
1N/A
1N/AThis keyword is similar to the PROTOTYPES: keyword above but can be used to
1N/Aforce B<xsubpp> to use a specific prototype for the XSUB. This keyword
1N/Aoverrides all other prototype options and keywords but affects only the
1N/Acurrent XSUB. Consult L<perlsub/Prototypes> for information about Perl
1N/Aprototypes.
1N/A
1N/A bool_t
1N/A rpcb_gettime(timep, ...)
1N/A time_t timep = NO_INIT
1N/A PROTOTYPE: $;$
1N/A PREINIT:
1N/A char *host = "localhost";
1N/A STRLEN n_a;
1N/A CODE:
1N/A if( items > 1 )
1N/A host = (char *)SvPV(ST(1), n_a);
1N/A RETVAL = rpcb_gettime( host, &timep );
1N/A OUTPUT:
1N/A timep
1N/A RETVAL
1N/A
1N/AIf the prototypes are enabled, you can disable it locally for a given
1N/AXSUB as in the following example:
1N/A
1N/A void
1N/A rpcb_gettime_noproto()
1N/A PROTOTYPE: DISABLE
1N/A ...
1N/A
1N/A=head2 The ALIAS: Keyword
1N/A
1N/AThe ALIAS: keyword allows an XSUB to have two or more unique Perl names
1N/Aand to know which of those names was used when it was invoked. The Perl
1N/Anames may be fully-qualified with package names. Each alias is given an
1N/Aindex. The compiler will setup a variable called C<ix> which contain the
1N/Aindex of the alias which was used. When the XSUB is called with its
1N/Adeclared name C<ix> will be 0.
1N/A
1N/AThe following example will create aliases C<FOO::gettime()> and
1N/AC<BAR::getit()> for this function.
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A char *host
1N/A time_t &timep
1N/A ALIAS:
1N/A FOO::gettime = 1
1N/A BAR::getit = 2
1N/A INIT:
1N/A printf("# ix = %d\n", ix );
1N/A OUTPUT:
1N/A timep
1N/A
1N/A=head2 The OVERLOAD: Keyword
1N/A
1N/AInstead of writing an overloaded interface using pure Perl, you
1N/Acan also use the OVERLOAD keyword to define additional Perl names
1N/Afor your functions (like the ALIAS: keyword above). However, the
1N/Aoverloaded functions must be defined with three parameters (except
1N/Afor the nomethod() function which needs four parameters). If any
1N/Afunction has the OVERLOAD: keyword, several additional lines
1N/Awill be defined in the c file generated by xsubpp in order to
1N/Aregister with the overload magic.
1N/A
1N/ASince blessed objects are actually stored as RV's, it is useful
1N/Ato use the typemap features to preprocess parameters and extract
1N/Athe actual SV stored within the blessed RV. See the sample for
1N/AT_PTROBJ_SPECIAL below.
1N/A
1N/ATo use the OVERLOAD: keyword, create an XS function which takes
1N/Athree input parameters ( or use the c style '...' definition) like
1N/Athis:
1N/A
1N/A SV *
1N/A cmp (lobj, robj, swap)
1N/A My_Module_obj lobj
1N/A My_Module_obj robj
1N/A IV swap
1N/A OVERLOAD: cmp <=>
1N/A { /* function defined here */}
1N/A
1N/AIn this case, the function will overload both of the three way
1N/Acomparison operators. For all overload operations using non-alpha
1N/Acharacters, you must type the parameter without quoting, seperating
1N/Amultiple overloads with whitespace. Note that "" (the stringify
1N/Aoverload) should be entered as \"\" (i.e. escaped).
1N/A
1N/A=head2 The FALLBACK: Keyword
1N/A
1N/AIn addition to the OVERLOAD keyword, if you need to control how
1N/APerl autogenerates missing overloaded operators, you can set the
1N/AFALLBACK keyword in the module header section, like this:
1N/A
1N/A MODULE = RPC PACKAGE = RPC
1N/A
1N/A FALLBACK: TRUE
1N/A ...
1N/A
1N/Awhere FALLBACK can take any of the three values TRUE, FALSE, or
1N/AUNDEF. If you do not set any FALLBACK value when using OVERLOAD,
1N/Ait defaults to UNDEF. FALLBACK is not used except when one or
1N/Amore functions using OVERLOAD have been defined. Please see
1N/AL<overload/Fallback> for more details.
1N/A
1N/A=head2 The INTERFACE: Keyword
1N/A
1N/AThis keyword declares the current XSUB as a keeper of the given
1N/Acalling signature. If some text follows this keyword, it is
1N/Aconsidered as a list of functions which have this signature, and
1N/Ashould be attached to the current XSUB.
1N/A
1N/AFor example, if you have 4 C functions multiply(), divide(), add(),
1N/Asubtract() all having the signature:
1N/A
1N/A symbolic f(symbolic, symbolic);
1N/A
1N/Ayou can make them all to use the same XSUB using this:
1N/A
1N/A symbolic
1N/A interface_s_ss(arg1, arg2)
1N/A symbolic arg1
1N/A symbolic arg2
1N/A INTERFACE:
1N/A multiply divide
1N/A add subtract
1N/A
1N/A(This is the complete XSUB code for 4 Perl functions!) Four generated
1N/APerl function share names with corresponding C functions.
1N/A
1N/AThe advantage of this approach comparing to ALIAS: keyword is that there
1N/Ais no need to code a switch statement, each Perl function (which shares
1N/Athe same XSUB) knows which C function it should call. Additionally, one
1N/Acan attach an extra function remainder() at runtime by using
1N/A
1N/A CV *mycv = newXSproto("Symbolic::remainder",
1N/A XS_Symbolic_interface_s_ss, __FILE__, "$$");
1N/A XSINTERFACE_FUNC_SET(mycv, remainder);
1N/A
1N/Asay, from another XSUB. (This example supposes that there was no
1N/AINTERFACE_MACRO: section, otherwise one needs to use something else instead of
1N/AC<XSINTERFACE_FUNC_SET>, see the next section.)
1N/A
1N/A=head2 The INTERFACE_MACRO: Keyword
1N/A
1N/AThis keyword allows one to define an INTERFACE using a different way
1N/Ato extract a function pointer from an XSUB. The text which follows
1N/Athis keyword should give the name of macros which would extract/set a
1N/Afunction pointer. The extractor macro is given return type, C<CV*>,
1N/Aand C<XSANY.any_dptr> for this C<CV*>. The setter macro is given cv,
1N/Aand the function pointer.
1N/A
1N/AThe default value is C<XSINTERFACE_FUNC> and C<XSINTERFACE_FUNC_SET>.
1N/AAn INTERFACE keyword with an empty list of functions can be omitted if
1N/AINTERFACE_MACRO keyword is used.
1N/A
1N/ASuppose that in the previous example functions pointers for
1N/Amultiply(), divide(), add(), subtract() are kept in a global C array
1N/AC<fp[]> with offsets being C<multiply_off>, C<divide_off>, C<add_off>,
1N/AC<subtract_off>. Then one can use
1N/A
1N/A #define XSINTERFACE_FUNC_BYOFFSET(ret,cv,f) \
1N/A ((XSINTERFACE_CVT(ret,))fp[CvXSUBANY(cv).any_i32])
1N/A #define XSINTERFACE_FUNC_BYOFFSET_set(cv,f) \
1N/A CvXSUBANY(cv).any_i32 = CAT2( f, _off )
1N/A
1N/Ain C section,
1N/A
1N/A symbolic
1N/A interface_s_ss(arg1, arg2)
1N/A symbolic arg1
1N/A symbolic arg2
1N/A INTERFACE_MACRO:
1N/A XSINTERFACE_FUNC_BYOFFSET
1N/A XSINTERFACE_FUNC_BYOFFSET_set
1N/A INTERFACE:
1N/A multiply divide
1N/A add subtract
1N/A
1N/Ain XSUB section.
1N/A
1N/A=head2 The INCLUDE: Keyword
1N/A
1N/AThis keyword can be used to pull other files into the XS module. The other
1N/Afiles may have XS code. INCLUDE: can also be used to run a command to
1N/Agenerate the XS code to be pulled into the module.
1N/A
1N/AThe file F<Rpcb1.xsh> contains our C<rpcb_gettime()> function:
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A char *host
1N/A time_t &timep
1N/A OUTPUT:
1N/A timep
1N/A
1N/AThe XS module can use INCLUDE: to pull that file into it.
1N/A
1N/A INCLUDE: Rpcb1.xsh
1N/A
1N/AIf the parameters to the INCLUDE: keyword are followed by a pipe (C<|>) then
1N/Athe compiler will interpret the parameters as a command.
1N/A
1N/A INCLUDE: cat Rpcb1.xsh |
1N/A
1N/A=head2 The CASE: Keyword
1N/A
1N/AThe CASE: keyword allows an XSUB to have multiple distinct parts with each
1N/Apart acting as a virtual XSUB. CASE: is greedy and if it is used then all
1N/Aother XS keywords must be contained within a CASE:. This means nothing may
1N/Aprecede the first CASE: in the XSUB and anything following the last CASE: is
1N/Aincluded in that case.
1N/A
1N/AA CASE: might switch via a parameter of the XSUB, via the C<ix> ALIAS:
1N/Avariable (see L<"The ALIAS: Keyword">), or maybe via the C<items> variable
1N/A(see L<"Variable-length Parameter Lists">). The last CASE: becomes the
1N/AB<default> case if it is not associated with a conditional. The following
1N/Aexample shows CASE switched via C<ix> with a function C<rpcb_gettime()>
1N/Ahaving an alias C<x_gettime()>. When the function is called as
1N/AC<rpcb_gettime()> its parameters are the usual C<(char *host, time_t *timep)>,
1N/Abut when the function is called as C<x_gettime()> its parameters are
1N/Areversed, C<(time_t *timep, char *host)>.
1N/A
1N/A long
1N/A rpcb_gettime(a,b)
1N/A CASE: ix == 1
1N/A ALIAS:
1N/A x_gettime = 1
1N/A INPUT:
1N/A # 'a' is timep, 'b' is host
1N/A char *b
1N/A time_t a = NO_INIT
1N/A CODE:
1N/A RETVAL = rpcb_gettime( b, &a );
1N/A OUTPUT:
1N/A a
1N/A RETVAL
1N/A CASE:
1N/A # 'a' is host, 'b' is timep
1N/A char *a
1N/A time_t &b = NO_INIT
1N/A OUTPUT:
1N/A b
1N/A RETVAL
1N/A
1N/AThat function can be called with either of the following statements. Note
1N/Athe different argument lists.
1N/A
1N/A $status = rpcb_gettime( $host, $timep );
1N/A
1N/A $status = x_gettime( $timep, $host );
1N/A
1N/A=head2 The & Unary Operator
1N/A
1N/AThe C<&> unary operator in the INPUT: section is used to tell B<xsubpp>
1N/Athat it should convert a Perl value to/from C using the C type to the left
1N/Aof C<&>, but provide a pointer to this value when the C function is called.
1N/A
1N/AThis is useful to avoid a CODE: block for a C function which takes a parameter
1N/Aby reference. Typically, the parameter should be not a pointer type (an
1N/AC<int> or C<long> but not an C<int*> or C<long*>).
1N/A
1N/AThe following XSUB will generate incorrect C code. The B<xsubpp> compiler will
1N/Aturn this into code which calls C<rpcb_gettime()> with parameters C<(char
1N/A*host, time_t timep)>, but the real C<rpcb_gettime()> wants the C<timep>
1N/Aparameter to be of type C<time_t*> rather than C<time_t>.
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A char *host
1N/A time_t timep
1N/A OUTPUT:
1N/A timep
1N/A
1N/AThat problem is corrected by using the C<&> operator. The B<xsubpp> compiler
1N/Awill now turn this into code which calls C<rpcb_gettime()> correctly with
1N/Aparameters C<(char *host, time_t *timep)>. It does this by carrying the
1N/AC<&> through, so the function call looks like C<rpcb_gettime(host, &timep)>.
1N/A
1N/A bool_t
1N/A rpcb_gettime(host,timep)
1N/A char *host
1N/A time_t &timep
1N/A OUTPUT:
1N/A timep
1N/A
1N/A=head2 Inserting POD, Comments and C Preprocessor Directives
1N/A
1N/AC preprocessor directives are allowed within BOOT:, PREINIT: INIT:, CODE:,
1N/APPCODE:, POSTCALL:, and CLEANUP: blocks, as well as outside the functions.
1N/AComments are allowed anywhere after the MODULE keyword. The compiler will
1N/Apass the preprocessor directives through untouched and will remove the
1N/Acommented lines. POD documentation is allowed at any point, both in the
1N/AC and XS language sections. POD must be terminated with a C<=cut> command;
1N/AC<xsubpp> will exit with an error if it does not. It is very unlikely that
1N/Ahuman generated C code will be mistaken for POD, as most indenting styles
1N/Aresult in whitespace in front of any line starting with C<=>. Machine
1N/Agenerated XS files may fall into this trap unless care is taken to
1N/Aensure that a space breaks the sequence "\n=".
1N/A
1N/AComments can be added to XSUBs by placing a C<#> as the first
1N/Anon-whitespace of a line. Care should be taken to avoid making the
1N/Acomment look like a C preprocessor directive, lest it be interpreted as
1N/Asuch. The simplest way to prevent this is to put whitespace in front of
1N/Athe C<#>.
1N/A
1N/AIf you use preprocessor directives to choose one of two
1N/Aversions of a function, use
1N/A
1N/A #if ... version1
1N/A #else /* ... version2 */
1N/A #endif
1N/A
1N/Aand not
1N/A
1N/A #if ... version1
1N/A #endif
1N/A #if ... version2
1N/A #endif
1N/A
1N/Abecause otherwise B<xsubpp> will believe that you made a duplicate
1N/Adefinition of the function. Also, put a blank line before the
1N/A#else/#endif so it will not be seen as part of the function body.
1N/A
1N/A=head2 Using XS With C++
1N/A
1N/AIf an XSUB name contains C<::>, it is considered to be a C++ method.
1N/AThe generated Perl function will assume that
1N/Aits first argument is an object pointer. The object pointer
1N/Awill be stored in a variable called THIS. The object should
1N/Ahave been created by C++ with the new() function and should
1N/Abe blessed by Perl with the sv_setref_pv() macro. The
1N/Ablessing of the object by Perl can be handled by a typemap. An example
1N/Atypemap is shown at the end of this section.
1N/A
1N/AIf the return type of the XSUB includes C<static>, the method is considered
1N/Ato be a static method. It will call the C++
1N/Afunction using the class::method() syntax. If the method is not static
1N/Athe function will be called using the THIS-E<gt>method() syntax.
1N/A
1N/AThe next examples will use the following C++ class.
1N/A
1N/A class color {
1N/A public:
1N/A color();
1N/A ~color();
1N/A int blue();
1N/A void set_blue( int );
1N/A
1N/A private:
1N/A int c_blue;
1N/A };
1N/A
1N/AThe XSUBs for the blue() and set_blue() methods are defined with the class
1N/Aname but the parameter for the object (THIS, or "self") is implicit and is
1N/Anot listed.
1N/A
1N/A int
1N/A color::blue()
1N/A
1N/A void
1N/A color::set_blue( val )
1N/A int val
1N/A
1N/ABoth Perl functions will expect an object as the first parameter. In the
1N/Agenerated C++ code the object is called C<THIS>, and the method call will
1N/Abe performed on this object. So in the C++ code the blue() and set_blue()
1N/Amethods will be called as this:
1N/A
1N/A RETVAL = THIS->blue();
1N/A
1N/A THIS->set_blue( val );
1N/A
1N/AYou could also write a single get/set method using an optional argument:
1N/A
1N/A int
1N/A color::blue( val = NO_INIT )
1N/A int val
1N/A PROTOTYPE $;$
1N/A CODE:
1N/A if (items > 1)
1N/A THIS->set_blue( val );
1N/A RETVAL = THIS->blue();
1N/A OUTPUT:
1N/A RETVAL
1N/A
1N/AIf the function's name is B<DESTROY> then the C++ C<delete> function will be
1N/Acalled and C<THIS> will be given as its parameter. The generated C++ code for
1N/A
1N/A void
1N/A color::DESTROY()
1N/A
1N/Awill look like this:
1N/A
1N/A color *THIS = ...; // Initialized as in typemap
1N/A
1N/A delete THIS;
1N/A
1N/AIf the function's name is B<new> then the C++ C<new> function will be called
1N/Ato create a dynamic C++ object. The XSUB will expect the class name, which
1N/Awill be kept in a variable called C<CLASS>, to be given as the first
1N/Aargument.
1N/A
1N/A color *
1N/A color::new()
1N/A
1N/AThe generated C++ code will call C<new>.
1N/A
1N/A RETVAL = new color();
1N/A
1N/AThe following is an example of a typemap that could be used for this C++
1N/Aexample.
1N/A
1N/A TYPEMAP
1N/A color * O_OBJECT
1N/A
1N/A OUTPUT
1N/A # The Perl object is blessed into 'CLASS', which should be a
1N/A # char* having the name of the package for the blessing.
1N/A O_OBJECT
1N/A sv_setref_pv( $arg, CLASS, (void*)$var );
1N/A
1N/A INPUT
1N/A O_OBJECT
1N/A if( sv_isobject($arg) && (SvTYPE(SvRV($arg)) == SVt_PVMG) )
1N/A $var = ($type)SvIV((SV*)SvRV( $arg ));
1N/A else{
1N/A warn( \"${Package}::$func_name() -- $var is not a blessed SV reference\" );
1N/A XSRETURN_UNDEF;
1N/A }
1N/A
1N/A=head2 Interface Strategy
1N/A
1N/AWhen designing an interface between Perl and a C library a straight
1N/Atranslation from C to XS (such as created by C<h2xs -x>) is often sufficient.
1N/AHowever, sometimes the interface will look
1N/Avery C-like and occasionally nonintuitive, especially when the C function
1N/Amodifies one of its parameters, or returns failure inband (as in "negative
1N/Areturn values mean failure"). In cases where the programmer wishes to
1N/Acreate a more Perl-like interface the following strategy may help to
1N/Aidentify the more critical parts of the interface.
1N/A
1N/AIdentify the C functions with input/output or output parameters. The XSUBs for
1N/Athese functions may be able to return lists to Perl.
1N/A
1N/AIdentify the C functions which use some inband info as an indication
1N/Aof failure. They may be
1N/Acandidates to return undef or an empty list in case of failure. If the
1N/Afailure may be detected without a call to the C function, you may want to use
1N/Aan INIT: section to report the failure. For failures detectable after the C
1N/Afunction returns one may want to use a POSTCALL: section to process the
1N/Afailure. In more complicated cases use CODE: or PPCODE: sections.
1N/A
1N/AIf many functions use the same failure indication based on the return value,
1N/Ayou may want to create a special typedef to handle this situation. Put
1N/A
1N/A typedef int negative_is_failure;
1N/A
1N/Anear the beginning of XS file, and create an OUTPUT typemap entry
1N/Afor C<negative_is_failure> which converts negative values to C<undef>, or
1N/Amaybe croak()s. After this the return value of type C<negative_is_failure>
1N/Awill create more Perl-like interface.
1N/A
1N/AIdentify which values are used by only the C and XSUB functions
1N/Athemselves, say, when a parameter to a function should be a contents of a
1N/Aglobal variable. If Perl does not need to access the contents of the value
1N/Athen it may not be necessary to provide a translation for that value
1N/Afrom C to Perl.
1N/A
1N/AIdentify the pointers in the C function parameter lists and return
1N/Avalues. Some pointers may be used to implement input/output or
1N/Aoutput parameters, they can be handled in XS with the C<&> unary operator,
1N/Aand, possibly, using the NO_INIT keyword.
1N/ASome others will require handling of types like C<int *>, and one needs
1N/Ato decide what a useful Perl translation will do in such a case. When
1N/Athe semantic is clear, it is advisable to put the translation into a typemap
1N/Afile.
1N/A
1N/AIdentify the structures used by the C functions. In many
1N/Acases it may be helpful to use the T_PTROBJ typemap for
1N/Athese structures so they can be manipulated by Perl as
1N/Ablessed objects. (This is handled automatically by C<h2xs -x>.)
1N/A
1N/AIf the same C type is used in several different contexts which require
1N/Adifferent translations, C<typedef> several new types mapped to this C type,
1N/Aand create separate F<typemap> entries for these new types. Use these
1N/Atypes in declarations of return type and parameters to XSUBs.
1N/A
1N/A=head2 Perl Objects And C Structures
1N/A
1N/AWhen dealing with C structures one should select either
1N/AB<T_PTROBJ> or B<T_PTRREF> for the XS type. Both types are
1N/Adesigned to handle pointers to complex objects. The
1N/AT_PTRREF type will allow the Perl object to be unblessed
1N/Awhile the T_PTROBJ type requires that the object be blessed.
1N/ABy using T_PTROBJ one can achieve a form of type-checking
1N/Abecause the XSUB will attempt to verify that the Perl object
1N/Ais of the expected type.
1N/A
1N/AThe following XS code shows the getnetconfigent() function which is used
1N/Awith ONC+ TIRPC. The getnetconfigent() function will return a pointer to a
1N/AC structure and has the C prototype shown below. The example will
1N/Ademonstrate how the C pointer will become a Perl reference. Perl will
1N/Aconsider this reference to be a pointer to a blessed object and will
1N/Aattempt to call a destructor for the object. A destructor will be
1N/Aprovided in the XS source to free the memory used by getnetconfigent().
1N/ADestructors in XS can be created by specifying an XSUB function whose name
1N/Aends with the word B<DESTROY>. XS destructors can be used to free memory
1N/Awhich may have been malloc'd by another XSUB.
1N/A
1N/A struct netconfig *getnetconfigent(const char *netid);
1N/A
1N/AA C<typedef> will be created for C<struct netconfig>. The Perl
1N/Aobject will be blessed in a class matching the name of the C
1N/Atype, with the tag C<Ptr> appended, and the name should not
1N/Ahave embedded spaces if it will be a Perl package name. The
1N/Adestructor will be placed in a class corresponding to the
1N/Aclass of the object and the PREFIX keyword will be used to
1N/Atrim the name to the word DESTROY as Perl will expect.
1N/A
1N/A typedef struct netconfig Netconfig;
1N/A
1N/A MODULE = RPC PACKAGE = RPC
1N/A
1N/A Netconfig *
1N/A getnetconfigent(netid)
1N/A char *netid
1N/A
1N/A MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
1N/A
1N/A void
1N/A rpcb_DESTROY(netconf)
1N/A Netconfig *netconf
1N/A CODE:
1N/A printf("Now in NetconfigPtr::DESTROY\n");
1N/A free( netconf );
1N/A
1N/AThis example requires the following typemap entry. Consult the typemap
1N/Asection for more information about adding new typemaps for an extension.
1N/A
1N/A TYPEMAP
1N/A Netconfig * T_PTROBJ
1N/A
1N/AThis example will be used with the following Perl statements.
1N/A
1N/A use RPC;
1N/A $netconf = getnetconfigent("udp");
1N/A
1N/AWhen Perl destroys the object referenced by $netconf it will send the
1N/Aobject to the supplied XSUB DESTROY function. Perl cannot determine, and
1N/Adoes not care, that this object is a C struct and not a Perl object. In
1N/Athis sense, there is no difference between the object created by the
1N/Agetnetconfigent() XSUB and an object created by a normal Perl subroutine.
1N/A
1N/A=head2 The Typemap
1N/A
1N/AThe typemap is a collection of code fragments which are used by the B<xsubpp>
1N/Acompiler to map C function parameters and values to Perl values. The
1N/Atypemap file may consist of three sections labelled C<TYPEMAP>, C<INPUT>, and
1N/AC<OUTPUT>. An unlabelled initial section is assumed to be a C<TYPEMAP>
1N/Asection. The INPUT section tells
1N/Athe compiler how to translate Perl values
1N/Ainto variables of certain C types. The OUTPUT section tells the compiler
1N/Ahow to translate the values from certain C types into values Perl can
1N/Aunderstand. The TYPEMAP section tells the compiler which of the INPUT and
1N/AOUTPUT code fragments should be used to map a given C type to a Perl value.
1N/AThe section labels C<TYPEMAP>, C<INPUT>, or C<OUTPUT> must begin
1N/Ain the first column on a line by themselves, and must be in uppercase.
1N/A
1N/AThe default typemap in the C<lib/ExtUtils> directory of the Perl source
1N/Acontains many useful types which can be used by Perl extensions. Some
1N/Aextensions define additional typemaps which they keep in their own directory.
1N/AThese additional typemaps may reference INPUT and OUTPUT maps in the main
1N/Atypemap. The B<xsubpp> compiler will allow the extension's own typemap to
1N/Aoverride any mappings which are in the default typemap.
1N/A
1N/AMost extensions which require a custom typemap will need only the TYPEMAP
1N/Asection of the typemap file. The custom typemap used in the
1N/Agetnetconfigent() example shown earlier demonstrates what may be the typical
1N/Ause of extension typemaps. That typemap is used to equate a C structure
1N/Awith the T_PTROBJ typemap. The typemap used by getnetconfigent() is shown
1N/Ahere. Note that the C type is separated from the XS type with a tab and
1N/Athat the C unary operator C<*> is considered to be a part of the C type name.
1N/A
1N/A TYPEMAP
1N/A Netconfig *<tab>T_PTROBJ
1N/A
1N/AHere's a more complicated example: suppose that you wanted C<struct
1N/Anetconfig> to be blessed into the class C<Net::Config>. One way to do
1N/Athis is to use underscores (_) to separate package names, as follows:
1N/A
1N/A typedef struct netconfig * Net_Config;
1N/A
1N/AAnd then provide a typemap entry C<T_PTROBJ_SPECIAL> that maps underscores to
1N/Adouble-colons (::), and declare C<Net_Config> to be of that type:
1N/A
1N/A
1N/A TYPEMAP
1N/A Net_Config T_PTROBJ_SPECIAL
1N/A
1N/A INPUT
1N/A T_PTROBJ_SPECIAL
1N/A if (sv_derived_from($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")) {
1N/A IV tmp = SvIV((SV*)SvRV($arg));
1N/A $var = ($type) tmp;
1N/A }
1N/A else
1N/A croak(\"$var is not of type ${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")
1N/A
1N/A OUTPUT
1N/A T_PTROBJ_SPECIAL
1N/A sv_setref_pv($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\",
1N/A (void*)$var);
1N/A
1N/AThe INPUT and OUTPUT sections substitute underscores for double-colons
1N/Aon the fly, giving the desired effect. This example demonstrates some
1N/Aof the power and versatility of the typemap facility.
1N/A
1N/A=head2 Safely Storing Static Data in XS
1N/A
1N/AStarting with Perl 5.8, a macro framework has been defined to allow
1N/Astatic data to be safely stored in XS modules that will be accessed from
1N/Aa multi-threaded Perl.
1N/A
1N/AAlthough primarily designed for use with multi-threaded Perl, the macros
1N/Ahave been designed so that they will work with non-threaded Perl as well.
1N/A
1N/AIt is therefore strongly recommended that these macros be used by all
1N/AXS modules that make use of static data.
1N/A
1N/AThe easiest way to get a template set of macros to use is by specifying
1N/Athe C<-g> (C<--global>) option with h2xs (see L<h2xs>).
1N/A
1N/ABelow is an example module that makes use of the macros.
1N/A
1N/A #include "EXTERN.h"
1N/A #include "perl.h"
1N/A #include "XSUB.h"
1N/A
1N/A /* Global Data */
1N/A
1N/A #define MY_CXT_KEY "BlindMice::_guts" XS_VERSION
1N/A
1N/A typedef struct {
1N/A int count;
1N/A char name[3][100];
1N/A } my_cxt_t;
1N/A
1N/A START_MY_CXT
1N/A
1N/A MODULE = BlindMice PACKAGE = BlindMice
1N/A
1N/A BOOT:
1N/A {
1N/A MY_CXT_INIT;
1N/A MY_CXT.count = 0;
1N/A strcpy(MY_CXT.name[0], "None");
1N/A strcpy(MY_CXT.name[1], "None");
1N/A strcpy(MY_CXT.name[2], "None");
1N/A }
1N/A
1N/A int
1N/A newMouse(char * name)
1N/A char * name;
1N/A PREINIT:
1N/A dMY_CXT;
1N/A CODE:
1N/A if (MY_CXT.count >= 3) {
1N/A warn("Already have 3 blind mice") ;
1N/A RETVAL = 0;
1N/A }
1N/A else {
1N/A RETVAL = ++ MY_CXT.count;
1N/A strcpy(MY_CXT.name[MY_CXT.count - 1], name);
1N/A }
1N/A
1N/A char *
1N/A get_mouse_name(index)
1N/A int index
1N/A CODE:
1N/A dMY_CXT;
1N/A RETVAL = MY_CXT.lives ++;
1N/A if (index > MY_CXT.count)
1N/A croak("There are only 3 blind mice.");
1N/A else
1N/A RETVAL = newSVpv(MY_CXT.name[index - 1]);
1N/A
1N/A
1N/AB<REFERENCE>
1N/A
1N/A=over 5
1N/A
1N/A=item MY_CXT_KEY
1N/A
1N/AThis macro is used to define a unique key to refer to the static data
1N/Afor an XS module. The suggested naming scheme, as used by h2xs, is to
1N/Ause a string that consists of the module name, the string "::_guts"
1N/Aand the module version number.
1N/A
1N/A #define MY_CXT_KEY "MyModule::_guts" XS_VERSION
1N/A
1N/A=item typedef my_cxt_t
1N/A
1N/AThis struct typedef I<must> always be called C<my_cxt_t> -- the other
1N/AC<CXT*> macros assume the existence of the C<my_cxt_t> typedef name.
1N/A
1N/ADeclare a typedef named C<my_cxt_t> that is a structure that contains
1N/Aall the data that needs to be interpreter-local.
1N/A
1N/A typedef struct {
1N/A int some_value;
1N/A } my_cxt_t;
1N/A
1N/A=item START_MY_CXT
1N/A
1N/AAlways place the START_MY_CXT macro directly after the declaration
1N/Aof C<my_cxt_t>.
1N/A
1N/A=item MY_CXT_INIT
1N/A
1N/AThe MY_CXT_INIT macro initialises storage for the C<my_cxt_t> struct.
1N/A
1N/AIt I<must> be called exactly once -- typically in a BOOT: section.
1N/A
1N/A=item dMY_CXT
1N/A
1N/AUse the dMY_CXT macro (a declaration) in all the functions that access
1N/AMY_CXT.
1N/A
1N/A=item MY_CXT
1N/A
1N/AUse the MY_CXT macro to access members of the C<my_cxt_t> struct. For
1N/Aexample, if C<my_cxt_t> is
1N/A
1N/A typedef struct {
1N/A int index;
1N/A } my_cxt_t;
1N/A
1N/Athen use this to access the C<index> member
1N/A
1N/A dMY_CXT;
1N/A MY_CXT.index = 2;
1N/A
1N/A=back
1N/A
1N/A=head1 EXAMPLES
1N/A
1N/AFile C<RPC.xs>: Interface to some ONC+ RPC bind library functions.
1N/A
1N/A #include "EXTERN.h"
1N/A #include "perl.h"
1N/A #include "XSUB.h"
1N/A
1N/A #include <rpc/rpc.h>
1N/A
1N/A typedef struct netconfig Netconfig;
1N/A
1N/A MODULE = RPC PACKAGE = RPC
1N/A
1N/A SV *
1N/A rpcb_gettime(host="localhost")
1N/A char *host
1N/A PREINIT:
1N/A time_t timep;
1N/A CODE:
1N/A ST(0) = sv_newmortal();
1N/A if( rpcb_gettime( host, &timep ) )
1N/A sv_setnv( ST(0), (double)timep );
1N/A
1N/A Netconfig *
1N/A getnetconfigent(netid="udp")
1N/A char *netid
1N/A
1N/A MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
1N/A
1N/A void
1N/A rpcb_DESTROY(netconf)
1N/A Netconfig *netconf
1N/A CODE:
1N/A printf("NetconfigPtr::DESTROY\n");
1N/A free( netconf );
1N/A
1N/AFile C<typemap>: Custom typemap for RPC.xs.
1N/A
1N/A TYPEMAP
1N/A Netconfig * T_PTROBJ
1N/A
1N/AFile C<RPC.pm>: Perl module for the RPC extension.
1N/A
1N/A package RPC;
1N/A
1N/A require Exporter;
1N/A require DynaLoader;
1N/A @ISA = qw(Exporter DynaLoader);
1N/A @EXPORT = qw(rpcb_gettime getnetconfigent);
1N/A
1N/A bootstrap RPC;
1N/A 1;
1N/A
1N/AFile C<rpctest.pl>: Perl test program for the RPC extension.
1N/A
1N/A use RPC;
1N/A
1N/A $netconf = getnetconfigent();
1N/A $a = rpcb_gettime();
1N/A print "time = $a\n";
1N/A print "netconf = $netconf\n";
1N/A
1N/A $netconf = getnetconfigent("tcp");
1N/A $a = rpcb_gettime("poplar");
1N/A print "time = $a\n";
1N/A print "netconf = $netconf\n";
1N/A
1N/A
1N/A=head1 XS VERSION
1N/A
1N/AThis document covers features supported by C<xsubpp> 1.935.
1N/A
1N/A=head1 AUTHOR
1N/A
1N/AOriginally written by Dean Roehrich <F<roehrich@cray.com>>.
1N/A
1N/AMaintained since 1996 by The Perl Porters <F<perlbug@perl.org>>.