.\" -*- mode: troff; coding: utf-8 -*-
.\" Automatically generated by Pod::Man v6.0.2 (Pod::Simple 3.48)
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
.ie n \{\
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds C`
.    ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el       .ds Aq '
.\"
.\" If the F register is >0, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.nr rF 0
.if \n(.g .if rF .nr rF 1
.if (\n(rF:(\n(.g==0)) \{\
.    if \nF \{\
.        de IX
.        tm Index:\\$1\t\\n%\t"\\$2"
..
.        if !\nF==2 \{\
.            nr % 0
.            nr F 2
.        \}
.    \}
.\}
.rr rF
.\"
.\" Required to disable full justification in groff 1.23.0.
.if n .ds AD l
.\" ========================================================================
.\"
.IX Title "PERLXS 1"
.TH PERLXS 1 2026-07-13 "perl v5.44.0" "Perl Programmers Reference Guide"
.\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.if n .ad l
.nh
.SH NAME
perlxs \- the XS Language Reference Manual
.SH SYNOPSIS
.IX Header "SYNOPSIS"
.Vb 3
\&    /* This is a simple example of an XS file. The first half of an XS
\&     * file is uninterpreted C code; all lines are passed through
\&     * unprocessed. */
\&
\&    =pod
\&    Except that any POD is stripped.
\&    =cut
\&
\&    /* Standard boilerplate: */
\&
\&    /* For efficiency, always define PERL_NO_GET_CONTEXT: not enabled by
\&     * default for backwards compatibility. For details, see "How multiple
\&     * interpreters and concurrency are supported" in perlguts. */
\&    #define PERL_NO_GET_CONTEXT
\&
\&    #include "EXTERN.h"
\&    #include "perl.h"
\&    #include "XSUB.h"
\&    #include "ppport.h"
\&
\&    /* Any general C code here; for example: */
\&
\&    #define FOO 1
\&    static int
\&    my_helper_function(int i) { /* do stuff */ }
\&
\&    /* The first MODULE line starts the XS half of the file: */
\&
\&    MODULE = Foo::Bar PACKAGE = Foo::Bar
\&
\&      # Indented \*(Aq#\*(Aq are XS code comments.
\&      # C preprocessor directives are still allowed and are passed
\&      # through:
\&    #define BAR 2
\&
\&      # File\-scoped XS directives
\&    PROTOTYPES: DISABLE
\&
\&      # A simple XSUB: generate a wrapper for the strlen() C library
\&      # function.
\&
\&    int
\&    strlen(char *s)
\&
\&    =pod
\&    A more complex example:
\&    C<multi16(i,j)>: do a 16\-bit multiply
\&    =cut
\&
\&    unsigned int
\&    multi16(unsigned int i, \e
\&            unsigned int j)
\&      CODE:
\&        i = i & 0xFFFF;
\&        j = j & 0xFFFF;
\&        RETVAL = (i * j) & 0xFFFF;
\&      OUTPUT:
\&        RETVAL
.Ve
.SH DESCRIPTION
.IX Header "DESCRIPTION"
This is the reference manual for the XS language. This is a type of
template language from which is generated a C code source file that
contains functions written in C, but which can be called from Perl, and
which behave just like Perl subs. These are known as \fIexternal\fR or
\&\fIextension\fR subs, or XSUBs for short.
.PP
Note that this POD file was heavily rewritten and modernised in 2025.
Various old practices, such as "K&R" XSUB function signature declarations,
are no longer encouraged; but much old code will still be using them, so
be cautious when using old code as examples for writing new code.
.SS "Version numbers"
.IX Subsection "Version numbers"
Unless otherwise specified, the syntax described in this document is valid
at least as far back as the 1.9508 version of the XS parser utility
\&\fIxsubpp\fR, which was bundled with Perl release 5.8.0.
.PP
In \fIxsubpp\fR version 2.09_01, the bulk of the code for this utility was
split out into a separate module, ExtUtils::ParseXS. This module
inherited the version numbering scheme of \fIxsubpp\fR, and since then, the
latter just uses the version number of the \fIParseXS.pm\fR which gets
loaded. This splitting out means that a newer version of
\&\fIExtUtils::ParseXS\fR can be installed via CPAN into an older Perl
installation, allowing newer XS syntax to be used with older Perls.
.PP
(Between 1.98_01 and 2.09_01, \fIExtUtils::ParseXS\fR existed as a separate
fork of \fIxsubpp\fR, with some changes ported back and forwards with the
perl distribution\*(Aqs \fIxsubpp\fR, in a confusing manner.)
.PP
This document refers to changes in XS syntax by reference to \fIxsubpp\fR
version numbers. This should be understood as usually mapping directly to
the same version number of \fIExtUtils::ParseXS\fR. To determine which
version of this module was bundled with which release of Perl, you can use
the \fIcorelist\fR utility which is usually a part of the Perl installation,
e.g.
.PP
.Vb 1
\&    corelist \-a ExtUtils::ParseXS
.Ve
.SH "THE FORMAL SYNTAX OF AN XS FILE"
.IX Header "THE FORMAL SYNTAX OF AN XS FILE"
This is a BNF\-like description of the syntax of an XS file. It is intended
to be human\-readable rather than machine\-readable, and doesn\*(Aqt try to
accurately specify where line breaks can occur.
.PP
.Vb 1
\& Key:
\&
\&    foo         BNF token.
\&    "bar"       Literal terminal symbol.
\&    /.../       Terminal symbol defined by a pattern.
\&    [Foo::Bar]  Terminal symbol defined by way of an example.
\&    * + ? | ( ) These have their usual regex\-style meanings.
\&    // ...      BNF Comments.
\&
\&
\& XS_file           = C_file_part ( module_decl  XS_file_part )+
\&
\& C_file_part       = (
\&                        // Lines of C code (including /* ... */),
\&                        // which are all passed through uninterpreted.
\&                     |
\&                        pod // These are stripped.
\&                     )*
\&
\& pod               = /^=/ .. /^=cut\es*$/
\&
\& module_decl       = blank_line
\&                     // NB: all on one line:
\&                     "MODULE =" [Foo::Bar] "PACKAGE =" [Foo::Bar]
\&                                             ( "PREFIX =" [foo_] )?
\&
\& blank_line        = /^\es*$/
\&
\& XS_file_part      = ( file_scoped_decls* xsub )*
\&
\& file_scoped_decls =
\&                     blank_line
\&                     // Any valid CPP directive: these are passed through:
\&                   | "#if" | "#  if" | "#define" | // etc
\&                   | #comment // anything not recognised as CPP directive
\&                   | pod
\&                   | "SCOPE:"               enable
\&                   | "EXPORT_XSUB_SYMBOLS:" enable
\&                   | "PROTOTYPES:"          enable
\&                   | "VERSIONCHECK:"        enable
\&                   | "FALLBACK:"            ("TRUE" | "FALSE" | "UNDEF")
\&                   | "INCLUDE:"             [foo.xs]
\&                   | "INCLUDE_COMMAND:"     [... some command line ...]
\&                   | "REQUIRE:"             [1.23] // min xsubpp version
\&                   | "BOOT:"
\&                         code_block
\&                   | "TYPEMAP: <<"[EOF]
\&                        // Heredoc with typemap declarations.
\&                     [EOF]
\&
\& enable            = ( "ENABLE" | "DISABLE" )
\&
\& code_block        = // Lines of C and/or blank lines terminated by the
\&                     // next keyword or XSUB start. POD is stripped.
\&
\& xsub              = blank_line // not *always* necessary
\&                     xsub_decl
\&                     ( cases | xbody )
\&
\& xsub_decl         = return_type
\&                     xsub_name "(" parameters ")" "const" ?
\&
\& return_type       = "NO_OUTPUT" ? "extern \e"C\e"" ? "static" ? C_type
\&
\& C_type            = [const char *]  // etc: any valid C type
\&
\& C_expression      = [foo(ix) + 1]   // etc: any valid C expression
\&
\& xsub_name         = [foo] | [X::Y::foo] // simple name or C++ name
\&
\& parameters        =   empty
\&                     | parameter ( "," parameter )*
\&
\& empty             = /\es*/
\&
\& parameter         = (
\&                       in_out_decl ?
\&                       C_type ?
\&                       /\ew+/   // variable name
\&                       // Default or optional value:
\&                       ( "=" ( C_expression | "NO_INIT" ) )?
\&
\&                       // Pseudo\-param: foo must match another param name:
\&                     | C_type "length(" [foo] ")"
\&                     | "..."
\&                     )
\&
\& in_out_decl       = "IN" | "OUT" | "IN_OUT" | "OUTLIST" | "IN_OUTLIST"
\&
\& cases             = (
\&                        "CASE:" ( C_expression | empty )
\&                        xbody
\&                     )+
\&
\& xbody             = implicit_input     ?
\&                     xbody_input_part   *
\&                     xbody_init_part    *
\&                     xbody_code_part
\&                     xbody_output_part  * // Not after PPCODE.
\&                     xbody_cleanup_part * // Not after PPCODE.
\&
\& implicit_input    = ( blank_line | input_line )+
\&
\& xbody_input_part  =
\&                       "INPUT:" ( blank_line | input_line )*
\&                     | "PREINIT:"
\&                           code_block
\&                     | xbody_generic_key
\&                     | c_args
\&                     | interface_macro
\&                     | "SCOPE:" enable  // Only in xsubpp 3.58 onwards.
\&
\& input_line        = C_type
\&                     "&" ?
\&                     /\ew+/   // variable name
\&                     // Optional initialiser:
\&                     (
\&                       ( "=" | ";" ) "NO_INIT"
\&                     |
\&                       // Override or add to the default typemap.
\&                       // The expression is eval()ed as a
\&                       // double\-quotish string.
\&                       "=" [ a_typemap_override($arg) ]
\&                     |
\&                       ("+" | ";")  [ a_deferred_initialiser($arg) ]
\&                     )?
\&                     ";" ?
\&
\& xbody_init_part   =   "INIT:"
\&                           code_block
\&                     | xbody_generic_key
\&                     | c_args
\&                     | interface
\&                     | interface_macro
\&
\& xbody_code_part   =
\&                       autocall
\&                     | "CODE:"
\&                           code_block
\&                     | "PPCODE:"
\&                           code_block
\&                     | // Only recognised if immediately following
\&                       // an INPUT section:
\&                       "NOT_IMPLEMENTED_YET:"
\&
\&                     // Implicit call to wrapped library function.
\& autocall          = empty
\&
\& xbody_output_part =
\&                      xbody_postcall *
\&                      xbody_output *
\&
\& xbody_postcall    =   "POSTCALL:"
\&                           code_block
\&                     | xbody_generic_key
\&
\& xbody_output      =   "OUTPUT:"
\&                        ( blank_line
\&                        | output_line
\&                        | "SETMAGIC:" enable
\&                        )*
\&                     | xbody_generic_key
\&
\&                     // Variable name with optional expression which
\&                     // overrides the typemap
\& output_line       = /\ew+/ ( [ sv_setfoo(ST[0], RETVAL) ] )?
\&
\& xbody_cleanup_part = "CLEANUP:"
\&                           code_block
\&                     | xbody_generic_key
\&
\&                     // Text to use as the arguments for an autocall;
\&                     // may be spread over multiple lines:
\& c_args            = "C_ARGS:" [foo, bar, baz]
\&
\&                     // Comma\-separated list of Perl subroutine names
\&                     // which use the XSUB, over one or more lines:
\& interface         = "INTERFACE:"  [foo, bar, Bar::baz]
\&
\& interface_macro   =
\&                     "INTERFACE_MACRO:"
\&                       [GET_MACRO_NAME]
\&                       [SET_MACRO_NAME] ?
\&
\&
\&                       // These can appear anywhere in an XSUB.
\& xbody_generic_key =   pod
\&                     | alias
\&                     | "PROTOTYPE:" ( enable | [$$@] )
\&
\&                       // Whitespace\-separated list of overload types,
\&                       // over one or more lines:
\&                     | "OVERLOAD:"  [ cmp eq <=> etc ]
\&
\&                       // Whitespace\-separated list of attribute names,
\&                       // over one or more lines:
\&                     | "ATTRS:" [foo bar baz]
\&
\&
\& alias             = "ALIAS:"
\&                       // One or more lines; each with zero or more
\&                       // {alias_name, op, index} triplets:
\&                       (
\&                         [bar]       "="  [5]
\&                       | [Foo::baz]  "="  [A_CPP_DEFINE]
\&                       | [Bar::boz]  "=>" [Foo::baz]
\&                       )*
.Ve
.SH "OVERVIEW OF XS AND XSUBS"
.IX Header "OVERVIEW OF XS AND XSUBS"
.SS "Initial and Further Reading"
.IX Subsection "Initial and Further Reading"
This document is structured on the assumption that you are already
familiar with the very basics of XS and XSUBs; in particular, the code
examples may make use of common keywords that are only described later in
the file. But once you have that basic familiarity, then this document
may be read through in order.
.PP
It is in two main parts. First there is a long overview part, which
explains (in great detail) what XS and XSUBs are, how the perl interpreter
calls XSUBs, and how data is passed to and from an XSUB. There is much
more detail here than is strictly necessary for writing simple XSUBs, but
this document is intended to be comprehensive. Then comes the reference
manual proper, which has a section for each keyword and other parts of an
XSUB declaration and definition, plus a few more general topics, such as
using typemaps and storing static data.
.PP
If necessary, read perlxstut first for a gentler tutorial introduction.
In addition, you may find the following Perl documents useful.
.IP \(bu 4
perlxstypemap: this describes typemap files and how to create new
typemaps. These are code templates which are used by the XS compiler to
automatically generate code which converts between Perl and C data types.
Creating an interface to a C library is sometimes mainly a case of adding
new typemap entries to handle the new data types which the library uses.
.IP \(bu 4
perlguts: this contains details of selected parts of the internals of
the Perl interpreter. A better understanding of that may help when writing
more complex XSUBs, or when debugging.
.Sp
Note that much of the data passing overview part of this document is just a summary of
the parts of perlguts which are most relevant to writing XS code,
possibly saving you from having to actually read that document.
.IP \(bu 4
perlclib: this describes how and when to use the basic C and OS library
functions from XS. Often, the Perl API contains functions which you should
use \fIinstead\fR of the standard C library ones, e.g. using \f(CWPerlIO_read()\fR
instead of \f(CWfread()\fR.
.IP \(bu 4
perlcall: this describes how to call Perl functions and do the
equivalent of \f(CW\*(C`eval {}\*(C'\fR from C.
.IP \(bu 4
perlembed: this describes how to embed a complete Perl interpreter
within another application and do the equivalent of \f(CW\*(C`eval ""\*(C'\fR from C.
.SS "An Introduction to XS and XSUBs"
.IX Subsection "An Introduction to XS and XSUBs"
Formally, an XSUB is a compiled function, typically written in C or C++,
which can be called from Perl as if it was a Perl function. A collection
of them are compiled into a \f(CW\*(C`.so\*(C'\fR or \f(CW\*(C`.dll\*(C'\fR library file and are usually
dynamically loaded at \f(CW\*(C`use Foo::Bar\*(C'\fR time (but can in principle be
statically linked into the perl interpreter).
.PP
From Perl, an XSUB looks just like any other sub and is called in the same
way. In the most general case, an XSUB can be passed and return arbitrary
lists of values. More commonly, such as when XSUBs are being used as thin
wrappers to call existing C library functions, they might take a fixed list
of arguments and return a single result (or zero items for a \f(CW\*(C`void\*(C'\fR
function).
.PP
An XS file is a template file format which contains a mixture of C code
and XSUB declarations. It is used to generate XSUBs where most boilerplate
code is handled automatically: e.g. converting argument values between C
and Perl.
.PP
Note that this document refers to both the thing in the XS file, and to
the C function generated from it, as an XSUB. It should be clear from the
context which is being referred to.
.PP
When XSUBs are being used as a thin wrapper between Perl and the functions
in a particular C library, the XSUB definitions in the XS file are often
just a couple of lines, consisting of a declaration of the name,
parameters and return type. The XS parser will do almost all the heavy
lifting for you.
.PP
XS is optional; in principle you can write your own C code directly, or
use other systems such as \f(CW\*(C`Inline::C\*(C'\fR or SWIG. For creating simple
bindings to existing compiled libraries, there is also the
libffi <http://sourceware.org/libffi/> interface via CPAN modules like
FFI::Platypus or FFI::Raw. Note that creating XS may initially take
more effort than those, but it is lightweight in terms of dependencies.
.PP
XSUBs have three main roles. They can be used as thin wrappers for C
library functions, e.g. Digest::SHA. They can be used to write
functions which are faster than pure Perl or easier to do in C, e.g.
List::Util. Or they can be used to extend the Perl interpreter itself,
e.g. threads.
.PP
XS has extensive support for the first role, and makes writing the second
need less boilerplate code. This document doesn\*(Aqt cover the third role,
which often requires extensive knowledge of the Perl interpreter\*(Aqs
internals.
.PP
The \fIh2xs\fR utility bundled with Perl can in principle be used to generate
an initial XS file from a C header file, which (with possibly only minor
edits) can be used to wrap an entire C API. But note that this utility is
rather old and may not handle more modern C header code.
.PP
\&\fIh2xs\fR (as well as other tools) can also be used to generate an initial
"empty" skeleton distribution even when not deriving from a header file
(see perlxstut for more details).
.PP
Typemaps are sets of rules which map C types such as \f(CW\*(C`int\*(C'\fR to logical XS
types such as \f(CW\*(C`T_IV\*(C'\fR, and from there to \f(CW\*(C`INPUT\*(C'\fR and \f(CW\*(C`OUTPUT\*(C'\fR templates
such as \f(CW\*(C`$var = ($type)SvIV($arg)\*(C'\fR and \f(CW\*(C`sv_setiv($arg, (IV)$var)\*(C'\fR
which, after variable expansion, generate C code which converts back and
forth between Perl arguments and C auto variables.
.PP
There is a standard system typemap file which contains rules for common C
and Perl types, but you can add your own typemap file in addition, and
from \fIxsubpp\fR 3.01 onwards you can also add typemap declarations inline
within the XS file. You can either just add mappings from new C types to
existing XS types to make use of existing templates, or you can add new
templates too. As an example of the former, if you\*(Aqre using a C header
file which has:
.PP
.Vb 1
\&    typedef int my_int;
.Ve
.PP
then adding this typemap entry:
.PP
.Vb 1
\&    my_int T_IV
.Ve
.PP
is sufficient for the XS parser to know to use the existing \f(CW\*(C`T_IV\*(C'\fR
templates when processing an XSUB which has a \f(CW\*(C`my_int\*(C'\fR parameter type.
See "Using Typemaps" and perlxstypemap for more information.
.PP
An XS file is parsed by ExtUtils::ParseXS, or by the \fIxsubpp\fR utility
(which is a thin wrapper over the module), and generates a \f(CW\*(C`.c\*(C'\fR file.
\&\fIxsubpp\fR is typically called at build time from the Makefile of a
distribution (as generated by ExtUtils::MakeMaker); or
ExtUtils::ParseXS can be used directly, e.g. by Module::Build. The C
file is then compiled into a \f(CW\*(C`.so\*(C'\fR or \f(CW\*(C`.dll\*(C'\fR, again at module build and
install time.
.SS "The Structure of an XS File"
.IX Subsection "The Structure of an XS File"
An XS file has two parts, which are parsed and treated completely
differently: the C half and the XS half.
.PP
Anything before the first MODULE directive line
is treated as pure C (except for any sections of POD, which are
discarded). All such lines, including C preprocessor directives and C code
comments, are passed through unprocessed into the destination C file. XS
comments (as described below) aren\*(Aqt recognised by the XS parser, and are
just passed through unprocessed.
.PP
It is possible that machine\-generated C code inserted in this section
could include an equal sign character in column one, which would be
misinterpreted as POD; if this is a risk, make sure that this hypothetical
code generator includes a leading space character.
.PP
This half of the file is the place to put things which will be of use to
the XSUB code further down: such as \f(CW\*(C`#include\*(C'\fR, \f(CW\*(C`#define\*(C'\fR, \f(CW\*(C`typedef\*(C'\fR,
and static C functions. Note that you should (in general) avoid declaring
static \fIdata\fR in XS files; see "Safely Storing Static Data in XS" for
details and workarounds.
.PP
After the first \f(CW\*(C`MODULE\*(C'\fR line, the rest of the file is interpreted as XS
syntax. Further \f(CW\*(C`MODULE\*(C'\fR keywords may appear where needed to change the
current package (in a similar fashion to a single Perl \fIFoo.pm\fR file
having multiple \f(CW\*(C`package\*(C'\fR statements).
.PP
This second half consists mostly of a series of XSUB definitions. Between
these XSUBs, there can be a few file\-scope keywords (including further
\&\f(CW\*(C`MODULE\*(C'\fR lines), POD, C preprocessor directives, XS (\f(CW\*(C`#\*(C'\fR) comments, and
blank lines. See "File\-scoped XS Keywords and Directives" for more
details.
.PP
The XS half of the file can be thought of as being parsed in two stages.
In the initial processing step, the XS parser does the following basic
text processing actions.
.IP \(bu 4
A trailing backslash (i.e. \f(CW\*(C`/\e\e\en/\*(C'\fR) within the XS part of the file is
treated as a line continuation: any such series of lines are concatenated.
They are then treated as single line by the main (line\-orientated) XS
Parser. This means that the next line loses any special significance; for
example, it may not be recognised as a keyword or end\-of\-XSUB blank line.
.Sp
Note however that the two characters \f(CW"\e\e\en"\fR are kept in the
concatenated line, to be subsequently interpreted by the main part of the
XS parser. Mostly these two extra characters will just confuse the parser;
but where such lines are just passed\-through to the output C file as\-is
(such as for \f(CW\*(C`CODE\*(C'\fR blocks and C preprocessor directives), this results
in the backslash and newline appearing in the C code.
.Sp
The main exception to leaving the continuation characters in the line is
in an XSUB\*(Aqs signature, where any trailing backslashes are stripped away
before parsing.
.IP \(bu 4
The parser discards any POD lines. Any sequence of lines matching
\&\f(CW\*(C`/^=/ .. /^=cut\es*$/\*(C'\fR is considered POD.
.IP \(bu 4
It discards any XS comment lines. Any line starting with \f(CW\*(C`/^\es*#/\*(C'\fR which
\&\fIisn\*(Aqt\fR recognised by the XS parser as a valid C preprocessor directive,
is treated as an XS comment line.
.Sp
It is recommended to include at least one space before an XS \f(CW\*(C`#\*(C'\fR comment
to avoid any possible confusion with C preprocessor directives.
.Sp
If an XS comment line ends with a backslash, then the line following it is
treated as part of that comment line and is also discarded.
.PP
Once that basic textual preprocessing has been performed, the main XS
parsing takes place. XS syntax is very line\-orientated. XS lines and
sections mostly start with a keyword of the form;
.PP
.Vb 1
\&    /^\es*[A\-Z_]+:/
.Ve
.PP
It is best to position file\-scoped keywords at column one, while
XSUB\-scoped keywords are best indented. This may avoid surprises with edge
cases in the XS parser.
.PP
Keywords can be either single line, e.g. \f(CW\*(C`PROTOTYPES: ENABLE\*(C'\fR, or
multi\-line. The latter consume lines until the next keyword, or until the
possible start of a new XSUB (\f(CW\*(C`/\en\en\eS/\*(C'\fR), or to EOF. Multi\-line keywords
treat the rest of the text on the line which follows the keyword as the
first line of data. The exception to this is keywords which introduce a
block of code, such as \f(CW\*(C`CODE:\*(C'\fR  or \f(CW\*(C`BOOT:\*(C'\fR, which silently ignore the
rest of the first line. (Yes, this is a implementation flaw.)
.PP
It is best to include a blank line between each file\-scoped item, and
before the start of each XSUB. While some items \fIare\fR processed correctly
if they are on the line immediately preceding the start of an XSUB, the
parser is inconsistent in their handling.
.PP
An XSUB ends when \f(CW\*(C`/\en\en\eS/\*(C'\fR is encountered: i.e. a blank line followed
by something on column one. (This is why it\*(Aqs recommended to indent
XSUB\-scoped keywords.) If the thing at column one matches any of the items
which can appear in between XSUBs (such as file\-scoped keywords) then it,
and any subsequent lines, are processed as such. Anything starting on
column one which isn\*(Aqt otherwise recognised, is interpreted as the first
line of the next XSUB definition. In particular it is interpreted as the
return type of the XSUB: this can lead to weird errors when something is
unexpectedly interpreted as the start of a new XSUB, such as \f(CW\*(C`/* */\*(C'\fR,
which isn\*(Aqt valid in the XS half of the file apart from within code
blocks.
.PP
Some multi\-line keywords, such as \f(CW\*(C`C_ARGS\*(C'\fR, are treated as just a single
uninterpreted multi\-line string. Others, such as \f(CW\*(C`OUTPUT\*(C'\fR, have a
specific per\-line syntax, where each line within the section is parsed.
Finally, code blocks such as \f(CW\*(C`CODE\*(C'\fR are just copied as\-is to the output C
file (possibly sandwiched between \f(CW\*(C`#line\*(C'\fR directives to ensure that
compiler error messages report from the correct location).
.PP
The XS parser doesn\*(Aqt recognise C comments, so don\*(Aqt use them apart from
in C code (e.g. not in an XSUB signature). More generally, the XS parser
doesn\*(Aqt understand C syntax or semantics; it just uses crude regexes to
parse the XS file. For example the parser can handle an XSUB declaration
like this:
.PP
.Vb 2
\&    int
\&    foo(int a, char *b = "),")
.Ve
.PP
Here, the parser just extracts out everything between (...) and splits on
commas, with just enough intelligence to ignore commas etc within matching
pairs of double\-quotes. The parser doesn\*(Aqt understand C type declaration
syntax; for example it typically just extracts everything before what
appears to be a parameter name, and assumes that it must be the type. That
"type" will later be looked up in a typemap, and if no entry is found,
will only then raise an error. So it will fail to correctly parse the
following parameters:
.PP
.Vb 2
\&    int
\&    foo(int a /* not\-a\-comment */, this is seen as a type!! b)
.Ve
.PP
In addition, the XS parser has historically been very permissive, even to
the point of accepting nonsense as input. Since around \fIxsubpp\fR releases
3.54\-3.61, more things are likely to warn or raise errors during XS
parsing, rather than silently generating a non\-compilable C code file.
.PP
As mentioned earlier, an XSUB definition typically starts with \f(CW\*(C`/\en\en\eS/\*(C'\fR
and continues until the next \f(CW\*(C`/\en\en\eS/\*(C'\fR. The XSUB definition consists of
a declaration, followed by an optional body. The declaration gives the
function\*(Aqs name, parameters and return type, and is intended to mimic a C
function declaration. It is usually two lines long.
.PP
The XSUB\*(Aqs body consists of a series of keywords. The main C code of an
XSUB is specified by a \f(CW\*(C`CODE\*(C'\fR or \f(CW\*(C`PPCODE\*(C'\fR section. In the absence of
this, a short body is generated automatically, which consists of a call to
a C function with the same name and arguments as the XSUB. In this way,
the XSUB becomes a short wrapper function between Perl and the C library
function, with the wrapper handling the conversion been Perl and C
arguments. This is referred to in this document as \fIautocall\fR.
.PP
Other keywords can be used to modify the code generated for the XSUB, or
to alter how it is registered with the interpreter (e.g. adding
attributes).
.PP
So that is the basic structure of an XSUB. What a real XSUB looks like
will be covered later in "The Anatomy of an XSUB", but first a slight
digression follows.
.SS "Overview of how data is passed to and from an XSUB"
.IX Subsection "Overview of how data is passed to and from an XSUB"
This section contains a basic background on how XSUBs are invoked, what
their arguments consist of, and how XSUB arguments are passed to and from
Perl. It is essentially a summary of some relevant sections within
perlguts; see that document for  a more detailed exploration.
.PP
Note that most of the information in this section isn\*(Aqt needed to create
basic XSUBs; but for more complex needs or for debugging, it helps to
understand what\*(Aqs happening behind the scenes.
.PP
\fIPerl OPs\fR
.IX Subsection "Perl OPs"
.PP
(This next paragraph is definitely only for background on debugging.)
.PP
An \f(CW\*(C`OP\*(C'\fR is a data structure within the perl interpreter. It is used to
hold the nodes within a tree structure created when the perl source is
compiled. It usually represents a single operation within the perl source,
such as an add, or a function call. The structure has various flags and
data, and a pointer to a C function (called the PP function) which is used
to implement the actions of that OP. The main loop of the perl interpreter
consists of calling the PP function associated with the current OP
(\f(CW\*(C`PL_op\*(C'\fR) and then updating it, typically to \f(CW\*(C`PL_op\->op_next\*(C'\fR.
.PP
In particular, the \f(CW\*(C`OP_ENTERSUB\*(C'\fR OP, via a call to \f(CWpp_entersub()\fR,
performs (or at least starts) a function call, including any calls to XS
functions
.PP
\fISVs and the Perl interpreter\*(Aqs argument stack\fR
.IX Subsection "SVs and the Perl interpreter's argument stack"
.PP
Almost all runtime data within the Perl interpreter, including all Perl
variables, are stored in an \fISV\fR structure. These SVs can hold data of
many different types, including integers (IV \- integer value), strings (PV
\&\- pointer value), references (RV), arrays (AV), elements of arrays,
subroutines (CV \- code value) etc. These will be discussed in more detail
below.
.PP
Perl has an \fIargument\fR stack, which is a C array of SV pointers. Most of
the run\-time actions of the PP functions consist of pushing SV pointers
onto the stack or popping them off and processing them. There is a
companion \fImark\fR stack, which is an array of integers which are argument
stack offsets. These marks serve to delineate the stack into frames.
.PP
Consider this subroutine call:
.PP
.Vb 1
\&    @a = foo(1, $x);
.Ve
.PP
The various OPs executed by the Perl interpreter up until the function is
called will: push a mark indicating the start of a new argument stack
frame; push an SV containing the integer value 1; push the SV currently
associated with the variable \f(CW$x\fR; and push the \f(CW*foo\fR typeglob. Then
the PP function \f(CWpp_entersub()\fR associated with the \f(CW\*(C`OP_ENTERSUB\*(C'\fR will
pop that typeglob, extract the \f(CW&foo\fR CV from it, and see whether it is a
normal CV or an XSUB CV.
.PP
For a normal Perl subroutine call, \f(CWpp_entersub()\fR will then: pop the
topmost mark off the mark stack; pop the SV pointers between that mark and
the top of the stack and store them in \f(CW@_\fR; then set \f(CW\*(C`PL_op\*(C'\fR to the
first OP pointed to by the \f(CW&foo\fR CV. Those OPs will then be run by the
main loop, until the OPs associated with the last statement of the
function (or an explicit return) will leave any return values as SV
pointers on the stack.
.PP
For an XSUB sub, \f(CWpp_entersub()\fR will instead note the value of the
topmost mark (but not pop it) and call the C function pointed to from the
CV; this is the XSUB which has been generated by the XS parser. The XSUB
itself is responsible for popping the mark stack, doing any processing of
its arguments on the stack, and then pushing return values. But note that
for straightforward XSUBs, this is usually all done by boilerplate code
generated by the XS parser. Exactly what is done automatically and what
can be overridden and handled manually if needed, is one of the themes of
this document. Finally, \f(CWpp_entersub()\fR will do any post\-processing of
the returned values; for example discarding all but the top\-most stack
item if the function call was in scalar context.
.PP
\fIAn SV\*(Aqs reference count\fR
.IX Subsection "An SV's reference count"
.PP
Perl uses reference counting as its garbage collection method. One of the
always\-present fields in an SV is its reference count, accessible as
\&\f(CWSvREFCNT(sv)\fR.
.PP
Usually an SV\*(Aqs reference count is incremented each time a pointer to the
SV is stored somewhere, and decremented any time such a pointer is
removed. When the reference count reaches zero, any destructor associated
with that SV is called, then the SV is freed. Mismanaging reference counts
can lead to SVs leaking or being prematurely freed.
.PP
When relying on XS to generate all the boilerplate code, reference count
bookkeeping is usually handled for you automatically. Once you start
handling this yourself, then there are some specific considerations.
.PP
Functions which create a new SV, such as \f(CWnewSViv(i)\fR, return an SV
that has an initial \f(CWSvREFCNT()\fR of \fIone\fR. This is actually one too
high, since there are not yet any pointers to this SV stored anywhere. The
expectation is that the SV will shortly be embedded somewhere \- such as
stored in an array \- which will take "ownership" of that one count. If the
program calls \f(CWcroak()\fR or similar before the new SV has been embedded,
then it will leak. Note that \f(CWcroak()\fR can be trapped by \f(CWeval()\fR, so
it\*(Aqs possible that \f(CWcroak()\fR could be called many times, leaking each
time. Note also that many things may indirectly trigger a \f(CWcroak()\fR. For
example accessing the value of an SV associated with a tied variable may
trigger a call to its \f(CWFETCH()\fR method, which could call \f(CW\*(C`die\*(C'\fR. So a new
SV needs to be embedded quickly.
.PP
Since such new SVs already have a reference count of one, when embedding
them it should be done in a way which doesn\*(Aqt increase its reference
count. For example, this modifies \f(CW\*(C`sv\*(C'\fR to be a reference to a
newly\-created SV holding an integer value, i.e. the perl equivalent of
\&\f(CW\*(C`$sv = \e99\*(C'\fR:
.PP
.Vb 1
\&    sv_setrv_noinc(sv, newSViv(99));
.Ve
.PP
The \f(CW\*(C`_noinc\*(C'\fR variant is used here as it doesn\*(Aqt increment the reference
count of the integer\-valued SV when creating a reference to it.
.PP
Where appropriate, reference counts can be adjusted with \f(CWSvREFCNT_inc()\fR
and \f(CWSvREFCNT_dec()\fR and their variants.
.PP
An exception to this system is the argument stack. Pointers on the
argument stack to SVs do \fInot\fR contribute to the reference count of that
SV. The code typically generated by XS takes advantage of this. For
example when ready to return a single value, the XSUB just stores a new SV
pointer at the base of the current stack frame, overwriting the old value,
then resets the argument stack pointer to the base of the frame plus one,
and returns. All the original values on the stack are discarded, without
adjusting any reference counts.
.PP
This can be a problem if the XSUB is returning a new SV. Since this SV
isn\*(Aqt embedded anywhere apart from on the stack (which doesn\*(Aqt hold a
reference count to it), then if the code croaks, the SV on the stack will
leak. To avoid this, there is a separate \fItemps\fR stack in the Perl
interpreter. Items on this stack \fIare\fR reference counted. Typically the
temps stack is reset at the start of each statement, back to some
particular level. Each SV above this level has its reference count
decremented. Putting an SV on the temps stack is referred to as
\&\fImortalising\fR it. It is common to create a new SV and mortalise it at the
same time: here are some examples:
.PP
.Vb 2
\&    SV *sv_99  = sv_2mortal(newSViv(99));
\&    SV *sv_abc = newSVpvn_flags("abc", 3, SVs_TEMP);
.Ve
.PP
Many OPs have an SV attached to them called a \fIPADTMP\fR. This SV has a
long lifetime which is the same as the sub which the OP is a part of
(typically it is created when a named sub is compiled and freed when that
sub is deleted, often at the end of the execution of the program),
and usually has a reference count of one. It is used by many OPs to avoid
having to create (and later free) a temporary SV to return a value. For
example the \f(CW\*(C`ADD\*(C'\fR op in \f(CW\*(C`$a + $b\*(C'\fR typically extracts the integer values
of its two arguments, calculates its sum, sets its \f(CW\*(C`PADTMP\*(C'\fR to that value
and pushes it onto the stack. The \f(CW\*(C`OP_ENTERSUB\*(C'\fR which typically invokes
an XSUB usually has a \f(CW\*(C`PADTMP\*(C'\fR attached to it, and when returning a
value, the XSUB\*(Aqs boilerplate code generated by XS will usually try to use
it to return the value, rather than creating a fresh mortal SV on each
call.
.PP
Note that there is a \fIhighly experimental\fR perl interpreter build option,
\&\f(CW\*(C`PERL_RC_STACK\*(C'\fR, under which the argument stack \fIis\fR reference counted,
but that is currently beyond the scope of this document.
.PP
\fIThe IV, NV etc types\fR
.IX Subsection "The IV, NV etc types"
.PP
An \f(CW\*(C`IV\*(C'\fR (Integer Value) is a typedef in the perl interpreter\*(Aqs header
files that maps to a C integer. The exact integer type and size will
depend on the build configuration of the interpreter. It is guaranteed to
be large enough to hold a pointer. A \f(CW\*(C`UV\*(C'\fR is the same but unsigned. An
\&\f(CW\*(C`NV\*(C'\fR (numeric value) is a floating\-point value; usually a \f(CW\*(C`double\*(C'\fR.
These types are used widely within the perl interpreter.
.PP
A PV (pointer value) "type" is often used informally within documentation
and within the names of structure fields etc to refer to a string pointer
(\f(CW\*(C`char*\*(C'\fR), but it is not actually a declared type. Similarly, RV
(reference value) is informally a pointer to another SV.
.PP
There are also \f(CW\*(C`SSize_t\*(C'\fR and \f(CW\*(C`Size_t\*(C'\fR, which are large enough to hold
signed and unsigned integer values representing the number of items in a C
array. \f(CW\*(C`STRLEN\*(C'\fR is used specifically for variables which store the number
of characters in a string (it is typically just an alias for \f(CW\*(C`Size_t\*(C'\fR).
.PP
\fIThe SV scalar value structure\fR
.IX Subsection "The SV scalar value structure"
.PP
(Again there is a lot of detail in this section that you may not need to
know when just creating simple XSUBs, but is useful background for
debugging.)
.PP
As mentioned above, almost all runtime data within the perl interpreter is
stored in an SV (scalar value) structure. The head of an SV structure
consists of three or four fields: a reference count; a type and flags; a
pointer to a body; and since perl 5.10.0, a general payload field. There
are around 17 types, and the type indicates what body (if any) is pointed
to from the SV\*(Aqs head. The body type only indicates what \fIsorts\fR of data
the body is capable of holding; the actual "type" of the SV (IV, NV, PV,
RV etc) is mostly indicated by what flags are set.
.PP
Simple SVs may not have a body. Undefined values typically don\*(Aqt have one.
Also, some IV, NV, and RV values are stored directly in the payload field.
In this case the body pointer is faked up to point back to the head, but
with a suitable offset so that an attempt to access the IV field (for
example) within the "body" actually reads the IV value in the head\*(Aqs
payload field.
.PP
For SVs which have a body, the payload field in the head is usually used
to store one common value which would otherwise have to be stored in the
body and require a further pointer indirection to access. For example, the
\&\f(CW\*(C`char*\*(C'\fR pointer of a perl string SV is stored in the head, while the
length is stored in the body.
.PP
The fields of an SV (both in the head and in the body) are usually
accessed via macros, which has allowed various rearrangements of the head
and body fields over the years while maintaining backwards compatibility.
Always use the macros. For example, \f(CWSvIVX(sv)\fR directly accesses the IV
field of the SV (which may be in the head or body depending on the SV\*(Aqs
type). If the SV has a valid integer value, then the \f(CW\*(C`SVf_IOK\*(C'\fR flag will
be set, which can be tested with the macro \f(CWSvIOK(sv)\fR.
.PP
The body of an SV may be upgraded to a "bigger" one during the SV\*(Aqs
lifetime, but it is not usually downgraded. For example, during the course
of executing this perl code:
.PP
.Vb 4
\&    my $x;
\&    $x = "1";
\&    $u = $x + 1;
\&    undef $x;
.Ve
.PP
Initially the SV has no body and none of the \f(CW\*(C`SVf_IOK\*(C'\fR, \f(CW\*(C`SVf_NOK\*(C'\fR,
\&\f(CW\*(C`SVf_POK\*(C'\fR, nor \f(CW\*(C`SVf_ROK\*(C'\fR flags are set, indicating that it has neither
an IV, NV, PV or RV value. The complete lack of those flags indicates an
undefined value. After the string is assigned to it, its body type is set
to \f(CW\*(C`SVt_PV\*(C'\fR, and it is given the corresponding body. The string pointer
and length are stored in the body (or perhaps the pointer in the payload
word), and the \f(CW\*(C`SVf_POK\*(C'\fR flag is set, indicating that the SV holds a
valid string value.
.PP
When Perl wants to use that SV as an integer, it uses a macro like
\&\f(CWSvIV(sv)\fR to return the integer value. Unlike the direct \f(CWSvIVX()\fR
macro, this first checks \f(CWSvIOK(sv)\fR, and if not true, calls a function
which calculates the integer value from its current string value. The
effect of this call is to update the SV\*(Aqs type and body to \f(CW\*(C`SVt_PVIV\*(C'\fR
which is capable of holding both a string \fIand\fR and integer value, and
then to set the \f(CW\*(C`SVf_IOK\*(C'\fR flag in addition to the \f(CW\*(C`SVf_POK\*(C'\fR flag.
.PP
Finally, the \f(CW\*(C`undef\*(C'\fR frees the string and turns off the \f(CW\*(C`SVf_IOK\*(C'\fR and
\&\f(CW\*(C`SVf_POK\*(C'\fR flags, but leaves the body type as \f(CW\*(C`SVt_PVIV\*(C'\fR. (Hence why an
SV\*(Aqs current Perl\-level type should be determined by its flags, not its
body type.)
.PP
Note that you should never directly access fields using macros like
\&\f(CWSvIVX()\fR (the \f(CW\*(C`X\*(C'\fR implies direct) \fIunless\fR you have just tested for
the corresponding flag, e.g. \f(CWSvIOK()\fR. In general, always use macros
such as \f(CWSvIV()\fR, which will do any checking and conversion for you.
.PP
There is a further complication with SVs: they can have one or more items
of \fImagic\fR attached to them. These are small payloads, along with a
pointer to a jump table of pointers to functions with get/set etc actions.
They are used to implement things like \f(CW$1\fR, \f(CW$.\fR and tied variables.
The idea is that macros like \f(CWSvIV()\fR will first check whether the SV has
\&\fIget\fR magic (using \f(CWSvGMAGICAL(sv)\fR); and if so call its get method
first. For example, for a tied variable, this C\-level get function will
call the perl\-level \f(CWFETCH()\fR method and assign the return value of that
to the SV. Only then will \f(CWSvIV()\fR do its \f(CWSvIOK()\fR check.
.PP
When presented with an unknown SV, it should always have its magic checked
before examining the values of the SVs flags.
.PP
In total, the \f(CWSvIV(sv)\fR macro does roughly the equivalent of:
.PP
.Vb 5
\&    if (SvGMAGICAL(sv))
\&        mg_get(sv);   /* do FETCH() etc; update the SV\*(Aqs value / flags */
\&    if (!SvIOK(sv))
\&        sv_2iv(sv);   /* convert undef to 0, "1" to 1 etc */
\&    return SvIVX(sv); /* use the raw value */
.Ve
.PP
You will see soon that XS\*(Aqs typemap templates mostly use high\-level macros
like \f(CWSvIV()\fR, so this is usually all handled automatically for you. Only
if you start to do your own type conversions will you need to worry about
these details.
.PP
Forgetting to test for, and to call, \f(CW\*(C`get\*(C'\fR magic will typically appear to
work fine until the first time someone passes a tied variable or similar
to your XSUB, and \f(CWFETCH()\fR doesn\*(Aqt get called. Accessing fields with
\&\f(CWSvPVX()\fR etc without testing for \f(CWSvPOK()\fR first may access a field in
a body which doesn\*(Aqt exist and possibly trigger a SEGV.
.PP
Magic should only be called once per "use"; for example if a tied scalar
is passed as an argument to your XSUB, you would expect \f(CWFETCH()\fR to only
be called once. Normally this is easy because you (or the typemap code)
does a single \f(CWSvIV()\fR call. Occasionally you may have explicitly called
\&\f(CWmg_get()\fR first, perhaps in order to check some flags; if so, you can
skip a second magic call with variants like \f(CWSvIV_nomg()\fR. For example:
.PP
.Vb 7
\&    SvGETMAGIC(sv); /* this calls mg_get() if SvGMAGICAL() */
\&    if (SvNOK(sv))
\&        /* special\-case: do something with a floating\-point value */
\&    else {
\&        IV i = SvIV_nomg(sv);
\&        /* fall\-back to treating it as an integer value */
\&    }
.Ve
.PP
A Perl reference is just another type of scalar. It is indicated by
\&\f(CWSvROK()\fR being true, and the pointer to the referent SV is accessed
using \f(CWSvRV()\fR.
.PP
The equivalent of \f(CWSvIV()\fR for strings is \f(CWSvPV()\fR (and variants, such
as \f(CW\*(C`SvPVutf8\*(C'\fR):
.PP
.Vb 2
\&    STRLEN len;
\&    char *pv = SvPV(sv, len);
.Ve
.PP
which both retrieves a string pointer and sets \f(CW\*(C`len\*(C'\fR to its length.
(\f(CW\*(C`SvPV\*(C'\fR is a macro, which is how it can update \f(CW\*(C`len\*(C'\fR without needing an
explicit \f(CW&len\fR.) Note that there is no guarantee that after this call
\&\f(CWSvPOK(sv)\fR is true, nor that \f(CW\*(C`pv == SvPVX(sv)\*(C'\fR. For example, \f(CW\*(C`sv\*(C'\fR may
be a reference to a blessed object with an overloaded stringify (\f(CW""\fR)
method.  In which case, behind the scenes there may be a temporary SV
containing the result of the call to the method, with \f(CW\*(C`pv\*(C'\fR pointing to
\&\fIthat\fR SV\*(Aqs string buffer; \f(CW\*(C`sv\*(C'\fR remains a reference. Similarly, a
non\-overloaded reference to an array may return a temporary string like
\&\f(CW"ARRAY(0x12345678)"\fR.
.PP
If you need to coerce an SV to a string (e.g. before directly modifying
its string buffer) then use \f(CWSvPV_force()\fR or one of its variants. For
example if used on an array reference, the SV will be converted from a
reference into a plain string SV with an \f(CWSvPVX()\fR value of
\&\f(CW"ARRAY(0x12345678)"\fR, and the array\*(Aqs reference count decremented.
.PP
Once an SV has been coerced into a PV (\f(CWSvPOK(sv)\fR is true), then
\&\f(CWSvLEN(sv)\fR represents the size of the allocated buffer, while
\&\f(CWSvCUR(sv)\fR represents the current length (in bytes) of the string. Note
that with Unicode, \f(CWSvCUR(sv)\fR may not necessarily equal the value
returned by the Perl built\-in \f(CWlength(sv)\fR, which is the length in
\&\fIcharacters\fR. That can be obtained using the \f(CWsv_len_utf8(sv)\fR function.
See "Unicode and UTF\-8" below for more details.
.PP
The SV structure can also be used to store things which aren\*(Aqt simple
scalar values: in particular, arrays, hashes and code values. There are
typedefs for AV, HV and CV structures (plus a few others). These
structures are identical to SVs and can generally be used interchangeably
with suitable casting, e.g. \f(CW\*(C`SV *ret = (SV*)av\*(C'\fR. The main feature of
these non\-scalar SVs is that the value of the type field in these cases,
\&\f(CW\*(C`SVt_PVAV\*(C'\fR, \f(CW\*(C`SVt_PVHV\*(C'\fR, \f(CW\*(C`SVt_PVCV\*(C'\fR etc, actually \fIdo\fR indicate the
Perl type, rather than just indicating what sort of body they have.
.PP
An important thing to note is that AVs and HVs are never directly pushed
onto the stack when calling and returning from subroutines and XSUBs.
Instead where necessary, references (RVs) to them are pushed: either
automatically via suitable typemaps, or using \f(CWnewRV()\fR or similar. You
will likely first spot such an error when you start getting "Bizarre copy
of ..." error messages.
.PP
\fIUnicode and UTF\-8\fR
.IX Subsection "Unicode and UTF-8"
.PP
A simple Perl string SV uses what is sometimes referred to as byte
encoding: each character is represented using a single byte. But when a
Perl string contains code points >= 0x100, each character of the string is
stored as a variable number of bytes using the UTF\-8 encoding scheme, with
the \f(CWSvUTF8(sv)\fR flag being set to indicate this. Other strings may or
may not be using UTF\-8 encoding, depending on the history of the string.
For example, with:
.PP
.Vb 3
\&    my $s = "A\ex80";
\&    $s .= "\ex{100}";
\&    chop $s;
.Ve
.PP
the string starts off in byte encoding, with \f(CW\*(C`SvCUR(sv) == 2,
sv_len_utf8(sv) == 2\*(C'\fR and with each byte representing one character. When
the extra character is appended, the string gets upgraded to UTF\-8, with
\&\f(CW\*(C`SvCUR(sv) == 5, sv_len_utf8(sv) == 3\*(C'\fR and the second and third
characters each using two bytes of storage. Once the third character is
removed, the string stays in UTF\-8 encoding, with \f(CW\*(C`SvCUR(sv) == 3,
sv_len_utf8(sv) == 2\*(C'\fR and the second character using two bytes. So such a
string SV when passed to an XSUB has two possible representations; and
which will be used is somewhat unpredictable.
.PP
Unfortunately XS currently has no support for UTF\-8. All the standard
typemap entries, such as \f(CW\*(C`char *\*(C'\fR, assume that the buffer of a string SV
is just an array of bytes to be manipulated by the XSUB or passed on
uninterpreted to a C function. If it is necessary for the XSUB to control
the UTF\-8 status of an argument, then it is best to declare the parameter
as type \f(CW\*(C`SV*\*(C'\fR and do your own manipulation of it. Similarly for returning
string values.
.PP
An SV\*(Aqs string representation can be forced to bytes using \f(CWSvPVbyte()\fR
and variants; if the string contains any characters not representable in
a single byte, then that call croaks with a \f(CW\*(C`Wide character\*(C'\fR error.
Conversely, \f(CWSvPVutf8()\fR and variants will force the string to UTF\-8.
.PP
See perlunicode for more details.
.SS "The Anatomy of an XSUB"
.IX Subsection "The Anatomy of an XSUB"
The previous section has explained how arguments are pushed onto the
stack, what those arguments look like, and how XSUBs are called. We will
now look at what happens \fIinside\fR an XSUB function once called; in
particular, how it retrieves values from its arguments on the stack and
later returns a value or values on the stack; and how XS and typemaps
automate most of this.
.PP
This section will provide both an overview of what an XSUB looks like in
XS, \fIand\fR what sort of C code is generated for it. The majority of the
rest of this document will then describe in more detail the various parts
of an XSUB mentioned here. Note that the various keywords within an XSUB\*(Aqs
definition usually correspond closely (and in the same order) to what C
code is generated for the XSUB. Most of the boilerplate code generated for
an XSUB is concerned with getting argument values off the stack at the
start, then returning zero or one result values on the stack at the end.
.PP
A typical XSUB definition might look like:
.PP
.Vb 1
\&    MODULE = Foo::Bar PACKAGE = Foo::Bar
\&
\&    short
\&    baz(int a, char *b = "")
\&      PREINIT:
\&        long z = ...;
\&      CODE:
\&        ... do stuff ...;
\&        RETVAL = some_function(a, b, z);
\&      OUTPUT:
\&        RETVAL
.Ve
.PP
The first two lines of an XSUB are its declaration, which must be preceded
by a blank line. It gives the XSUB\*(Aqs return type, its name, and its
parameters (including any default values). While it is modelled on C
syntax, it is actually XS syntax (so for example \f(CW\*(C`/* ... */\*(C'\fR isn\*(Aqt
recognised). The return type and name must both start on column one,
although the XS parser actually allows both to be on the same line, such
as
.PP
.Vb 1
\&    short baz(...)
.Ve
.PP
This XSUB definition will be translated into a C function whose start may
look something like this (the exact details may vary across XS parser
releases):
.PP
.Vb 6
\&    void
\&    XS_Foo_\|_Bar_baz(pTHX_ CV* cv)
\&    {
\&        dVAR; dXSARGS;
\&        if (items < 1 || items > 2)
\&           croak_xs_usage(cv,  "a, b= \e"\e"");
.Ve
.PP
Note that the first line of the function is actually specified using a
macro such as \f(CWXS_EXTERNAL()\fR, but for explanatory purposes, what is
shown above is one possible expansion of that macro, depending on the Perl
version and XS configuration.
.PP
The important thing to note is that the XSUB\*(Aqs arguments are \fInot\fR passed
as arguments of the C function; they are still on the Perl argument stack.
Nor is the XSUB\*(Aqs return value returned by the C function.
.PP
The C function\*(Aqs name is based on the XSUB\*(Aqs name plus the current XS
package (with \f(CW\*(C`s/:/_/g\*(C'\fR). Apart from debugging, you don\*(Aqt generally need
to know this name.
.PP
The function\*(Aqs parameters are the CV associated with this XSUB (i.e.
\&\f(CW&Foo::Bar::baz\fR) and, on MULTIPLICITY/threaded builds, a pointer to the
current Perl interpreter context. You won\*(Aqt need to directly use these
most of the time.
.PP
The first few lines of code in the C function are standard boilerplate
added to all XSUBs.  Note that the naming convention for Perl
interpreter macros is that ones starting with a \f(CW\*(C`d\*(C'\fR are declarations; they
go in places where a variable can be declared, and typically declare one
or more variables and possibly their initialisations.
.PP
\&\f(CW\*(C`dVAR\*(C'\fR is mostly a no\-op; it used to be needed for some obscure Perl
interpreter configurations and is still emitted for
backwards compatibility.
.PP
\&\f(CW\*(C`dXSARGS\*(C'\fR pops one index off the mark stack and sets up some auto
variables to allow the arguments on the stack to be accessed:
specifically, the variable \f(CW\*(C`items\*(C'\fR is declared, which indicates how many
arguments were passed, and some hidden variables are also declared which
are used by the macro \f(CWST(n)\fR to retrieve a pointer to argument \f(CW\*(C`n\*(C'\fR from
the stack (counting from 0). The stack pointer is not actually decremented
yet.
.PP
For a generic list\-processing XSUB, these argument\-accessing variables and
macros may be used directly. But more commonly, for an XSUB which has a
fixed signature (as in the example above), the parser will declare an auto
C variable for each parameter, and (using the system or a user typemap)
assign them values extracted from \f(CWST(0)\fR etc.  It will also declare a
variable called \f(CW\*(C`RETVAL\*(C'\fR with the XSUB\*(Aqs return type (unless that is
\&\f(CW\*(C`void\*(C'\fR), which is typically assigned to by the coder and then whose value
is automatically returned. Continuing the example above, the generated
code for the input part of the XSUB is similar to:
.PP
.Vb 5
\&    {
\&        long z = ...;
\&        short RETVAL;
\&        int   a = (int)SvIV(ST(0));
\&        char *b;
\&
\&        if (items < 2)
\&            b = "";
\&        else
\&            b = (char *)SvPV_nolen(ST(1));
.Ve
.PP
This consists of declarations for \f(CW\*(C`a\*(C'\fR, \f(CW\*(C`b\*(C'\fR, \f(CW\*(C`z\*(C'\fR and \f(CW\*(C`RETVAL\*(C'\fR, plus
code to initialise them. The part of the code which extracts a value from
an SV on the stack, such as \f(CW\*(C`(int)SvIV(ST(0))\*(C'\fR, is derived from a typemap
entry. For a simple entry such the one for \f(CW\*(C`a\*(C'\fR, the code may be added as
part of the declaration of the variable itself; otherwise the
initialisation may be done as a separate statement after all the variable
declarations (such as for \f(CW\*(C`b\*(C'\fR).
.PP
Variable declarations appear in the order they appear in \f(CW\*(C`INPUT\*(C'\fR and
\&\f(CW\*(C`PREINIT\*(C'\fR blocks, followed by \f(CW\*(C`RETVAL\*(C'\fR and then any parameters defined
completely within the signature (i.e. which don\*(Aqt use an \f(CW\*(C`INPUT\*(C'\fR section
to specify their type).
.PP
Note that \f(CW\*(C`INPUT\*(C'\fR sections are generally obsolete these days, and
\&\f(CW\*(C`PREINIT\*(C'\fR is rarely needed. Perls before 5.36 used C89 compiler
semantics, which didn\*(Aqt allow variable declarations after statements. CPAN
modules, depending on if/how they set compiler flags, may still default
to C89. To work around this, the \f(CW\*(C`PREINIT\*(C'\fR keyword allows you to inject
additional variable declaration code early in the function.
.PP
Following on from the input part, the main body of the function is output;
this is copied exactly as\-is from the \f(CW\*(C`CODE\*(C'\fR or \f(CW\*(C`PPCODE\*(C'\fR section, if
present. If neither is present, the parser will assume that this XSUB is
just wrapping a C library function of the same name as the XSUB, and will
automatically generate some code like the following:
.PP
.Vb 1
\&    RETVAL = baz(a, b);
.Ve
.PP
The \f(CW\*(C`INIT\*(C'\fR and \f(CW\*(C`POSTCALL\*(C'\fR keywords may be used to add code just before
and after the main code; typically only useful for autocall.
.PP
\&\f(CW\*(C`PPCODE\*(C'\fR is the same as \f(CW\*(C`CODE\*(C'\fR except that after argument processing,
the stack pointer is reset to the base of the frame, and the coder becomes
responsible for pushing any return values onto the stack. No further
keywords can follow \f(CW\*(C`PPCODE\*(C'\fR.  This is typically used for XSUBs which
need to return a list or have other complex requirements beyond just
returning a single value.
.PP
For \f(CW\*(C`CODE\*(C'\fR and autocall, unless the return type is void, the parser will
generate code to return the value of \f(CW\*(C`RETVAL\*(C'\fR. This is automatic in the
case of autocall, but for \f(CW\*(C`CODE\*(C'\fR you have to ask the parser to do so
with \f(CW\*(C`OUTPUT: RETVAL\*(C'\fR. The code generated in either case may look
something like
.PP
.Vb 5
\&    {
\&        SV *RETVALSV = sv_newmortal();
\&        sv_setiv(RETVALSV, (IV)RETVAL);
\&        ST(0) = RETVALSV;
\&    }
.Ve
.PP
A temporary SV will be created, set to the value of \f(CW\*(C`RETVAL\*(C'\fR (again,
using a typemap template), then placed on the stack. In practice, various
optimisations may be used; in particular, the \f(CW\*(C`PADTMP\*(C'\fR target SV which is
attached to the calling \f(CW\*(C`OP_ENTERSUB\*(C'\fR may be used instead of allocating
and freeing an SV for each call, as explained earlier.
.PP
XSUB parameters declared as \f(CW\*(C`OUT\*(C'\fR or \f(CW\*(C`OUTLIST\*(C'\fR will cause additional
output code to be generated which respectively: updates the value of one
of the passed arguments; or pushes the value of that parameter onto the
stack (in addition to \f(CW\*(C`RETVAL\*(C'\fR).
.PP
Finally, (apart from \f(CW\*(C`PPCODE\*(C'\fR), a macro like this is added to the end of
the C function:
.PP
.Vb 1
\&    XSRETURN(1);
.Ve
.PP
This resets the stack pointer to one above the base of the frame (so the
top item on the stack is \f(CWST(0)\fR), then does \f(CW\*(C`return\*(C'\fR.
.PP
For a \f(CW\*(C`void\*(C'\fR XSUB, \f(CW\*(C`XSRETURN_EMPTY\*(C'\fR is used instead.
.SS "Returning Values from an XSUB"
.IX Subsection "Returning Values from an XSUB"
An XSUB\*(Aqs declared return type is typically a C type such as \f(CW\*(C`int\*(C'\fR or
\&\f(CW\*(C`char*\*(C'\fR. XS is very good at automating this common case of returning a
single C\-ish value: behind the scenes it creates a temporary SV; then,
using an appropriate typemap template, sets that SV to the value of
\&\f(CW\*(C`RETVAL\*(C'\fR and returns that SV on the stack.
.PP
But sometimes you want to return a Perl\-ish value rather than a C\-ish
value, for example, Perl\*(Aqs undef value or a Perl array reference. Or you
may want to return multiple values, or update one of the passed
arguments. The following subsections describe various such cases.
.PP
Note that XSUBs are somewhat like Perl lvalue subs, in that they return
the actual SV to the caller, while normal Perl subs return a temporary
copy of each return value. When returning a C value like \f(CW\*(C`int\*(C'\fR this
doesn\*(Aqt matter, since the XSUB is returning a temporary SV anyway; but
when returning your own SV, it could in theory make a visible difference.
For example,
.PP
.Vb 2
\&    sub foo { $_[0]++ }
\&    foo(an_xsub_which_returns_element_0_of_an_array(\e@a));
.Ve
.PP
would increment \f(CW$a[0]\fR.
.PP
\fIReturning undef / TRUE / FALSE / empty list\fR
.IX Subsection "Returning undef / TRUE / FALSE / empty list"
.PP
Sometimes you need to return an undefined value, e.g. to indicate failure.
It\*(Aqs possible to return early from a CODE block with an undefined value,
bypassing the normal creation of a temporary SV and the setting of its
value. For example:
.PP
.Vb 8
\&    int
\&    file_size(char *filename)
\&      CODE:
\&        RETVAL = file_size(filename);
\&        if (RETVAL == \-1)
\&            XSRETURN_UNDEF;
\&      OUTPUT:
\&        RETVAL
.Ve
.PP
The \f(CW\*(C`XSRETURN_UNDEF\*(C'\fR macro causes the address of the special Perl SV
\&\f(CW\*(C`PL_sv_undef\*(C'\fR to be stored at \f(CWST(0)\fR (which is the same value that the
Perl function \f(CW\*(C`undef\*(C'\fR returns), and then makes the XSUB return
immediately.
.PP
If using autocall, then you can instead return early in a \f(CW\*(C`POSTCALL\*(C'\fR
section:
.PP
.Vb 5
\&    int
\&    file_size(char *filename)
\&      POSTCALL:
\&        if (RETVAL == \-1)
\&            XSRETURN_UNDEF;
.Ve
.PP
There are similar macros
.PP
.Vb 3
\&    XSRETURN_YES
\&    XSRETURN_NO
\&    XSRETURN_EMPTY
.Ve
.PP
which allow you to return Perl\*(Aqs true and false values, or to return
an empty list.
.PP
If your XSUB will always explicitly return a special SV and won\*(Aqt ever
require typemap conversions (e.g. it always returns via \f(CW\*(C`XSRETURN_YES\*(C'\fR or
\&\f(CW\*(C`XSRETURN_NO\*(C'\fR), then just declare the return type as \f(CW\*(C`SV*\*(C'\fR.
.PP
Note that any early return from an XSUB should always be via one of the
\&\f(CW\*(C`XSRETURN\*(C'\fR macros and not directly via \f(CW\*(C`return\*(C'\fR; the former will do any
bookkeeping associated with the argument stack.
.PP
\fIReturning an SV*\fR
.IX Subsection "Returning an SV*"
.PP
More generally, you may want to create and return an SV yourself, rather
than relying on the boilerplate XSUB code to generate a temporary SV and
set it to a C\-ish value. Here you would declare the return type as \f(CW\*(C`SV*\*(C'\fR.
For example:
.PP
.Vb 6
\&    SV*
\&    abc(bool uc)
\&      CODE:
\&        RETVAL = newSVpv(uc ? "ABC" : "abc", 3);
\&      OUTPUT:
\&        RETVAL
.Ve
.PP
There is some special processing which happens when using a return type
such as \f(CW\*(C`SV*\*(C'\fR. First, consider that for a C return type like \f(CW\*(C`int\*(C'\fR, the
typemap template which sets the temporary SV\*(Aqs value may look something
like:
.PP
.Vb 1
\&    sv_setiv($arg, (IV)$var);
.Ve
.PP
which after expansion may look like:
.PP
.Vb 1
\&    sv_setiv(RETVALSV, (IV)RETVAL);
.Ve
.PP
where the temporary SV has previously been assigned to \f(CW\*(C`RETVALSV\*(C'\fR.
.PP
Now, if you declare an XSUB with a return type of \f(CW\*(C`SV*\*(C'\fR, you \fImight\fR
expect the typemap template to look something like:
.PP
.Vb 1
\&    sv_setsv($arg, (SV*)$var);
.Ve
.PP
This Perl library function copies the value of one SV to another (the
XS user\*(Aqs equivalent of the Perl \f(CW\*(C`$a = $b\*(C'\fR).
.PP
However, the design decision was made that for the \f(CW\*(C`SV*\*(C'\fR type in
particular, the typemap template would be
.PP
.Vb 1
\&    $arg = $var;
.Ve
.PP
Here is where the special processing comes in. The XS compiler, in the
case of an output template beginning \f(CW\*(C`$arg = ...\*(C'\fR, skips creating a
temporary SV, and just returns the SV in \f(CW\*(C`RETVAL\*(C'\fR directly. So the
typemap template would be expanded to
.PP
.Vb 1
\&    ST(0) = RETVAL;
.Ve
.PP
This is faster than copying.
.PP
But in addition, for \fIany\fR \f(CW\*(C`$arg = ...\*(C'\fR template (not just the template
for \f(CW\*(C`SV*\*(C'\fR), the XS compiler makes one further assumption: that the
expression to the right of the assign evaluates to an SV with a reference
count \fIone too high\fR, and so in addition, the XS compiler emits:
.PP
.Vb 1
\&    sv_2mortal(RETVAL);
.Ve
.PP
or similar, which causes the reference count of the SV to be decremented
by one at (typically) the start of the next statement. This makes sense if
the SV is newly created with one of the \f(CWnewSVfoo()\fR family of functions:
see the discussion on this in "An SV\*(Aqs reference count"
.PP
However, if the SV comes from elsewhere, for example via a Perl array
lookup, then its reference count doesn\*(Aqt need to be adjusted, and so the
mortalising will cause it to be prematurely freed. In this case, you need
to artificially increase the SV\*(Aqs reference count: typically using
\&\f(CWSvREFCNT_inc()\fR, as shown below.
.PP
The previous example showed creating a new SV using \f(CWnewSVpv()\fR; here\*(Aqs an
example where the SV pre\-exists in an array:
.PP
.Vb 12
\&    SV*
\&    lookup(int i)
\&      CODE:
\&        {
\&            SV** svp = av_fetch(some_array_AV, i, 0);
\&            if (!svp)
\&                XSRETURN_UNDEF;
\&            /* compensate for the implicit mortalisation */
\&            RETVAL = SvREFCNT_inc(*svp);
\&        }
\&      OUTPUT:
\&        RETVAL
.Ve
.PP
Finally, note that some very old (pre\-1996) XS documentation suggested
that you could return your own SV using code like:
.PP
.Vb 4
\&    void
\&    foo(...)
\&      CODE:
\&        ST(0) = some_SV;
.Ve
.PP
This is very wrong, as the \f(CW\*(C`void\*(C'\fR declaration tells the XS code to expect
to return \fIzero\fR items on the stack. There is still come code like this
in the wild, and to work around it, the XS compiler does a very special
and ugly hack for a \f(CW\*(C`void\*(C'\fR XSUB when it sees \f(CWST(0)\fR being assigned to
within a \f(CW\*(C`CODE\*(C'\fR block: it pretends that the XSUB was actually declared as
returning \f(CW\*(C`SV*\*(C'\fR and so emits \f(CWXSRETURN(1)\fR rather than
\&\f(CW\*(C`XSRETURN_EMPTY\*(C'\fR.  But don\*(Aqt rely on this: it is likely to warn
eventually. If your XSUB is doing its own setting of \f(CWST(0)\fR, then always
declare the return type as \f(CW\*(C`SV*\*(C'\fR.
.PP
The mark stack isn\*(Aqt used when returning arguments; instead, the caller of
the XSUB (usually the \f(CW\*(C`OP_ENTERSUB\*(C'\fR) notes the offset of the base of
the argument stack frame before calling the XSUB and the offset of the
stack pointer on return, and can deduce the number of returned arguments
from that.
.PP
\fIReturning AV* etc refs\fR
.IX Subsection "Returning AV* etc refs"
.PP
Sometimes you want to return a non\-scalar SV, such as an AV, HV or CV.
However, these aren\*(Aqt allowed directly on the argument stack. You are
supposed to instead return a \fIreference\fR to the AV: a bit like a Perl sub
returning \f(CW\*(C`\e@foo\*(C'\fR.
.PP
The standard typemaps can create this reference for you automatically. So
for example an XSUB with a return type of \f(CW\*(C`AV*\*(C'\fR will actually create and
return an RV scalar which references the AV in \f(CW\*(C`RETVAL\*(C'\fR. So the XS
equivalent of Perl\*(Aqs \f(CW\*(C`return [8,9]\*(C'\fR might be:
.PP
.Vb 10
\&    AV *
\&    array89()
\&      CODE:
\&        RETVAL = newAV();
\&        /* see text below for why this line is needed */
\&        sv_2mortal((SV*)RETVAL);
\&        av_store(RETVAL, 0, newSViv(8));
\&        av_store(RETVAL, 1, newSViv(9));
\&      OUTPUT:
\&        RETVAL
.Ve
.PP
Note that the \f(CW\*(C`RETVAL\*(C'\fR variable is declared as type \f(CW\*(C`AV*\*(C'\fR, but what is
actually returned to the caller is a temporary SV which is a reference to
\&\f(CW\*(C`RETVAL\*(C'\fR. The standard output typemap template for the \f(CW\*(C`AV*\*(C'\fR type looks
like:
.PP
.Vb 1
\&    $arg = newRV((SV*)$var);
.Ve
.PP
This means it creates a new RV which refers to to the AV. Because of the
rule for \f(CW\*(C`$arg = ...\*(C'\fR typemaps, the RV will be correctly mortalised
before being returned. However, the \f(CWnewRV()\fR function increments the
reference count of the thing being referred to (the \f(CW\*(C`RETVAL\*(C'\fR AV in this
case). Since the AV has just been created by \f(CWnewAV()\fR with a reference
count one too high, it will leak. This why the \f(CWsv_2mortal()\fR is
required.  Conversely for a pre\-existing AV, the mortalisation isn\*(Aqt
required.
.PP
Since \fIxsubpp\fR 3.06, there are a set of alternative XS types which can be
used for AVs etc which \fIdon\*(Aqt\fR increment the reference count of the AV
when being pointed to from the new RV. These can be enabled by mapping the
\&\f(CW\*(C`AV*\*(C'\fR etc C types to these new XS types:
.PP
.Vb 6
\&    TYPEMAP: <<EOF
\&    AV*   T_AVREF_REFCOUNT_FIXED
\&    HV*   T_HVREF_REFCOUNT_FIXED
\&    CV*   T_CVREF_REFCOUNT_FIXED
\&    SVREF T_SVREF_REFCOUNT_FIXED
\&    EOF
.Ve
.PP
Or alternatively you could just declare the return type as \f(CW\*(C`SV*\*(C'\fR and
handle the RV generation yourself:
.PP
.Vb 6
\&    SV *
\&    create_array_ref()
\&      CODE:
\&        RETVAL =  newRV_noinc((SV*)newAV());
\&      OUTPUT:
\&        RETVAL
.Ve
.PP
If instead you want to return a flattened array (the equivalent of Perl\*(Aqs
\&\f(CW\*(C`return @a\*(C'\fR) then you would have to push the elements of the array
individually onto the stack in a \f(CW\*(C`PPCODE\*(C'\fR block. See "Returning a
list" below.
.PP
Finally, the C \f(CW\*(C`SVREF\*(C'\fR type in the standard typemap is a way of creating
and returning a \fIreference\fR to a scalar. This is in contrast to the
\&\f(CW\*(C`SV*\*(C'\fR type, which just returns a scalar.
.PP
Note that unlike \f(CW\*(C`SV\*(C'\fR etc, \f(CW\*(C`SVREF\*(C'\fR isn\*(Aqt a standard built\-in Perl type:
it exists purely as an entry in a typemap. So In this case you have to
tell the C compiler that \f(CW\*(C`SVREF\*(C'\fR is just another name for \f(CW\*(C`SV*\*(C'\fR:
.PP
.Vb 1
\&    typedef SV *SVREF;
.Ve
.PP
Then in an XSUB like
.PP
.Vb 7
\&    SVREF
\&    foo()
\&      CODE:
\&        RETVAL = newSViv(9);
\&        sv_2mortal(RETVAL);
\&      OUTPUT:
\&        RETVAL
.Ve
.PP
\&\f(CW\*(C`RETVAL\*(C'\fR will be declared with type \f(CW\*(C`SVREF\*(C'\fR (hence the need for the
typedef above), and the XSUB will return a reference the \f(CW\*(C`RETVAL\*(C'\fR SV.
This XSUB is the equivalent of the perl \f(CW\*(C`my $x = 9; return \e$x\*(C'\fR.
.PP
\fIUpdating arguments and returning multiple values.\fR
.IX Subsection "Updating arguments and returning multiple values."
.PP
By using the \f(CW\*(C`IN_OUT\*(C'\fR and similar parameter modifiers, XS provides
limited support for returning extra values in addition to (or instead of)
\&\f(CW\*(C`RETVAL\*(C'\fR, either by updating the values of passed arguments (\f(CW\*(C`OUT\*(C'\fR), or
by returning some of the parameters (and pseudo\-parameters) as extra
return values (\f(CW\*(C`OUTLIST\*(C'\fR). For returning an arbitrary list of values, see
the next section.
.PP
Here are a couple of simple XS examples with their approximate perl
equivalents:
.PP
.Vb 1
\&    # Update a passed argument
\&
\&    void                          sub inc9 {
\&    inc9(IN_OUT int i)                my $i = $_[0];
\&      CODE:                           $i += 9;
\&        i += 9                        $_[0] = $i;
\&                                  }
\&
\&    # Return (2*$i, 3*$i)
\&
\&    void                         sub mul23 {
\&    mul23(int i, \e                   my $i = $_[0];
\&          OUTLIST int x, \e           my ($x, $y);
\&          OUTLIST int y)             $x = $i * 2;
\&      CODE                           $y = $i * 3;:
\&        x = i * 2;                   return $x, $y;
\&        y = i * 3;               }
.Ve
.PP
See "Updating and returning parameter values: the IN_OUT etc keywords"
for the full details,
.PP
\fIReturning a list\fR
.IX Subsection "Returning a list"
.PP
If you want to return a list, i.e. an arbitrary number of items on the
stack, you generally have to forgo the convenience of some of the
boilerplate code generated by XS, which is biased towards returning a
single value. Instead you will have to create and push the SVs yourself.
The PPCODE keyword is specifically intended for
this purpose. Here is a simple example which does the same as the
Perl\-level \f(CW\*(C`return 1..$n\*(C'\fR:
.PP
.Vb 12
\&    void
\&    one_to_n(int n)
\&      PPCODE:
\&        {
\&            int i;
\&            if (n < 1)
\&                Perl_croak_nocontext(
\&                    "one_to_n(): argument %d must be >= 1", n);
\&            EXTEND(SP, n);
\&            for (i = 1; i <= n; i++)
\&                mPUSHi(i);
\&        }
.Ve
.PP
The \f(CW\*(C`PPCODE\*(C'\fR keyword causes the argument stack pointer to be initially
reset to the base of the frame (discarding any passed arguments), and
suppresses any automatic return code generation. The return type of the
XSUB is ignored, except that declaring it \f(CW\*(C`void\*(C'\fR suppresses the
declaration of a \f(CW\*(C`RETVAL\*(C'\fR variable.
.PP
The \f(CWEXTEND()\fR macro makes sure that there are at least that many free
slots on the stack (its first argument should always be \f(CW\*(C`SP\*(C'\fR). The
\&\f(CWmPUSHi()\fR macro creates a new SV, mortalises it, sets its value to the
integer \f(CW\*(C`i\*(C'\fR, and pushes it on the stack.
.PP
Here\*(Aqs another example, which flattens the array passed as an argument:
the equivalent of this Perl:
.PP
.Vb 1
\&    sub flatten { my $aref = $_[0]; @$aref: }
.Ve
.PP
In this example, the SVs being pushed aren\*(Aqt freshly created with a
reference count one too high, so don\*(Aqt need mortalising.
.PP
.Vb 10
\&    void
\&    flatten(AV *av)
\&      PPCODE:
\&        {
\&            int i;
\&            int max_ix = AvFILL(av);
\&            SV **svp;
\&            EXTEND(SP, max_ix + 1);
\&            for (i = 0; i <= max_ix; i++)  {
\&                svp = av_fetch(av, i, 0);
\&                PUSHs(svp ? *svp : &PL_sv_undef);
\&            }
\&        }
.Ve
.PP
This function actually expects to be passed a \fIreference\fR to an array:
the input typemap entry for \f(CW\*(C`AV*\*(C'\fR automatically takes care of
dereferencing the argument and croaking if it\*(Aqs not actually a reference.
The \f(CWPUSHs()\fR macro simply pushes an SV onto the stack, without any
mortalising or copying. Any "holes" in the array are filled with undefs.
.PP
Note that there is a \f(CWXPUSHs()\fR macro which combines a push with an
\&\f(CWEXTEND(1)\fR; but if you know at the start how many items are to be
pushed, it is more efficient to do a single large extend first.
.PP
Note also that there is always guaranteed to be one allocated slot on the
stack when an XSUB is called, even if it has no arguments. So for the
particular case of returning a single value, no extend is necessary.
.SS Bootstrapping
.IX Subsection "Bootstrapping"
In addition to the \f(CW\*(C`XS_Foo_\|_Bar_baz()\*(C'\fR C function generated for each XSUB
declaration, a \f(CW\*(C`boot_Foo_\|_Bar()\*(C'\fR C function is also automatically
generated, one for each XS file. This XSUB function is called once when
the module is first loaded. For each declared XSUB in the file, a line
similar to the following is added to the boot function:
.PP
.Vb 1
\&        newXS("Foo::Bar::baz", XS_Foo_\|_Bar_baz);
.Ve
.PP
(the exact details of the code will vary across releases and
configurations).  This call creates a CV, flags it as being an XSUB, adds
a pointer from it to \f(CW\*(C`XS_Foo_\|_Bar_baz()\*(C'\fR, then adds the CV to the
\&\f(CW*FOO::Bar::baz\fR typeglob in the Perl interpreter\*(Aqs symbol table. It is
the XS equivalent of the Perl\-level
.PP
.Vb 1
\&    *FOO::Bar::baz  = sub { ... }
.Ve
.PP
For some XSUBs, additional lines may be added by the parser to the boot
XSUB to handle things like aliases or overloading.
.PP
You can add your own additional lines to the boot XSUB using the \f(CW\*(C`BOOT\*(C'\fR
keyword.
.PP
A typical Perl module like \fIFoo/Bar.pm\fR should have code in it similar
to:
.PP
.Vb 4
\&    package Foo::Bar;
\&    our $VERSION = \*(Aq1.01\*(Aq;
\&    require XSLoader;
\&    XSLoader::load();
.Ve
.PP
This causes the \fIBar.so\fR or \fIBar.dll\fR file to be dynamically linked in
and then the \f(CW\*(C`boot_Foo_\|_Bar()\*(C'\fR function to be called. This boilerplate
code is typically created automatically with \fIh2xs\fR when you first create
the skeleton of a new distribution. See perlxstut for more details.
.SH "REFERENCE MANUAL"
.IX Header "REFERENCE MANUAL"
This part of the document explains what each XS keyword does. They are
arranged in the approximate order in which they might appear within an XS
file, and then might appear within an XSUB declaration. Related keywords
are grouped together.
.SS "The MODULE Declaration"
.IX Subsection "The MODULE Declaration"
.Vb 3
\&    MODULE = Foo::Bar  PACKAGE = Foo::Bar
\&    MODULE = Foo::Bar  PACKAGE = Foo::Bar::Baz
\&    MODULE = Foo::Bar  PACKAGE = Foo::Bar      PREFIX = foobar_
.Ve
.PP
The \f(CW\*(C`MODULE\*(C'\fR keyword is used to start the XS half of the file, and to
specify the package of the functions which are being defined. The
\&\f(CW\*(C`MODULE\*(C'\fR keyword must start on column one. All text preceding the first
\&\f(CW\*(C`MODULE\*(C'\fR keyword is considered C code and is passed through to the output
with POD stripped, but otherwise untouched.
.PP
It is usually necessary to include a blank line before each MODULE
declaration.
.PP
For the first such declaration, the \f(CW\*(C`MODULE\*(C'\fR and \f(CW\*(C`PACKAGE\*(C'\fR values are
typically the same. In subsequent entries, the \f(CW\*(C`PACKAGE\*(C'\fR value varies,
while the \f(CW\*(C`MODULE\*(C'\fR value is kept unchanged. In fact, only the \f(CW\*(C`MODULE\*(C'\fR
value from the \fIlast\fR such declaration is used, and specifies the name of
the boot XSUB which is called when the module is loaded (typically via
\&\f(CW\*(C`use Foo::Bar\*(C'\fR).
.PP
The value of the \f(CW\*(C`PACKAGE\*(C'\fR keyword is analogous to the Perl \f(CW\*(C`package\*(C'\fR
keyword, and determines which package any subsequent XSUBs will be created
in. It is permissible to have the same \f(CW\*(C`PACKAGE\*(C'\fR value appear more than
once, again similarly to Perl.
.PP
In theory the \f(CW\*(C`PACKAGE\*(C'\fR keyword is optional, and defaults to \f(CW\*(Aq\*(Aq\fR. This
means that any subsequent XSUBs will be placed in the \f(CW\*(C`main::\*(C'\fR package.
In practice, you should always specify the package.
.PP
The optional \f(CW\*(C`PREFIX\*(C'\fR value is stripped from the XSUB\*(Aqs name when
generating the XSUB\*(Aqs Perl name. It is typically used to simplify creating
autocall XSUBs. It addresses the issue that while Perl has package names,
C only has function name prefixes. Consider a C library called \f(CW\*(C`foobar\*(C'\fR,
which has functions such as \f(CWfoobar_read()\fR and \f(CWfoobar_write()\fR. We
want to make these accessible from a Perl module called \f(CW\*(C`Foo::Bar\*(C'\fR. In
the presence of \f(CW\*(C`PREFIX = foobar_\*(C'\fR, any such prefix of each XSUB
name will be stripped off when determining the XSUB\*(Aqs Perl name. For
example:
.PP
.Vb 1
\&    MODULE = Foo::Bar  PACKAGE = Foo::Bar  PREFIX = foobar_
\&
\&    char* foobar_read(int n)
\&
\&    int   foobar_write(char *text, int n)
.Ve
.PP
This will insert two XSUBs into the Perl namespace, called
\&\f(CWFoo::Bar::read()\fR and \f(CWFoo::Bar::write()\fR, which when called, will
themselves call the C functions \f(CWfoobar_read()\fR and \f(CWfoobar_write()\fR.
.SS "File\-scoped XS Keywords and Directives"
.IX Subsection "File-scoped XS Keywords and Directives"
After the first \f(CW\*(C`MODULE\*(C'\fR keyword, everything else in the file consists of
XSUB definitions, plus anything that comes between the XSUBs. The XSUBs
will be explained further down, but this section addresses the in\-between
stuff, which can consist of any of the following.
.IP \(bu 4
A few file\-scoped keywords (including further MODULE declarations), whose
effects usually last for the rest of the file. These keywords will be
detailed further down in this section.
.IP \(bu 4
POD, which is stripped out. It must be terminated with \f(CW\*(C`=cut\*(C'\fR.
.IP \(bu 4
Blank lines, which are discarded.
.IP \(bu 4
Known \f(CW\*(C`/^#/\*(C'\fR C preprocessor directives, which are passed through as\-is.
Conditional ones, such as \f(CW\*(C`#if\*(C'\fR and \f(CW\*(C`#else\*(C'\fR, have some basic analysis
performed on them which, in particular, allows two variants of the same
XSUB to be declared without raising a "duplicate XSUB" warning. This
warning suppression only works when an else branch is present. For example
this works:
.Sp
.Vb 1
\&    #ifdef USE_2ARG
\&
\&    int foo(int a, int b)
\&
\&    #else
\&
\&    int foo(int a)
\&
\&    #endif
.Ve
.Sp
while this form will still raise warnings:
.Sp
.Vb 3
\&    #ifdef USE_2ARG
\&    ...
\&    #endif
\&
\&    #ifndef USE_2ARG
\&    ...
\&    #endif
.Ve
.IP \(bu 4
XS comment lines, which are stripped out; either a \f(CW\*(C`/^#/\*(C'\fR which isn\*(Aqt
recognised as a C preprocessor directive, or \f(CW\*(C`/^\es+#\*(C'\fR/.
.IP \(bu 4
Anything else is an error, unless it starts on column one, in which case
it will be treated as the start of a new XSUB.
.PP
The following file\-scoped keywords are supported.  Note that the
SCOPE can technically be a
file\-scoped keyword too, but is described further down as an XSUB keyword.
.PP
\fIThe REQUIRE: Keyword\fR
.IX Subsection "The REQUIRE: Keyword"
.PP
.Vb 1
\&    REQUIRE: 3.58
.Ve
.PP
The \f(CW\*(C`REQUIRE\*(C'\fR keyword is used to indicate the minimum version of the
\&\f(CW\*(C`ExtUtils::ParseXS\*(C'\fR XS compiler (and its \fIxsubpp\fR wrapper) needed to
compile the XS module. It is expected to be a floating\-point number of the
form \f(CW\*(C`/\ed+\e.\ed+/\*(C'\fR. It is analogous to the way that \f(CW\*(C`use v5.xx\*(C'\fR indicates
the minimum version of the perl interpreter needed in a Perl program.
.PP
\fIThe VERSIONCHECK: Keyword\fR
.IX Subsection "The VERSIONCHECK: Keyword"
.PP
.Vb 1
\&    VERSIONCHECK: DISABLE | ENABLE
.Ve
.PP
Version checking (enabled by default) checks that the version compiled
into the \f(CW\*(C`.so\*(C'\fR or \f(CW\*(C`.dll\*(C'\fR file matches the \f(CW\*(C`.pm\*(C'\fR file\*(Aqs \f(CW$VERSION\fR
value, and if not, dies with an error message like:
.PP
.Vb 1
\&    Foo::Bar object version 1.03 does not match bootstrap parameter 1.04
.Ve
.PP
Typically, when a module is built for the first time, the value of the
\&\f(CW$VERSION\fR variable in the \f(CW\*(C`.pm\*(C'\fR file is copied to the generated
\&\f(CW\*(C`Makefile\*(C'\fR as \f(CW\*(C`XS_VERSION\*(C'\fR, and from there, via a \f(CW\*(C`\-DXS_VERSION=...\*(C'\fR
compiler option, is baked into the boot XSUB. When the module is loaded
and the boot code called, the versions are compared, and it croaks if
there\*(Aqs a mismatch. This usually indicates that the \f(CW\*(C`.so\*(C'\fR and \f(CW\*(C`.pm\*(C'\fR
files are from different installs: for example someone copied over a more
recent version of the \f(CW\*(C`.pm\*(C'\fR file but forgot to copy or rebuild the
\&\f(CW\*(C`.so\*(C'\fR.
.PP
If the version of the PM module is a floating point number, it will be
stringified before the comparison, with a possible loss of precision
(currently chopping to nine decimal places), so it may not match the
version of the XS module any more. Quoting the \f(CW$VERSION\fR declaration to
make it a string is recommended if long version numbers are used.
.PP
There is rarely any good reason to disable this check.
.PP
Note that this module version checking is completely unrelated to the
\&\f(CW\*(C`REQUIRE\*(C'\fR keyword, which is a check against the version of the \fIXS
compiler\fR.
.PP
The \f(CW\*(C`VERSIONCHECK\*(C'\fR keyword corresponds to \fIxsubpp\fR\*(Aqs \f(CW\*(C`\-versioncheck\*(C'\fR
and \f(CW\*(C`\-noversioncheck\*(C'\fR options. This keyword overrides the command line
options.
.PP
\fIThe PROTOTYPES: Keyword\fR
.IX Subsection "The PROTOTYPES: Keyword"
.PP
.Vb 1
\&    PROTOTYPES: DISABLE | ENABLE
.Ve
.PP
When prototypes are enabled (they are disabled by default), any
subsequent XSUBs will be given a Perl prototype. The prototype string is
usually generated from the XSUB\*(Aqs parameter list. This keyword may be used
multiple times in an XS module to enable and disable prototypes for
different parts of the module.
.PP
For example, these two XSUB declarations:
.PP
.Vb 1
\&    int add1(int a, int b)
\&
\&    PROTOTYPES: ENABLE
\&
\&    int add2(int a, int b)
.Ve
.PP
behave similarly to the perl\-level:
.PP
.Vb 2
\&    sub add1     { ... }
\&    sub add2($$) { ... }
.Ve
.PP
Note also that prototypes can be overridden on a per\-XSUB basis with the
XSUB\-level PROTOTYPE keyword.
.PP
In general, XSUB prototypes (similarly to perl sub prototypes) are of very
limited use and are typically only used to mimic the behaviour of Perl
builtins. For example there is no way to implement a \f(CW\*(C`push @a, ...;\*(C'\fR
style function without a way of telling the Perl interpreter not to
flatten \f(CW@a\fR. Outside of these narrow uses, it is generally a mistake to
use prototypes.
.PP
In the early days of XS it was thought that using prototypes was probably
a Good Thing, and prototypes were enabled by default. This was soon
changed to disabled by default, and a warning was added if you haven\*(Aqt
explicitly indicated your preference: so in the absence of any
\&\f(CW\*(C`PROTOTYPES\*(C'\fR keyword, you will get this nagging warning:
.PP
.Vb 1
\&    Please specify prototyping behavior for Foo.xs (see perlxs manual)
.Ve
.PP
So 99% of the time you will want to add
.PP
.Vb 1
\&    PROTOTYPES: DISABLE
.Ve
.PP
to the start of the XS half of your \f(CW\*(C`.xs\*(C'\fR file.
.PP
The \f(CW\*(C`PROTOTYPES\*(C'\fR keyword corresponds to \fIxsubpp\fR\*(Aqs \f(CW\*(C`\-prototypes\*(C'\fR and
\&\f(CW\*(C`\-noprototypes\*(C'\fR options.
.PP
See "Prototypes" in perlsub for more information about Perl prototypes.
.PP
\fIThe EXPORT_XSUB_SYMBOLS: Keyword\fR
.IX Subsection "The EXPORT_XSUB_SYMBOLS: Keyword"
.PP
.Vb 1
\&    EXPORT_XSUB_SYMBOLS: ENABLE | DISABLE
.Ve
.PP
This keyword is present since \fIxsubpp\fR 3.04, and its value is disabled by
default.
.PP
Before 3.04, the C function which implemented an XSUB was exported. Since
3.04, it is declared \f(CW\*(C`static\*(C'\fR by default. The old behaviour can be
restored by enabling it. You are very unlikely to have a need for this
keyword.
.PP
\fIThe INCLUDE: Keyword\fR
.IX Subsection "The INCLUDE: Keyword"
.PP
.Vb 2
\&    INCLUDE: const\-xs.inc
\&    INCLUDE: some_command |
.Ve
.PP
This keyword can be used to pull in the contents of another file to the
"XS" part of an XS file. Unlike a top\-level XS file, included files don\*(Aqt
have a "C" first half, and the entire contents of the file are treated as
XS, as if it had all been inserted at that line.
.PP
One common use of \f(CW\*(C`INCLUDE\*(C'\fR is to include constant definitions generated
by \fIExtUtils::Constant\fR.
.PP
If the parameters to the \f(CW\*(C`INCLUDE\*(C'\fR keyword are followed by a pipe (\f(CW\*(C`|\*(C'\fR)
then the XS parser will interpret the parameters as a command. This
feature is mildly deprecated in favour of the \f(CW\*(C`INCLUDE_COMMAND:\*(C'\fR
directive, as documented below. The latter can be used to ensure that the
perl (if any) used in the command is the same as the one running the XS
parser.
.PP
\fIThe INCLUDE_COMMAND: Keyword\fR
.IX Subsection "The INCLUDE_COMMAND: Keyword"
.PP
.Vb 1
\&    INCLUDE_COMMAND: $^X \-e \*(Aq...\*(Aq
.Ve
.PP
Since \fIxsubpp\fR 2.2205.
.PP
Similar to \f(CW\*(C`INCLUDE: some_command|\*(C'\fR except that the \f(CW\*(C`|\*(C'\fR is implicit, and
it converts the special token \f(CW$^X\fR, if present, to the path of the perl
interpreter which is running the XS parser.
.PP
\fIThe TYPEMAP: Keyword\fR
.IX Subsection "The TYPEMAP: Keyword"
.PP
.Vb 9
\&    TYPEMAP: <<EOF
\&    myint  T_MYIV
\&    INPUT
\&        T_MYIV
\&            $var = ($type)my_SvIV($arg)
\&    OUTPUT
\&        T_MYIV
\&            my_sv_setiv($arg, (IV)$var);
\&    EOF
.Ve
.PP
Since \fIxsubpp\fR 3.01.
.PP
Typemaps are mappings and code templates which allow the XS parser to
automatically generate code snippets which convert between Perl and C
values. The \f(CW\*(C`TYPEMAP\*(C'\fR keyword can be used to embed typemap declarations
directly into your XS code, instead of (or in addition to) typemaps in a
separate file. Multiple such embedded typemaps will be processed in order
of appearance in the XS code. Typemaps are processed in the order:
.IP \(bu 4
The system typemap file.
.IP \(bu 4
A local typemap file, typically specified by \f(CW\*(C`xsubpp \-typemap typemap\*(C'\fR
in the \fIMakefile\fR.
.IP \(bu 4
\&\f(CW\*(C`TYPEMAP:\*(C'\fR entries, in order.
.PP
The most recently applied entries take precedence, so for example you can
use \f(CW\*(C`TYPEMAP:\*(C'\fR to individually override specific \f(CW\*(C`TYPEMAP\*(C'\fR, \f(CW\*(C`INPUT\*(C'\fR, or
\&\f(CW\*(C`OUTPUT\*(C'\fR entries in the system typemap. In general, typemap changes
affect any subsequent XSUBs within the file, until further updates.
.PP
Note however that, due to a quirk in parsing, it is possible in \fIxsubpp\fR
prior to 3.61 for a \f(CW\*(C`TYPEMAP:\*(C'\fR block which comes \fIimmediately after\fR an
XSUB to affect any entries used by that XSUB, as if the block had appeared
just before the XSUB. If all such typemap blocks are placed near the start
of an XS file, then this won\*(Aqt be an issue. Indeed, it can only be a
possible issue if you want typemap meanings to change during the course of
an XS file (which is rare).
.PP
The \f(CW\*(C`TYPEMAP\*(C'\fR keyword syntax is intended to mimic Perl\*(Aqs "heredoc"
syntax, and the keyword must be followed by one of these three forms:
.PP
.Vb 3
\&    <<  FOO
\&    << \*(AqFOO\*(Aq
\&    << "FOO"
.Ve
.PP
where \f(CW\*(C`FOO\*(C'\fR can be just about any sequence of characters, which must be
matched at the start of a subsequent line.
.PP
See "Using Typemaps" and perlxstypemap for more details on writing
typemaps.
.PP
\fIThe BOOT: Keyword\fR
.IX Subsection "The BOOT: Keyword"
.PP
.Vb 3
\&    BOOT:
\&        # Print a message when the module is loaded
\&        printf("Hello from the bootstrap!\en");
.Ve
.PP
The \f(CW\*(C`BOOT\*(C'\fR keyword is used to add code to the extension\*(Aqs bootstrap
function. This function is generated by the XS parser and normally holds
the statements necessary to register any XSUBs with Perl. It is usually
called once, at \f(CW\*(C`use Foo::Bar\*(C'\fR time.
.PP
This keyword should appear on a line by itself. All subsequent lines will
be interpreted as lines of C code to pass through, including C
preprocessor directives, but excluding POD and \f(CW\*(C`#\*(C'\fR comments; until the
next keyword or possible start of a new XSUB (\f(CW\*(C`/\en\en\eS/\*(C'\fR).
.PP
\fIThe FALLBACK: Keyword\fR
.IX Subsection "The FALLBACK: Keyword"
.PP
.Vb 1
\&    MODULE = Foo PACKAGE = Foo::Bar
\&
\&    FALLBACK: TRUE | FALSE | UNDEF
.Ve
.PP
Since \fIxsubpp\fR 2.09_01.
.PP
It defaults to \f(CW\*(C`UNDEF\*(C'\fR for each package. It sets the default fallback
handling behaviour for overloaded methods in the current package (i.e.
\&\f(CW\*(C`Foo:Bar\*(C'\fR in the example above). It is analogous to the Perl\-level:
.PP
.Vb 2
\&    package Foo::Bar;
\&    use overload "fallback" => 1 | 0 | undef;
.Ve
.PP
It only has any effect if there ends up being at least one XSUB in the
current package with the OVERLOAD keyword
present. See "fallback" in overload for more details.
.SS "The Structure of an XSUB"
.IX Subsection "The Structure of an XSUB"
Following any file\-scoped XS keywords and directives, an XSUB may appear.
The start of an XSUB is usually indicated by a blank line followed by
something starting on column one which isn\*(Aqt otherwise recognised as an
XSUB keyword or file\-scoped directive.
.PP
An XSUB definition consists of a declaration (typically two lines),
followed by an optional body. The declaration specifies the XSUB\*(Aqs name,
parameters and return type. The body consists of sections started by
keywords, which may specify how its parameters and any return value
should be processed, and what the main C code body of the XSUB consists
of. Other keywords can change the behaviour of the XSUB, or affect how it
is registered with Perl, e.g. with extra named aliases. In the absence of
an explicit main C code body specified by the \f(CW\*(C`CODE\*(C'\fR or \f(CW\*(C`PPCODE\*(C'\fR
keywords, the parser will generate a body automatically; this is referred
to as autocall in this document.
.PP
Nothing can appear between keyword sections apart from POD, XS comments,
and trailing blank lines, all of which are stripped out before the main
parsing takes place. Anything else will either raise an error, or be
interpreted as the start of a new XSUB.
.PP
An XSUB\*(Aqs body can be thought of as having up to five parts. These are, in
order of appearance, the Input, Init, Code, Output and Cleanup parts. There is no
formal syntax to define this structure; it\*(Aqs just an understanding that
certain keywords may only appear in certain parts and thus may only appear
after certain other keywords etc.
.SS "An XSUB Declaration"
.IX Subsection "An XSUB Declaration"
.Vb 1
\&    # A simple declaration:
\&
\&    int
\&    foo1(int i, char *s)
\&
\&    # All on one line; plus a default parameter value:
\&
\&    int foo2(int i, char *s = "")
\&
\&    # Complex parameters; plus variable argument count:
\&
\&    int
\&    foo3(OUT int i, IN_OUTLIST char *s, STRLEN length(s), ...)
\&
\&    # No automatic argument processing:
\&
\&    void
\&    foo4(...)
\&        PPCODE:
\&
\&    # C++ method; plus various return type qualifiers:
\&
\&    NO_OUTPUT extern "C" static int
\&    X::Y::foo5(int i, char *s) const
.Ve
.PP
An XSUB declaration consists of a return type, name, parameters, and
optional \f(CW\*(C`NO_OUTPUT\*(C'\fR, \f(CW\*(C`extern "C"\*(C'\fR, \f(CW\*(C`static\*(C'\fR and \f(CW\*(C`const\*(C'\fR keywords.
.PP
\fIAn XSUB\*(Aqs return type and the NO_OUTPUT keyword\fR
.IX Subsection "An XSUB's return type and the NO_OUTPUT keyword"
.PP
The return type can be any valid C type, including \f(CW\*(C`void\*(C'\fR. When non\-void,
it serves two purposes. First, it causes a C auto variable of that type
to be declared, called \f(CW\*(C`RETVAL\*(C'\fR. Second, it (usually) makes the XSUB
return a single SV whose value is set to \f(CW\*(C`RETVAL\*(C'\fR\*(Aqs value at the time of
return. In addition, a non\-void autocall XSUB will call the underlying C
library function and assign its return value to \f(CW\*(C`RETVAL\*(C'\fR.
.PP
In addition the return type can be a Perl package name; see
"Fully\-qualified type names and Perl objects" for details.
.PP
If the return type is prefixed with the \f(CW\*(C`NO_OUTPUT\*(C'\fR keyword, then the
\&\f(CW\*(C`RETVAL\*(C'\fR variable is still declared, but code to return its value is
suppressed. It is typically useful when making an autocall function
interface more Perl\-like, especially when the C return value is just an
error condition indicator. For example,
.PP
.Vb 6
\&    NO_OUTPUT int
\&    delete_file(char *name)
\&      # implicit autocall code here: RETVAL = delete_file(name);
\&      POSTCALL:
\&        if (RETVAL != 0)
\&            croak("Error %d while deleting file \*(Aq%s\*(Aq", RETVAL, name);
.Ve
.PP
Here the generated XS function returns nothing on success, and will
\&\f(CWdie()\fR with a meaningful error message on error. The XSUB\*(Aqs return type
of \f(CW\*(C`int\*(C'\fR is only meaningful for declaring \f(CW\*(C`RETVAL\*(C'\fR and for doing the
autocall.
.PP
The return type can also include the \f(CW\*(C`extern "C"\*(C'\fR and \f(CW\*(C`static\*(C'\fR
modifiers, which if present must be in that order, and come between any
\&\f(CW\*(C`NO_OUTPUT\*(C'\fR keyword and the return type. The \f(CW\*(C`extern\*(C'\fR declaration must
be written exactly as shown, i.e. with a single space and with double
quotes around the \f(CW\*(C`C\*(C'\fR. These two modifiers are mainly of use for XSUBs
written in C++. A C++ XSUB declaration is also allowed to have a trailing
\&\f(CW\*(C`const\*(C'\fR keyword, which mimics the C++ syntax. See "Using XS With C++"
for more details.
.PP
\fIAn XSUB\*(Aqs name\fR
.IX Subsection "An XSUB's name"
.PP
The name of the XSUB is usually put on the line following the return type,
in which case it must be on column one. It is permissible for both the
type and name to be on the same line.
.PP
The name can be any valid Perl subroutine name. The \f(CW\*(C`PACKAGE\*(C'\fR value from
the most recent \f(CW\*(C`MODULE\*(C'\fR declaration is used to give the XSUB it\*(Aqs
fully\-qualified Perl name.
.PP
If the name includes the package separator, \f(CW\*(C`::\*(C'\fR, then it is treated as
a C++ method declaration, and various extra bits of processing take place,
such as declaring an implicit \f(CW\*(C`THIS\*(C'\fR parameter. The XSUB\*(Aqs \fIPerl\fR
package name is still determined by the current XS package, and not the
C++ class name. See "Using XS With C++" for more details.
.PP
\fIAn XSUB\*(Aqs parameter list\fR
.IX Subsection "An XSUB's parameter list"
.PP
Following the XSUB\*(Aqs name, there is a comma\-separated list of parameters
within parentheses. Although this looks superficially the same as a C
function declaration, it is different. In particular, it is parsed by the
XS compiler, which is a simple regex\-based text processor and which
doesn\*(Aqt understand the full C type syntax; nor does it recognise C\-style
comments.
.PP
In fact all it does is extract the text between the \f(CW\*(C`(...)\*(C'\fR and split on
commas, while having enough intelligence to ignore commas and a closing
parenthesis within a quoted string. Once each parameter declaration is
extracted, it is processed, as described below in "An XSUB Parameter".
.PP
Each parameter declaration usually generates a C auto variable declaration
of the same name, along with initialisation code which assigns the value
of the corresponding passed argument to that variable. Under some
circumstances code can also be generated to return the value too.
.PP
Note that the original XS syntax required the type for each parameter to
be specified separately in one or more INPUT sections, mimicking pre\-C89
"K&R" C syntax. To support this, directly after the declaration there is an
implicit INPUT section, without a need to include the actual keyword. You
will see this pattern very frequently in older XS code.
.PP
Old style with an implicit INPUT keyword (a common pattern):
.PP
.Vb 6
\&    int
\&    foo(a, b)
\&        long  a
\&        char *b
\&      CODE:
\&        ...
.Ve
.PP
Old style with explicit INPUT keyword (unusual):
.PP
.Vb 7
\&    int
\&    foo(a, b)
\&      INPUT:
\&        long  a
\&        char *b
\&      CODE:
\&        ...
.Ve
.PP
New style (recommended for new code):
.PP
.Vb 4
\&    int
\&    foo(long a, char *b)
\&      CODE:
\&        ...
.Ve
.PP
Generally there is no reason to use the old style any more, apart from a
few obscure features that can be specified on an INPUT line but not in the
signature.
.SS "An XSUB Parameter"
.IX Subsection "An XSUB Parameter"
Some examples of valid XSUB parameter declarations:
.PP
.Vb 10
\&    char *foo             # parameter with type
\&    Foo::Bar foo          # parameter with Perl package type
\&    char *foo = "abc"     # default value
\&    char *foo = NO_INIT   # doesn\*(Aqt complain if arg missing
\&    OUT char *foo         # caller\*(Aqs arg gets updated
\&    IN_OUTLIST char *foo  # parameter value gets returned
\&    int length(foo)       # pseudo\-parameter that gets the length of foo
\&    foo                   # placeholder, or parameter without type
\&    SV*                   # placeholder
\&    ...                   # ellipsis: zero or more further arguments
.Ve
.PP
The most straightforward type of declaration in an XSUB\*(Aqs parameter list
consists of just a C type followed by a parameter name, such as \f(CWchar
*foo\fR. This has two main effects. First, it causes a C auto variable of
that name to be declared; and second, the variable is initialised to the
value of the passed argument which corresponds to that parameter. For
example,
.PP
.Vb 2
\&    void
\&    foo(int i, char *s)
.Ve
.PP
is roughly equivalent to the Perl:
.PP
.Vb 5
\&    sub foo {
\&        my $i = int($_[0]);
\&        my $s = "$_[1]";
\&        ...
\&    }
.Ve
.PP
and the generated C code may look something like:
.PP
.Vb 2
\&    if (items != 2)
\&       croak_xs_usage(cv,  "i, s");
\&
\&    {
\&        int   i = (int)SvIV(ST(0));
\&        char *s = (char *)SvPV_nolen(ST(1));
\&        foo(i, s); /* autocall */
\&        ...
\&    }
.Ve
.PP
In addition to the variable declaration and initialisation, the name of
the parameter will usually be used in the usage message and in any
autocall, as shown above. These variables are accessible for any user code
in a \f(CW\*(C`CODE\*(C'\fR block or similar. Their values aren\*(Aqt normally returned.
.PP
There are several variations on this basic pattern, which are explained in
the following subsections.
.PP
\fIFully\-qualified type names and Perl objects\fR
.IX Subsection "Fully-qualified type names and Perl objects"
.PP
.Vb 2
\&    Foo::Bar
\&    foo(Foo::Bar self, ...)
.Ve
.PP
Normally the type of an XUB\*(Aqs parameter or return value is a valid C type,
such as \f(CW"char *"\fR. However you can also use Perl package names. When a
type name includes a colon, it undergoes some extra processing; in
particular, the actual type as emitted into the C file is transformed
using \f(CW\*(C`s/:/_/g\*(C'\fR (unless \fIxsubpp\fR has been invoked with \f(CW\*(C`\-hiertype\*(C'\fR), so
that a legal C type is present. The complete effects for a type of
\&\f(CW\*(C`Foo::Bar\*(C'\fR are as follows.
.PP
The type string \f(CW\*(C`Foo::Bar\*(C'\fR is looked up in the typemap \fIas\-is\fR to find
the logical XS type; then the \f(CW\*(C`INPUT\*(C'\fR and \f(CW\*(C`OUTPUT\*(C'\fR typemap templates are
expanded with the \f(CW$ntype\fR variable set to \f(CW"Foo::Bar"\fR and the \f(CW$type\fR
variable set to \f(CW"Foo_\|_Bar"\fR. The declaration of the corresponding auto
variables uses the modified type string, so the example above might
result in these declarations in the C code:
.PP
.Vb 2
\&    Foo_\|_Bar  RETVAL;
\&    Foo_\|_Bar  self   = ...;
.Ve
.PP
With the appropriate XS typemap entries and C typedefs, this can be used
to assist in declaring XSUBs which are passed and return Perl objects.
See "T_PTROBJ and opaque handles" for an example of this using
the common \f(CW\*(C`T_PTROBJ\*(C'\fR typemap type.
.PP
Note that any check on whether the passed Perl object is of the correct
class is down to the implementation in the particular typemap: for
example, \f(CW\*(C`T_PTROBJ\*(C'\fR will croak unless the passed SV argument is blessed
into the \f(CW\*(C`Foo::Bar\*(C'\fR or derived class.
.PP
\fIXSUB Parameter Placeholders\fR
.IX Subsection "XSUB Parameter Placeholders"
.PP
Sometimes you want to skip an argument. There are two supported techniques
for efficiently declaring a placeholder. Both of these will completely
skip any declaration and initialisation of a C auto variable, but will
still consume an argument.
.PP
A bare parameter name is treated as a placeholder if has a name but no
type specified: neither in the signature, nor in any following \f(CW\*(C`INPUT\*(C'\fR
section. For example:
.PP
.Vb 4
\&    void
\&    foo(int a, b, char *c)
\&      CODE:
\&        ...
.Ve
.PP
is roughly equivalent to the Perl:
.PP
.Vb 5
\&    sub foo {
\&        my $a = int($_[0]);
\&        my $c = "$_[2]";
\&        ...
\&    }
.Ve
.PP
A parameter containing just the specific type \f(CW\*(C`SV*\*(C'\fR and no name is
treated specially. A bug in the XS parser meant that it used to skip any
parameter declaration which wasn\*(Aqt parsable. This inadvertently made many
things de facto placeholder declarations. A common usage was \f(CW\*(C`SV*\*(C'\fR, which
is now officially treated as a placeholder for backwards compatibility.
Any other bare types without a parameter name are errors since \fIxsubpp\fR
3.57. Note that the \f(CW\*(C`SV*\*(C'\fR text will appear in any \f(CWusage()\fR error
message. For example,
.PP
.Vb 2
\&    void
\&    foo(int a, SV*, char *c)
.Ve
.PP
may croak with:
.PP
.Vb 1
\&    Usage: Foo::Bar::foo(a, SV*, c) at ...
.Ve
.PP
Placeholders can\*(Aqt be used with autocall unless you use C_ARGS to override the missing argument. For example:
.PP
.Vb 3
\&    void
\&    foo(int a, b, char *c)
\&        C_ARGS: a, c
.Ve
.PP
\fIUpdating and returning parameter values: the IN_OUT etc keywords\fR
.IX Subsection "Updating and returning parameter values: the IN_OUT etc keywords"
.PP
.Vb 6
\&    IN         int i
\&               int i
\&    IN_OUT     int i
\&    IN_OUTLIST int i
\&    OUT        int i
\&    OUTLIST    int i
.Ve
.PP
Normally a parameter declaration causes a C auto variable of the same name
to be declared and initialised to the value of the corresponding passed
argument. These modifiers can make parameters also update or return
values, and can also cause the initialisation to be skipped. They come at
the start of a parameter declaration.
.PP
These modifiers address the issue that, because a simple C function takes
a fixed number of \fIread\-only\fR parameters and returns a \fIsingle\fR value,
the basic XSUB syntax has been designed to reflect that pattern.
.PP
The usual way to make a more complex C function API is to pass pointers to
variables, which the C function will use to set or update the variables.
For example, a couple of hypothetical C functions might be called as:
.PP
.Vb 4
\&    int time = ....;      // an integer in the range 0..86399
\&    int hour, min, sec;
\&    parse_time(time, &hour, &min, &sec); // set    hour, min, sec
\&    increment_time(&hour, &min, &sec);   // update hour, min, sec
.Ve
.PP
The XS \f(CW\*(C`IN_OUT\*(C'\fR etc modifiers allow you to write XSUBs which can wrap
such functions with autocall, and in general update passed arguments or
return multiple values.
.PP
The rules of these parameter modifiers are:
.IP \(bu 4
All such parameters, regardless of the modifier, cause a C auto variable
of the same name to be declared.
.IP \(bu 4
In the absence of a modifier, it defaults to \f(CW\*(C`IN\*(C'\fR.
.IP \(bu 4
The text of the modifier has one or two parts, separated by an underscore.
The input part comes first and, if present, must have the value \f(CW\*(C`IN\*(C'\fR;
while the output part, if present, can be one of \f(CW\*(C`OUT\*(C'\fR or \f(CW\*(C`OUTLIST\*(C'\fR.
.IP \(bu 4
An input part of \f(CW\*(C`IN\*(C'\fR (the default) causes that variable to be
initialised to the value of the corresponding passed argument. Otherwise
the initialisation is skipped: in particular, this means that an autocall
function will be passed a pointer to an uninitialised value: the
assumption being that the library function will set, but not use, that
value.
.IP \(bu 4
An absent output part (the default) means nothing is done to return the
value of the auto variable.
.IP \(bu 4
An output part of \f(CW\*(C`OUT\*(C'\fR or \f(CW\*(C`OUTLIST\*(C'\fR causes the value to be returned in
some fashion, and in addition, any autocall code will prefix such
variables with \f(CW\*(C`&\*(C'\fR when calling the wrapped C library function.
.IP \(bu 4
An output part of \f(CW\*(C`OUT\*(C'\fR causes the corresponding passed argument to be
\&\fIupdated\fR with the value of the variable.
.IP \(bu 4
An output part of \f(CW\*(C`OUTLIST\*(C'\fR causes the value of the variable to be
returned as an extra SV after the \f(CW\*(C`RETVAL\*(C'\fR value, if any. They are
returned in the order they appear in the XSUB\*(Aqs parameter list.
.IP \(bu 4
For the specific case of the modifier being \f(CW\*(C`OUTLIST\*(C'\fR, it is a
pseudo\-parameter, and \fIno argument is consumed\fR. It doesn\*(Aqt form part of
the signature of the XSUB, although it \fIis\fR used for any autocall. So for
example:
.Sp
.Vb 2
\&    int
\&    foo(int a, OUTLIST int b, int c)
.Ve
.Sp
gets converted to roughly this C code:
.Sp
.Vb 10
\&    if (items != 2)
\&       croak_xs_usage(cv,  "a, c");
\&    {
\&        int RETVAL;
\&        int a = (int)SvIV(ST(0));
\&        int b;
\&        int c = (int)SvIV(ST(1));
\&        RETVAL = foo(a, &b, c);
\&    }
\&    ... push the values of RETVAL and b onto the stack and return ...
.Ve
.PP
The approximate perl equivalents for these modifiers are given in the
examples below, where the perl code \f(CWreal_foo(\e$i)\fR stands in for the C
autocall \f(CWfoo(&i)\fR.
.PP
.Vb 4
\&    IN int i             sub foo {
\&       int i                  my $i = $_[N];
\&                              real_foo($i);
\&                         }
\&
\&    IN_OUT int i         sub foo {
\&                              my $i = $_[N];
\&                              real_foo(\e$i);
\&                              $_[N] = $i;
\&                         }
\&
\&    IN_OUTLIST int i     sub foo {
\&                              my $i = $_[N];
\&                              real_foo(\e$i);
\&                              return ..., $i, ...;
\&                         }
\&
\&    OUT int i            sub foo {
\&                              my $i;
\&                              real_foo(\e$i);
\&                              $_[N] = $i;
\&                         }
\&
\&    OUTLIST int i        sub foo {
\&                              my $i; # NB $_[N] is not consumed
\&                              real_foo(\e$i);
\&                              return ..., $i, ...;
\&                         }
.Ve
.PP
Together, they allow you to wrap C functions which use pointers to return
extra values; either preserving the C\-ish API in perl (\f(CW\*(C`OUT\*(C'\fR), or
providing a more Perl\-like API (\f(CW\*(C`OUTLIST\*(C'\fR). For example, wrapping the
\&\f(CWparse_time()\fR function from the example above could be done using
\&\f(CW\*(C`OUT\*(C'\fR:
.PP
.Vb 3
\&    void
\&    parse_time(int time, \e
\&               OUT int hour, OUT int min, OUT int sec)
.Ve
.PP
which could be called from perl as:
.PP
.Vb 3
\&    my ($hour, $min, $sec);
\&    # set ($hour, $min, $sec) to (23,59,59):
\&    parse_time(86399, $hour, $min, $sec);
.Ve
.PP
Or by using \f(CW\*(C`OUTLIST\*(C'\fR:
.PP
.Vb 3
\&    void
\&    parse_time(int time, \e
\&               OUTLIST int hour, OUTLIST int min, OUTLIST int sec)
.Ve
.PP
which could be called from perl as:
.PP
.Vb 2
\&    # set ($hour, $min, $sec) to (23,59,59):
\&    my ($hour, $min, $sec) = parse_time(86399);
.Ve
.PP
\fIDefault Parameter Values\fR
.IX Subsection "Default Parameter Values"
.PP
.Vb 2
\&    int
\&    foo(int i, char *s = "abc")
\&
\&    int
\&    bar(int i, int j = i + \*(Aq)\*(Aq, char *s = "abc,)")
\&
\&    int
\&    baz(int i, char *s = NO_INIT)
.Ve
.PP
Optional parameters can be indicated by appending \f(CW\*(C`= C_expression\*(C'\fR to the
parameter declaration. The C expression will be evaluated if not enough
arguments are supplied. Parameters with default values should come after
any mandatory parameters (although this is currently not enforced by the
XS compiler). The value can be any valid compile\-time or run\-time C
expression (but see below), including the values of any parameters
declared to its left. The special value \f(CW\*(C`NO_INIT\*(C'\fR indicates that the
parameter is kept uninitialised if there isn\*(Aqt a corresponding argument.
.PP
The XS parser\*(Aqs handling of default expressions is rather simplistic. It
just wants to extract parameter declarations (including any optional
trailing default value) from a comma\-separated list, but it doesn\*(Aqt
understand C syntax. It can handle commas and closing parentheses within a
quoted string, but currently not an escaped quote such as \f(CW\*(Aq\e\*(Aq\*(Aq\fR or
\&\f(CW"\e""\fR. Neither can it handle balanced parentheses such as \f(CW\*(C`int j =
(i+1)\*(C'\fR.
.PP
Due to an implementation flaw, default value expressions are currently
evalled in double\-quoted context during parsing, in a similar fashion to
typemap templates. So for example \f(CW\*(C`char *s = "$arg"\*(C'\fR is expanded to
\&\f(CW\*(C`char *s = "ST(0)"\*(C'\fR or similar. This behaviour may be fixed at some
point; in the meantime, it is best to avoid the \f(CW\*(C`$\*(C'\fR and \f(CW\*(C`@\*(C'\fR characters
within default value expressions.
.PP
\fIThe \fR\f(CIlength(param_name)\fR\fI pseudo\-parameter\fR
.IX Subsection "The length(param_name) pseudo-parameter"
.PP
.Vb 2
\&    int
\&    foo(char *s, int length(s))
.Ve
.PP
It is common for a C function to take a string pointer and length as two
arguments, while in Perl, string\-valued SVs combine both the string and
length in a single value. To simplify generating the autocall code in such
situations, the \f(CWlength(foo)\fR pseudo\-parameter acts as the length of the
parameter \f(CW\*(C`foo\*(C'\fR. It doesn\*(Aqt consume an argument or appear in the XSUB\*(Aqs
usage message, but it \fIis\fR passed to the autocalled C function. For
example, this XS:
.PP
.Vb 2
\&    void
\&    foo(char *s, short length(s), int t)
.Ve
.PP
translates to something similar to this C code:
.PP
.Vb 2
\&    if (items != 2)
\&       croak_xs_usage(cv, "s, t");
\&
\&    {
\&        STRLEN STRLEN_length_of_s;
\&        short  XSauto_length_of_s;
\&        char * s = (char *)SvPV(ST(0), STRLEN_length_of_s);
\&        int    t = (int)SvIV(ST(1));
\&
\&        XSauto_length_of_s = STRLEN_length_of_s;
\&        foo(s, XSauto_length_of_s, t);
\&    }
.Ve
.PP
and might be called from Perl as:
.PP
.Vb 1
\&    foo("abcd", 9999);
.Ve
.PP
The exact C code generated will vary over releases, but the important
things to note are:
.IP \(bu 4
The auto variable \f(CW\*(C`XSauto_length_of_foo\*(C'\fR will be declared with the
specified type and will be passed to any autocall function, but it won\*(Aqt
appear in the usage message. This variable is available for use in \f(CW\*(C`CODE\*(C'\fR
blocks and similar.
.IP \(bu 4
The auto variable \f(CW\*(C`STRLEN_length_of_s\*(C'\fR is used in addition to allow
conversion between the type expected by \f(CWSvPV()\fR and the type declared
for the length pseudo\-parameter.
.IP \(bu 4
A length parameter can appear anywhere in the signature, even before the
string parameter of the same name; but its position in any autocall
matches its position in the signature.
.IP \(bu 4
Each length parameter must match another parameter of the same name. That
parameter must be a string type (something which maps to the \f(CW\*(C`T_PV\*(C'\fR
typemap type).
.PP
\fIEllipsis: variable\-length parameter lists\fR
.IX Subsection "Ellipsis: variable-length parameter lists"
.PP
.Vb 2
\&    int
\&    foo(char *s, ...)
.Ve
.PP
An XSUB can have a variable\-length parameter list by specifying an
ellipsis as the last parameter, similar to C function declarations. Its
main effect is to disable the error check for too many parameters. Any
declared parameters will still be processed as normal, but the programmer
will have to access any extra arguments manually, making use of the
\&\f(CWST(n)\fR macro to access the nth item on the stack, and the \f(CW\*(C`items\*(C'\fR
variable, which indicates the total number of passed arguments, including
any fixed arguments. Note that \f(CWST(0)\fR is the first passed argument,
while the first ellipsis argument is \f(CWST(i)\fR where \f(CW\*(C`i\*(C'\fR is the number of
fixed arguments preceding the ellipsis.
.PP
Note that currently XS doesn\*(Aqt provide any mechanism to autocall
variable\-length C functions, so the ellipsis should only be used on XSUBs
which have a body.
.PP
For example, consider this Perl subroutine which returns the sum of all
of its arguments which are within a specified range:
.PP
.Vb 7
\&    sub minmax_sum {
\&        my $min = shift;
\&        my $max = shift;
\&        my $RETVAL = 0;
\&        $RETVAL += $_ for grep { $min <= $_ && $_ <= $max } @_;
\&        return $RETVAL;
\&    }
.Ve
.PP
This XSUB provides equivalent functionality:
.PP
.Vb 6
\&    int
\&    minmax_sum(int min, int max, ...)
\&      CODE:
\&        {
\&            int i = 2; /* skip the two fixed arguments */
\&            RETVAL = 0;
\&
\&            for (; i < items; i++) {
\&                int val  = (int)SvIV(ST(i));
\&                if (min <= val && val <= max)
\&                    RETVAL += val;
\&            }
\&        }
\&      OUTPUT:
\&        RETVAL
.Ve
.PP
It is possible to write an XSUB which both accepts and returns a list. For
example, this XSUB does the equivalent of the Perl \f(CW\*(C`map { $_*3 } ...\*(C'\fR
.PP
.Vb 11
\&    void
\&    triple(...)
\&      PPCODE:
\&        SP += items;
\&        {
\&            int i;
\&            for (i = 0; i < items; i++) {
\&                int val  = (int)SvIV(ST(i));
\&                ST(i) = sv_2mortal(newSViv(val*3));
\&            }
\&        }
.Ve
.PP
Note that the PPCODE keyword, in comparison to
\&\f(CW\*(C`CODE\*(C'\fR, resets the local copy of the argument stack pointer, and relies
on the coder to place any return values on the stack. The example above
reclaims the passed arguments by setting \f(CW\*(C`SP\*(C'\fR back to the top of the
stack, then replaces the items on the stack one by one.
.SS "The XSUB Input Part"
.IX Subsection "The XSUB Input Part"
Following an XSUB\*(Aqs declaration part, the body of the XSUB follows. The
first part of the body is the \fIinput\fR part, and is mainly concerned with
declaring auto variables and assigning to them values extracted from the
passed parameters. The two main keywords associated with this activity are
PREINIT and INPUT. The
first allows you to inject extra variable declaration lines, while the
latter used to be needed to specify the type of each parameter, but is now
mainly of historical interest. This is also the place for the rarely\-used
SCOPE keyword.
.PP
Note that the keywords described in "XSUB Generic Keywords" and "Sharing
XSUB bodies" may also appear in this part, plus the C_ARGS and INTERFACE_MACRO keywords.
.PP
\fIThe PREINIT: Keyword\fR
.IX Subsection "The PREINIT: Keyword"
.PP
.Vb 3
\&    PREINIT:
\&        int i;
\&        char *prog_name = get_prog_name();
.Ve
.PP
This keyword allows extra variables to be declared and possibly
initialised immediately before the declarations of auto variables
generated from any parameter declarations or \f(CW\*(C`INPUT\*(C'\fR lines. Any lines
following \f(CW\*(C`PREINIT\*(C'\fR until the next keyword (except POD and XS comments)
are copied out as\-is to the C code file. Multiple \f(CW\*(C`PREINIT\*(C'\fR keywords are
allowed.
.PP
It is sometimes needed because in traditional C, all variable
declarations must come before any statements. While this is no longer a
restriction in the perl interpreter source since Perl 5.36.0, the C
compiler flags used when compiling XS code may be different and so,
depending on the compiler, it may still be necessary to preserve the
correct ordering.
.PP
Any variable declarations generated by \f(CW\*(C`INPUT\*(C'\fR and lines from \f(CW\*(C`PREINIT\*(C'\fR
are output in the same order they appear in the XS source, followed by any
variable declarations generated from the XSUB\*(Aqs parameter declarations.
These may be followed by statements to initialise those variables.
Thus, any variable declarations in a later \f(CW\*(C`INIT\*(C'\fR or \f(CW\*(C`CODE\*(C'\fR block may be
flagged as a declaration\-after\-statement.
.PP
\&\f(CW\*(C`PREINIT\*(C'\fR code shouldn\*(Aqt assume that any variables declared earlier have
already been initialised; initialisation is deferred if the initialisation
code (typically obtained from a typemap) isn\*(Aqt of the simple \f(CW\*(C`type var =
init;\*(C'\fR form, or has a default value.
.PP
For example:
.PP
.Vb 6
\&    void
\&    foo(int i = 0)
\&        PREINIT:
\&            int j = 1;
\&        CODE:
\&            bar(i, j);
.Ve
.PP
might be translated into C code similar to:
.PP
.Vb 3
\&    {
\&        int j = 1;
\&        int i;
\&
\&        if (items < 1)
\&            i = 0;
\&        else {
\&            i = (int)SvIV(ST(0));
\&        }
\&        bar(i, j);
\&    }
.Ve
.PP
Usually you could dispense with \f(CW\*(C`PREINIT\*(C'\fR by just wrapping the code in
\&\f(CW\*(C`CODE\*(C'\fR blocks in braces, but it may be necessary if the ordering of the
variable initialisations is sensitive, e.g. if it is affected by some
changing global state.
.PP
\fIThe INPUT: Keyword\fR
.IX Subsection "The INPUT: Keyword"
.PP
.Vb 11
\&    void
\&    foo(a, b, c, d, e, int f)
\&      # implicit INPUT section
\&        int   a
\&      # explicit INPUT section
\&      INPUT:
\&        long  &b
\&        int    c = ($type)MySvIV($arg)
\&        int    d = NO_INIT
\&        int    e + if (some_condition) { $var += 1 }
\&      ...
.Ve
.PP
Immediately following an XSUB\*(Aqs declaration, there is an implicit \f(CW\*(C`INPUT\*(C'\fR
section, i.e. the parser behaves as if there was a literal "\f(CW\*(C`INPUT:\en"\*(C'\fR
line injected before the first line of the body. This can be followed by
zero or more explicit \f(CW\*(C`INPUT\*(C'\fR sections, possibly interleaved with other
keywords and sections such as \f(CW\*(C`PREINIT\*(C'\fR.
.PP
When XS was first created, it was modelled on the syntax of pre\-ANSI C,
which required the types of parameters to be separately specified. It was
later updated to allow parameter types to be specified in the parameter
list, like ANSI C. Thus there is rarely any good reason to use \f(CW\*(C`INPUT\*(C'\fR
sections now; but you will often encounter them in older code.
.PP
Each \f(CW\*(C`INPUT\*(C'\fR line, at a minimum, specifies the type of a parameter listed
in the XSUB\*(Aqs signature, e.g.
.PP
.Vb 1
\&    char *s
.Ve
.PP
In addition, the variable name may be prefixed with \f(CW\*(C`&\*(C'\fR to indicate that
a pointer to the variable should be passed to any autocall function; and
may have a postfix initialisation modifier starting with one of the three
characters \f(CW\*(C`= + ;\*(C'\fR.
.PP
Note that if a variable name doesn\*(Aqt match any of the declared parameters,
then it \fImight\fR be treated as an auto variable declaration (depending on
the perl version and on whether it has an initialisation override). This
misfeature may be deprecated at some point in the future, so don\*(Aqt rely on
it: use a \f(CW\*(C`PREINIT\*(C'\fR section if necessary. These two examples are mostly
equivalent, with the first form being preferred:
.PP
.Vb 4
\&    void
\&    foo(int a)
\&      PREINIT:
\&         short b = 1;
\&
\&    void
\&    foo(a)
\&         int a
\&         short b = 1;
.Ve
.PP
The & variable modifier in INPUT
.IX Subsection "The & variable modifier in INPUT"
.PP
The \f(CW\*(C`&\*(C'\fR variable modifier has the single effect that the corresponding
argument passed to an autocall function will have the variable name
prefixed with \f(CW\*(C`&\*(C'\fR. Combined with \f(CW\*(C`OUTPUT: foo\*(C'\fR, this allows the
\&\fIaddress\fR of a variable to be passed to a wrapped function, which updates
that variable\*(Aqs value; on return, the XSUB updates the caller\*(Aqs arg with
that value. The modern equivalent of this is to declare the parameter as
\&\f(CW\*(C`IN_OUT\*(C'\fR. These two XSUBs are equivalent:
.PP
.Vb 2
\&    void
\&    foo(IN_OUT int i)
\&
\&    void
\&    foo(i)
\&        int &i
\&      OUTPUT:
\&        i
.Ve
.PP
and they both wrap a C function called \fBfoo()\fR that takes a single \f(CW\*(C`int *\*(C'\fR
argument which (presumably) updates the integer pointed to. They both
generate C code similar to this:
.PP
.Vb 3
\&    int i = (int)SvIV(ST(0));
\&    foo(&i);
\&    sv_setiv(ST(0), (IV)i);
.Ve
.PP
Altering variable initialisation in INPUT
.IX Subsection "Altering variable initialisation in INPUT"
.PP
Normally each declared parameter causes a C auto variable of the same name
to be declared, and for code to be planted which initialises that variable
to the value of the corresponding passed argument. The initialisation code
is usually obtained by expanding the typemap template corresponding to
the parameter\*(Aqs type. It is possible to override, augment, or skip that
initialisation code, by appending one of the three characters \f(CW\*(C`= + ;\*(C'\fR and
an initialiser expression, to the \f(CW\*(C`INPUT\*(C'\fR line.
.PP
.Vb 2
\&    void
\&    foo(a,b,c,d,e,f,g)
\&
\&        # Use the standard typemap entry:
\&        int a
\&        # and with optional trailing colon
\&        int b;
\&
\&        # Override the typemap entry:
\&        int c = ($type)MySvIV($arg)
\&
\&        # Skip the initialisation entirely:
\&        int d = NO_INIT
\&        int e ; NO_INIT
\&
\&        # Add deferred initialisation code
\&        # *in addition* to the standard init:
\&        int f + if (some_condition) { $var += 1 }
\&
\&        # Add deferred initialisation code
\&        # *instead of* the standard init:
\&        int g ; if (some_condition) { $var += 1 }
.Ve
.PP
Any override code is passed through template expansion in the same way
that typemap templates are, with \f(CW$var\fR, \f(CW$arg\fR, \f(CW$type\fR etc being
expanded. Deferred initialisation code is placed after all variable
declarations.
.PP
In modern XS where \f(CW\*(C`INPUT\*(C'\fR is not often used, some of these initialiser
effects can be achieved in other ways:
.IP \(bu 4
an overridden typemap entry could be specified by using \f(CW\*(C`TYPEMAP\*(C'\fR
to add a template for the type of this variable;
.IP \(bu 4
skipping initialisation can be achieved using the \f(CW\*(C`OUT\*(C'\fR and \f(CW\*(C`OUTLIST\*(C'\fR
parameter declaration modifiers;
.IP \(bu 4
adding deferred initialisation code may be achievable via \f(CW\*(C`PREINIT\*(C'\fR or
\&\f(CW\*(C`INIT\*(C'\fR blocks.
.PP
\fIThe SCOPE: Keyword and typemap entry\fR
.IX Subsection "The SCOPE: Keyword and typemap entry"
.PP
.Vb 6
\&    # XSUB\-scoped
\&    void
\&    foo(int i)
\&      SCOPE: ENABLE
\&      CODE:
\&        ...
\&
\&    # file\-scoped
\&    SCOPE: ENABLE
\&    void
\&    bar(int i)
\&      CODE:
\&        ...
\&
\&    # typemap entry
\&    TYPEMAP: <<EOF
\&    INPUT
\&    T_MYINT
\&       $var = my_int($arg); /* SCOPE */
\&    EOF
.Ve
.PP
The \f(CW\*(C`SCOPE\*(C'\fR keyword can be used to enable scoping for a particular XSUB
(disabled by default). Its effect is to wrap the main body of the XSUB
(including most parameter and return value processing) within an \f(CW\*(C`{
ENTER;\*(C'\fR and \f(CW\*(C`LEAVE; }\*(C'\fR pair. This has the effect of clearing any
accumulated savestack entries at the end of the code body. If disabled,
then the savestack will usually be cleared by the caller anyway, so this
is a rarely\-used keyword.
.PP
The SCOPE keyword may be either XSUB\-scoped or file\-scoped (this refers to
the scope of the keyword within the XS file, not to the scope generated by
the keyword). For the first, it may appear anywhere in the input part or
the XSUB. For the latter, it may appear anywhere in file scope, but due to
a long\-standing parser bug, the keyword\*(Aqs state is reset at the start of
each XSUB, so it will only have any effect if it appears just before a
XSUB declaration and as part of the same paragraph (i.e. with no
intervening blank lines), such as in the example above. It will only
affect the single following XSUB.
.PP
The XSUB\-scoped form has been available since \fIxsubpp\fR 1.9506, but was
broken in release 2.21 and fixed in 3.58. The file\-scoped form has been
available since 2.21.
.PP
To support potentially complex type mappings, if an \f(CW\*(C`INPUT\*(C'\fR typemap entry
contains a code comment like \f(CW\*(C`/* SCOPE */\*(C'\fR, then scoping will be
automatically enabled for any XSUB which uses that typemap entry. This
currently only works for parameters whose type is specified using
old\-style \f(CW\*(C`INPUT\*(C'\fR lines rather than an ANSI\-style declaration, i.e. not
for \f(CW\*(C`foo(int i)\*(C'\fR. In fact, the XS parser, when looking for a SCOPE
comment in a typemap, is currently very lax: it\*(Aqs actually a
case\-insensitive match of any code comment which contains the text "scope"
plus anything else. But you shouldn\*(Aqt rely on this; always use the form
shown here. Even better, just don\*(Aqt use it at all.
.SS "The XSUB Init Part"
.IX Subsection "The XSUB Init Part"
Following an XSUB\*(Aqs input part, an optional init part follows. This
consists solely of the \f(CW\*(C`INIT\*(C'\fR keyword described below, plus the keywords
described in "XSUB Generic Keywords" and "Sharing XSUB bodies", plus the
C_ARGS.
.PP
\fIThe INIT: Keyword\fR
.IX Subsection "The INIT: Keyword"
.PP
The \f(CW\*(C`INIT\*(C'\fR keyword allows arbitrary initialisation code to be inserted
after any variable declarations (and their initialisations), but before
the main body of code. It is primarily intended for use when the main body
is an autocall to a C function. For example these two XSUBs are
equivalent:
.PP
.Vb 5
\&    int
\&    foo(int i)
\&      INIT:
\&        if (i < 0)
\&            XSRETURN_UNDEF;
\&
\&    int
\&    foo(int i)
\&      CODE:
\&        if (i < 0)
\&            XSRETURN_UNDEF;
\&        RETVAL = foo(i);
\&      OUTPUT:
\&        RETVAL
.Ve
.PP
Any lines following \f(CW\*(C`INIT\*(C'\fR until the next keyword (except POD and XS
comments) are copied out as\-is to the C code file. Multiple \f(CW\*(C`INIT\*(C'\fR
keywords are allowed.
.SS "The XSUB Code Part"
.IX Subsection "The XSUB Code Part"
Following an XSUB\*(Aqs optional init part, an optional code part follows. This
consists mainly of the \f(CW\*(C`CODE\*(C'\fR or \f(CW\*(C`PPCODE\*(C'\fR keywords, which provide the
code block for the main body of the XSUB. These two keywords are similar,
except that \f(CW\*(C`PPCODE\*(C'\fR can be thought of as acting at a lower level; it
resets the stack pointer to the base of the stack frame and then relies on
the programmer to push any return values; whereas \f(CW\*(C`CODE\*(C'\fR will (with
prompting) automatically generate code to return the value of \f(CW\*(C`RETVAL\*(C'\fR.
.PP
There is also a rarely\-used \f(CW\*(C`NOT_IMPLEMENTED_YET\*(C'\fR keyword which generates
a body which croaks.
.PP
Only one of these keywords may appear in this part, and at most once; and
no other keywords are recognised in this part (although such keywords
could instead be processed in the tail or head of the preceding and
following init and output parts).
.PP
In the absence of any of those three keywords, the XS compiler will
generate an autocall: a call to the C function of the same name as the
XSUB.
.PP
\fIAuto\-calling a C function\fR
.IX Subsection "Auto-calling a C function"
.PP
In the absence of any explicit main body code via \f(CW\*(C`CODE\*(C'\fR, \f(CW\*(C`PPCODE\*(C'\fR or
\&\f(CW\*(C`NOT_IMPLEMENTED_YET\*(C'\fR, the XS parser will generate a body for you
automatically (this is referred to as \f(CW\*(C`autocall\*(C'\fR in this document). In
its most basic form, the parser assumes that the XSUB will be a simple
wrapper for a C function of the same name, with the same parameters and
return type as the XSUB. So for example, these two XSUB definitions are
equivalent, but the first is an autocall with less boilerplate needed:
.PP
.Vb 2
\&    int
\&    foo(char *s, short flags)
\&
\&    int
\&    foo(char *s, short flags)
\&      CODE:
\&        RETVAL = foo(s, flags);
\&      OUTPUT:
\&        RETVAL
.Ve
.PP
Note that the XSUB C function and the wrapped C function are two
different entities; the first will have a name like \f(CW\*(C`XS_Foo_\|_Bar_foo\*(C'\fR;
when Perl code calls the \*(AqPerl\*(Aq function \f(CWFoo::Bar::foo()\fR, behind the
scenes the Perl interpreter calls \f(CW\*(C`XS_Foo_\|_Bar_foo()\*(C'\fR, which extracts the
string and short int values from the two passed argument SVs, calls
\&\f(CWfoo()\fR, then stuffs its return value into an SV and returns that to the
Perl caller.
.PP
The two basic types of generated autocall code are:
.PP
.Vb 1
\&    foo(a, b, c);
\&
\&    RETVAL = foo(a, b, c);
.Ve
.PP
depending on whether the XSUB is declared \f(CW\*(C`void\*(C'\fR or not. The variables
passed to the function are usually just the names of the XSUB\*(Aqs
parameters, in the same order. Parameters with default values are
included, while ellipses are ignored. So for example
.PP
.Vb 2
\&    int
\&    foo(int a, int b = 0, ...)
.Ve
.PP
generates this autocall code:
.PP
.Vb 1
\&    RETVAL = foo(a, b);
.Ve
.PP
There are various keywords which can be used to modify the basic behaviour
of an autocall.
.IP \(bu 4
The PREFIX keyword, which allows wrapped C functions
which share a common prefix in their names to be mapped to perl functions
whose names don\*(Aqt have that prefix.
.IP \(bu 4
The
OUT
etc parameter modifiers, which cause that parameter to be passed to the
autocalled function with a \f(CW\*(C`&\*(C'\fR prefix, on the assumption that the
wrapped function expects a pointer and will update the location pointed
to.
.IP \(bu 4
The length(param_name)
pseudo\-parameter, which allows the length of another parameter to be
passed as a separate argument to the wrapped function, even though it
isn\*(Aqt a parameter of the Perl function.
.IP \(bu 4
The C_ARGS keyword, which allows the arguments
passed to the  wrapped function to be completely overridden: handy when
arguments need to be skipped or reordered compared with the perl
function.
.IP \(bu 4
The INIT keyword, which allows code to be added
directly before the autocall.
.IP \(bu 4
The POSTCALL keyword, which allows code to be
added directly after the autocall.
.IP \(bu 4
Support for C++ XSUBs, which can (among other
things) modify the autocall into a C++ method call, e.g.
\&\f(CW\*(C`THIS\->foo(s,flags)\*(C'\fR.
.PP
The C_ARGS: Keyword
.IX Subsection "The C_ARGS: Keyword"
.PP
.Vb 2
\&    void foo1(int a, int b, int c)
\&      C_ARGS: b, a
\&
\&    void foo2(int a, int b)
\&      C_ARGS: a < 0 ? 0 : a,
\&              b,
\&              0
.Ve
.PP
Normally the arguments for an autocall are generated automatically, based
on the XSUB\*(Aqs parameter declarations. The \f(CW\*(C`C_ARGS\*(C'\fR keyword allows you to
override this and manually specify the text that will be placed between
the parentheses in the autocall. This is useful when the ordering and
nature of parameters varies between Perl and C, without a need to write a
\&\f(CW\*(C`CODE\*(C'\fR or \f(CW\*(C`PPCODE\*(C'\fR section.
.PP
The \f(CW\*(C`C_ARGS\*(C'\fR section consists of all lines of text until the next keyword
or to the end of the XSUB, and is used without modification (except that
any POD or XS comments will be stripped).
.PP
\fIThe CODE: Keyword\fR
.IX Subsection "The CODE: Keyword"
.PP
.Vb 8
\&    int
\&    abs_double(int i)
\&      CODE:
\&        if (i < 0)
\&            i = \-i;
\&        RETVAL = i * 2;
\&      OUTPUT:
\&        RETVAL
.Ve
.PP
The \f(CW\*(C`CODE\*(C'\fR keyword is the usual mechanism for providing your own code as
the main body of the XSUB. It is typically used when the XSUB, rather than
wrapping a library function, is providing general functionality which can
be more easily or efficiently implemented in C than in Perl.
Alternatively, it can still be used to wrap a library function for cases
which are too complex for autocall to handle.
.PP
Note that on entry to the \f(CW\*(C`CODE\*(C'\fR block of code, the values of any passed
arguments will have been assigned to auto variables, but the original SVs
will still be on the stack and accessible via \f(CWST(i)\fR if necessary.
.PP
Similarly to autocall XSUBs, a \f(CW\*(C`RETVAL\*(C'\fR variable is declared if the
return value of the XSUB is not \f(CW\*(C`void\*(C'\fR. Unlike autocall, you have to
explicitly tell the XS compiler to generate code to return the value of
\&\f(CW\*(C`RETVAL\*(C'\fR, by using the The OUTPUT keyword.
(Requiring this was probably a bad design decision, but we\*(Aqre stuck with
it now.) Newer XS parsers will warn if \f(CW\*(C`RETVAL\*(C'\fR is seen in the \f(CW\*(C`CODE\*(C'\fR
section without a corresponding \f(CW\*(C`OUTPUT\*(C'\fR section.
.PP
A \f(CW\*(C`CODE\*(C'\fR XSUB will typically return just the \f(CW\*(C`RETVAL\*(C'\fR value (or possibly
more items with the \f(CW\*(C`OUTLIST\*(C'\fR parameter modifiers). To take complete
control over returning values, you can use the \f(CW\*(C`PPCODE\*(C'\fR keyword instead.
Note that it is possible for a \f(CW\*(C`CODE\*(C'\fR section to do this too, by doing its
own stack manipulation and then doing an \f(CWXSRETURN(n)\fR to return directly
while indicating that there are \f(CW\*(C`n\*(C'\fR items on the stack. This bypasses the
normal \f(CWXSRETURN(1)\fR etc that the XS parser will have planted after the
\&\f(CW\*(C`CODE\*(C'\fR lines. But it is usually cleaner to use \f(CW\*(C`PPCODE\*(C'\fR instead.
.PP
Any lines following \f(CW\*(C`CODE\*(C'\fR until the next keyword (except POD and XS
comments) are copied out as\-is to the C code file. Multiple \f(CW\*(C`CODE\*(C'\fR
keywords are not allowed.
.PP
\fIThe PPCODE: Keyword\fR
.IX Subsection "The PPCODE: Keyword"
.PP
.Vb 1
\&    # XS equivalent of: sub one_to_n { my $n = $_[0]; 1..$n }
\&
\&    void
\&    one_to_n(int n)
\&      PPCODE:
\&        {
\&            int i;
\&            if (n < 1)
\&                Perl_croak_nocontext(
\&                    "one_to_n(): argument %d must be >= 1", n);
\&            EXTEND(SP, n);
\&            for (i = 1; i <= n; i++)
\&                mPUSHi(i);
\&        }
.Ve
.PP
The \f(CW\*(C`PPCODE\*(C'\fR keyword is similar to the \f(CW\*(C`CODE\*(C'\fR keyword, except that on
entry it resets the stack pointer to the base of the current stack frame,
and it doesn\*(Aqt generate any code to return \f(CW\*(C`RETVAL\*(C'\fR or similar: pushing
return values onto the stack is left to the programmer. In this way it can
be viewed as a lower\-level alternative to \f(CW\*(C`CODE\*(C'\fR, when you want to take
full control of manipulating the argument stack. The "PP" in its name
stands for "PUSH/PULL", reflecting the low\-level stack manipulation.
\&\f(CW\*(C`PPCODE\*(C'\fR is typically used when you want to return several values or even
an arbitrary list, compared with \f(CW\*(C`CODE\*(C'\fR, which normally returns just the
value of \f(CW\*(C`RETVAL\*(C'\fR.
.PP
The \f(CW\*(C`PPCODE\*(C'\fR keyword must be the last keyword in the XSUB. Any lines
following \f(CW\*(C`PPCODE\*(C'\fR until the end of the XSUB (except POD and XS comments)
are copied out as\-is to the C code file. Multiple \f(CW\*(C`PPCODE\*(C'\fR keywords are
not allowed.
.PP
Typically you declare a \f(CW\*(C`PPCODE\*(C'\fR XSUB with a return type of \f(CW\*(C`void\*(C'\fR; any
other return type will cause a \f(CW\*(C`RETVAL\*(C'\fR auto variable of that type to be
declared, which will be otherwise unused.
.PP
On entry to the \f(CW\*(C`PPCODE\*(C'\fR block of code, the values of any declared
parameters arguments will have already been assigned to auto variables,
but the original SVs will still be on the stack and initially accessible
via \f(CWST(i)\fR if necessary. But the default assumption for a \f(CW\*(C`PPCODE\*(C'\fR
block is that you have already finished processing any supplied arguments,
and that you want to push a number of return values onto the stack. The
simple \f(CWone_to_n()\fR example shown above is based on that assumption. But
more complex strategies are possible.
.PP
There are basically two ways to access and manipulate the stack in a
\&\f(CW\*(C`PPCODE\*(C'\fR block. First, by using the \f(CWST(i)\fR macro, to get, modify, or
replace the \fIi\fRth item in the current stack frame, and secondly to push
(usually temporary) return values onto the stack. The first uses the
hidden \f(CW\*(C`ax\*(C'\fR variable, which is set on entry to the XSUB, and is the index
of the base of the current stack frame. This remains unchanged throughout
execution of the XSUB. The second approach uses the local stack pointer,
\&\f(CW\*(C`SP\*(C'\fR (more on that below), which on entry to the \f(CW\*(C`PPCODE\*(C'\fR block points
to the base of the stack frame. Macros like \f(CWmPUSHi()\fR store a temporary
SV at that location, then increment \f(CW\*(C`SP\*(C'\fR. On return from a \f(CW\*(C`PPCODE\*(C'\fR
XSUB, the current value of \f(CW\*(C`SP\*(C'\fR is used to indicate to the caller how
many values are being returned.
.PP
In general these two ways of accessing the stack should not be mixed, or
confusion is likely to arise. The PUSH strategy is most useful when you
have no further use for the passed arguments, and just want to generate
and return a list of values, as in the \f(CWone_to_n()\fR example above. The
\&\f(CWST(i)\fR strategy is better when you still need to access the passed
arguments. In the example below,
.PP
.Vb 1
\&    # XS equivalent of: sub triple { map { $_ * 3} @_ }
\&
\&    void
\&    triple(...)
\&      PPCODE:
\&        SP += items;
\&        {
\&            int i;
\&            for (i = 0; i < items; i++) {
\&                int val  = (int)SvIV(ST(i));
\&                ST(i) = sv_2mortal(newSViv(val*3));
\&            }
\&        }
.Ve
.PP
\&\f(CW\*(C`SP\*(C'\fR is first incremented to reclaim the passed arguments which are still
on the stack; then one by one, each passed argument is retrieved, and then
each stack slot is replaced with a new mortal value. When the loop is
finished, the current stack frame contains a list of mortals, which is
then returned to the caller, with \f(CW\*(C`SP\*(C'\fR indicating how many items are
returned. Note that in this example the \f(CW\*(C`SP += items\*(C'\fR could have been
done at the end instead. However, if the code was doing a mixture of
updating the passed arguments \fIand\fR pushing extra return values, then
setting it early (before the first push) would be important.
.PP
Before pushing return values onto the stack (or storing values at \f(CWST(i)\fR
locations higher than the number of passed arguments), it is necessary to
ensure there is sufficient space on the stack. This can be achieved either
through the \f(CW\*(C`EXTEND(SP, n)\*(C'\fR macro as shown in the \f(CWone_to_n()\fR example
above, or by using the \*(AqX\*(Aq variants of the push macros, such as
\&\f(CWmXPUSHi()\fR, which can be used to check and extend the stack by one each
time. Doing a single \f(CW\*(C`EXTEND\*(C'\fR in advance is more efficient. \f(CW\*(C`EXTEND\*(C'\fR
will ensure that there is at least enough space on the stack for n further
items to be pushed.
.PP
If using the PUSH strategy, it is useful to understand in more detail how
pushing and the local stack pointer, \f(CW\*(C`SP\*(C'\fR are implemented. The generated
C file will have access to (among others) the following macro definitions
or similar:
.PP
.Vb 7
\&    #define dSP       SV **sp = PL_stack_sp
\&    #define SP        sp
\&    #define PUSHs(s)  *++sp = (s)
\&    #define mPUSHi(i) sv_setiv(PUSHs(sv_newmortal()), (IV)(i))
\&    #define PUTBACK   PL_stack_sp = sp
\&    #define SPAGAIN   sp = PL_stack_sp
\&    #define dXSARGS   dSP; ....
.Ve
.PP
The global (or per\-interpreter) variable \f(CW\*(C`PL_stack_sp\*(C'\fR is a pointer to
the current top\-most entry on the stack, equal initially to
\&\f(CW&ST(items\-1)\fR. On entry to the XSUB, the \f(CW\*(C`dXSARGS\*(C'\fR at its top will
cause the \f(CW\*(C`sp\*(C'\fR variable to be declared and initialised. This becomes a
\&\fIlocal\fR copy of the argument stack pointer. The standard stack
manipulation macros such as \f(CW\*(C`PUSHs\*(C'\fR all use this local copy.
.PP
The XS parser will usually emit two lines of C code similar to these
around the PP code block lines:
.PP
.Vb 3
\&    SP \-= items;
\&    ... PP lines ...
\&    PUTBACK; return;
.Ve
.PP
This has the effect of resetting the local copy of the stack pointer (but
\&\fInot\fR the stack pointer itself) back to the base of the current stack
frame, discarding any passed arguments. The original arguments are still
on the stack. \f(CWPUSHs()\fR etc will, starting at the base of the stack
frame, progressively overwrite any original arguments. Finally, the
\&\f(CW\*(C`PUTBACK\*(C'\fR sets the real stack pointer to the copy, making the changes
permanent, and also allowing the caller to determine how many arguments
were returned.
.PP
Any functions called from the XSUB will only see the value of
\&\f(CW\*(C`PL_stack_sp\*(C'\fR and not \f(CW\*(C`SP\*(C'\fR. So when calling out to a function which
manipulates the stack, you may need to resynchronise the two; for example:
.PP
.Vb 3
\&    PUTBACK;
\&    push_contents_of_array(av);
\&    SPAGAIN;
.Ve
.PP
The \f(CW\*(C`EXTEND(SP,n)\*(C'\fR and \f(CWmXPUSHfoo()\fR macros will update both
\&\f(CW\*(C`PL_stack_sp\*(C'\fR and \f(CW\*(C`SP\*(C'\fR if the extending causes the stack to be
reallocated.
.PP
Note that there are several \f(CWmPUSHfoo()\fR macros, which generally create a
temporary SV, set its value to the argument, and push it onto the stack.
These are:
.PP
.Vb 7
\&    mPUSHs(sv)         mortalise and push an SV
\&    mPUSHi(iv)         create+push mortal and set to the integer val
\&    mPUSHu(uv)         create+push mortal and set to the unsigned val
\&    mPUSHn(n)          create+push mortal and set to the num (float) val
\&    mPUSHp(str, len)   create+push mortal and set to the string+length
\&    mPUSHpvs("string") create+push mortal and set to the literal string
\&                         (perl 5.38.0 onwards)
.Ve
.PP
\fIThe NOT_IMPLEMENTED_YET: Keyword\fR
.IX Subsection "The NOT_IMPLEMENTED_YET: Keyword"
.PP
.Vb 3
\&    void
\&    foo(int a)
\&        NOT_IMPLEMENTED_YET:
.Ve
.PP
This keyword, as a fourth alternative to \f(CW\*(C`CODE\*(C'\fR, \f(CW\*(C`PPCODE\*(C'\fR and autocall,
generates a main body for the XSUB consisting solely of the C code:
.PP
.Vb 1
\&    Perl_croak(aTHX_ "Foo::Bar::foo: not implemented yet");
.Ve
.PP
The current implementation is quite buggy in terms of parsing and where
the keyword can appear within an XSUB, so it\*(Aqs generally better to avoid
it. It is documented here for completeness.
.SS "The XSUB Output Part"
.IX Subsection "The XSUB Output Part"
Following an XSUB\*(Aqs code part, any results may be post\-processed and
returned. Two keywords in particular support this: POSTCALL,  which allows for a block of code to be added after
any autocall in order to post\-process return values from the call, and
OUTPUT, which tells the parser to generate code to
return the value of \f(CW\*(C`RETVAL\*(C'\fR or to update the values of one or more
passed arguments.
.PP
These two optional keywords should each only be used once at most, and in
that order; but due to a parsing bug (kept for backwards compatibility),
they can appear in either order any number of times. But don\*(Aqt do that.
.PP
Note that the keywords described in "XSUB Generic Keywords" and "Sharing
XSUB bodies" may also appear in this part.
.PP
\fIThe POSTCALL: Keyword\fR
.IX Subsection "The POSTCALL: Keyword"
.PP
The \f(CW\*(C`POSTCALL\*(C'\fR keyword allows a block of code to be inserted directly after
any autocall or \f(CW\*(C`CODE\*(C'\fR code block (although it\*(Aqs really only of use with
autocall). It\*(Aqs typically used for cleaning up the return value from the
autocall. For example these two XSUBs are equivalent:
.PP
.Vb 5
\&    int
\&    foo(int a)
\&       POSTCALL:
\&         if (RETVAL < 0)
\&            RETVAL = 0
\&
\&    int
\&    foo(int a)
\&       CODE:
\&         RETVAL = foo(a);
\&         if (RETVAL < 0)
\&            RETVAL = 0
\&      OUTPUT:
\&        RETVAL
.Ve
.PP
\fIThe OUTPUT: Keyword\fR
.IX Subsection "The OUTPUT: Keyword"
.PP
.Vb 1
\&    # Common usage:
\&
\&    OUTPUT:
\&      RETVAL
\&
\&    # Rare usage:
\&
\&    OUTPUT:
\&      arg0
\&      SETMAGIC: DISABLE
\&      arg1
\&      SETMAGIC: ENABLE
\&      arg2 sv_setfoo(ST[2], arg2)
.Ve
.PP
The \f(CW\*(C`OUTPUT\*(C'\fR keyword can be used to indicate that the value of RETVAL
should be returned to the caller on the stack, and/or that the values of
certain passed Perl arguments should be updated with the current values of
the corresponding parameter variables. Each non\-blank line of the
\&\f(CW\*(C`OUTPUT\*(C'\fR block should contain the name of one variable, with optional
setting code, or a \f(CW\*(C`SETMAGIC:\*(C'\fR keyword with a value of \f(CW\*(C`ENABLE\*(C'\fR or
\&\f(CW\*(C`DISABLE\*(C'\fR.
.PP
The common usage is to list just the \f(CW\*(C`RETVAL\*(C'\fR variable:
.PP
.Vb 6
\&    int
\&    foo()
\&    CODE:
\&        RETVAL = ...;
\&    OUTPUT:
\&      RETVAL
.Ve
.PP
It is needed for XSUBs containing a \f(CW\*(C`CODE\*(C'\fR block to tell the XS compiler
to generate C code which will return the value of \f(CW\*(C`RETVAL\*(C'\fR to the caller.
For autocall XSUBs, this is done automatically without the need for the
\&\f(CW\*(C`OUTPUT\*(C'\fR keyword.
.PP
The second usage of \f(CW\*(C`OUTPUT\*(C'\fR is to specify parameters to be updated; this
usage has been almost completely replaced by using the
OUT
parameter modifier. For example these two XSUBs have identical behaviours,
but the second is the preferred form:
.PP
.Vb 6
\&    int
\&    foo1(a)
\&       INPUT:
\&         int &a
\&       OUTPUT:
\&         a
\&
\&    int
\&    foo2(IN_OUT int a)
.Ve
.PP
They both cause output C code  similar to this to be planted (with the
first part derived from a typemap):
.PP
.Vb 2
\&    sv_setiv(ST(0), (IV)a);
\&    SvSETMAGIC(ST(0));
.Ve
.PP
which updates the value of the passed SV with the current value of \f(CW\*(C`a\*(C'\fR,
and then calls the SV\*(Aqs \fIset\fR magic, if any: which will, for example,
cause a tied variable to have its \f(CWSTORE()\fR method called.
.PP
You can skip the planting of the \f(CWSvSETMAGIC()\fR magic call with
\&\f(CW\*(C`SETMAGIC: DISABLE\*(C'\fR; in the example at the start of this section, \f(CW\*(C`arg0\*(C'\fR
and \f(CW\*(C`arg2\*(C'\fR will have set magic, while \f(CW\*(C`arg1\*(C'\fR won\*(Aqt. The \f(CW\*(C`SETMAGIC\*(C'\fR
setting remains in force until another \f(CW\*(C`SETMAGIC\*(C'\fR, or notionally until
the end of the current \f(CW\*(C`OUTPUT\*(C'\fR block. In fact the current setting will
carry over into any further \f(CW\*(C`OUTPUT\*(C'\fR declarations within the same XSUB,
or since \fIxsubpp\fR 3.58, only into any declarations within the same
\&\f(CW\*(C`CASE\*(C'\fR branch.
.PP
The current setting of \f(CW\*(C`SETMAGIC\*(C'\fR is ignored for \f(CW\*(C`RETVAL\*(C'\fR, which is
usually setting the value of a fresh temporary SV which won\*(Aqt have any
attached magic anyway.
.PP
Finally, it is possible to override the typemap entry used to set the
value of the temporary SV or passed argument from the \f(CW\*(C`RETVAL\*(C'\fR or other
variables. Normally, in an XSUB like:
.PP
.Vb 4
\&    int
\&    foo(int abc)
\&      OUTPUT:
\&        abc
.Ve
.PP
the \f(CW\*(C`int\*(C'\fR type (via a two\-stage lookup in the system typemap) will yield
this output typemap entry:
.PP
.Vb 1
\&    sv_setiv($arg, (IV)$var);
.Ve
.PP
which, after variable expansion, may yield
.PP
.Vb 1
\&    sv_setiv(ST(0), (IV)abc);
.Ve
.PP
or similar. This can be overridden; for example
.PP
.Vb 4
\&    int
\&    foo(int abc)
\&      OUTPUT:
\&        abc   my_setiv(ST(0), (IV)abc);
.Ve
.PP
But importantly, unlike the similar syntax in \f(CW\*(C`INPUT\*(C'\fR lines, the override
text is \fInot\fR variable expanded. It is thus tricky to ensure that the
right arguments are used (such as \f(CWST(0)\fR). Basically this feature has a
design flaw and should probably be avoided. Since \fIxsubpp\fR 3.01 it\*(Aqs been
possible to have locally defined typemaps using the TYPEMAP keyword which is probably a better way to modify how
values are returned, for example,
.PP
.Vb 11
\&    typedef int myint
\&    ...
\&    TYPEMAP: <<EOF
\&    myint   T_MYINT
\&    INPUT
\&    T_MYINT
\&        $var = ($type)my_getiv($arg)
\&    OUTPUT
\&    T_MYINT
\&        my_setiv($arg, (IV)$var);
\&    EOF
\&
\&    int
\&    foo2(IN_OUT myint abc)
.Ve
.SS "The XSUB Cleanup Part"
.IX Subsection "The XSUB Cleanup Part"
Following an XSUB\*(Aqs output part, where code will have been planted to
return the value of \f(CW\*(C`RETVAL\*(C'\fR and \f(CW\*(C`OUT\*(C'\fR/\f(CW\*(C`OUTLIST\*(C'\fR parameters, it\*(Aqs
possible to inject some final clean\-up code by using the \f(CW\*(C`CLEANUP\*(C'\fR
keyword.
.PP
Note that the keywords described in "XSUB Generic Keywords" and "Sharing
XSUB bodies" may also appear in this part.
.PP
\fIThe CLEANUP: Keyword\fR
.IX Subsection "The CLEANUP: Keyword"
.PP
.Vb 8
\&    char *
\&    foo(int a)
\&      CODE:
\&        RETVAL = get_foo(a);
\&      OUTPUT:
\&        RETVAL
\&      CLEANUP:
\&        free(RETVAL); /* assuming get_foo() returns a malloced buffer */
.Ve
.PP
The \f(CW\*(C`CLEANUP\*(C'\fR keyword allows a block of code to be inserted directly
after any output code which has been generated automatically or via the
\&\f(CW\*(C`OUTPUT\*(C'\fR keyword. It can be used when an XSUB requires special clean\-up
procedures before it terminates. The code specified for the clean\-up block
will be added as the last statements in the XSUB before the final
\&\f(CW\*(C`XSRETURN(1);\*(C'\fR or similar.
.SS "XSUB Generic Keywords"
.IX Subsection "XSUB Generic Keywords"
There are a few per\-XSUB keywords which can appear anywhere within the
body of an XSUB. This is because they affect how the XSUB is registered
with the Perl interpreter, rather than affecting how the C code of the
XSUB itself is generated. These are described in the following
subsections. In addition there are a few more generic keywords which are
described later under "Sharing XSUB bodies".
.PP
On aesthetic grounds, it is best to use these keywords near the start of
the XSUB.
.PP
\fIThe PROTOTYPE: Keyword\fR
.IX Subsection "The PROTOTYPE: Keyword"
.PP
.Vb 4
\&    int
\&    foo1(int a, int b = 0)
\&      # this XSUB gets an auto\-generated \*(Aq$;$\*(Aq prototype
\&      PROTOTYPE: ENABLE
\&
\&    int
\&    foo2(int a, int b)
\&      # this XSUB doesn\*(Aqt get a prototype
\&      PROTOTYPE: DISABLE
\&
\&    int
\&    foo3(SV* a, int b)
\&      # this XSUB gets the specified prototype:
\&      PROTOTYPE: \e@$
\&
\&    int
\&    foo4(int a, int b)
\&      # this XSUB gets a blank () prototype
\&      PROTOTYPE:
.Ve
.PP
While the file\-scoped \f(CW\*(C`PROTOTYPES\*(C'\fR keyword turns automatic prototype
generation on or off for all subsequent XSUBs, the per\-XSUB \f(CW\*(C`PROTOTYPE\*(C'\fR
keyword overrides the setting for just the current XSUB. See the
PROTOTYPES section for details of what a
prototype is, and why you rarely need one.
.PP
This keyword\*(Aqs value can be either one of \f(CW\*(C`ENABLE\*(C'\fR/\f(CW\*(C`DISABLE\*(C'\fR to turn on
or off automatic prototype generation, or it can specify an explicit
prototype string, including the empty prototype.
.PP
\fIThe OVERLOAD: Keyword\fR
.IX Subsection "The OVERLOAD: Keyword"
.PP
.Vb 1
\&    MODULE = Foo PACKAGE = Foo::Bar
\&
\&    SV*
\&    subtract(SV* a, SV* b, bool swap)
\&      OVERLOAD: \- \-=
\&      CODE:
\&        ...
.Ve
.PP
The \f(CW\*(C`OVERLOAD\*(C'\fR keyword allows you to declare that this XSUB acts as an
overload method for the specified operators in the current package. The
example above is approximately equivalent to this Perl code:
.PP
.Vb 1
\&    package Foo::Bar;
\&
\&    sub subtract { ... }
\&
\&    use overload
\&        \*(Aq\-\*(Aq  => \e&subtract,
\&        \*(Aq\-=\*(Aq => \e&subtract;
.Ve
.PP
The rest of the line following the keyword, plus any further lines until
the next keyword, are interpreted as a space\-separated list of overloaded
operators. There is no check that they are valid operator names. The names
and symbols will eventually end up within double\-quoted strings in the C
file, so double\-quotes need to be escaped; in particular:
.PP
.Vb 1
\&      OVERLOAD: \e"\e"
.Ve
.PP
This could be regarded as an implementation bug, but we\*(Aqre stuck with it
now.
.PP
XSUBs used for overload methods are invoked with the same arguments as
Perl subroutines would be: for example, an overloaded binary operator will
trigger a call to the XSUB method with the first argument being an
overloaded object representing one of the two operands of the binary
operator; the second being the other operand (which may or may not be an
object); and third, a swap flag. See overload for the full details
of how these functions will be called, with what arguments. Note that
\&\f(CW\*(C`swap\*(C'\fR can in fact be undef in addition to false, to indicate an assign
overload such as \f(CW\*(C`+=\*(C'\fR. If this difference is important to your code, then
declare \f(CW\*(C`swap\*(C'\fR as type \f(CW\*(C`SV*\*(C'\fR so that you can use \fBSvOK()\fR and \fBSvTRUE()\fR
on it.
.PP
Bitwise operator methods sometimes take extra arguments: in
particular under \f(CW\*(C`use feature \*(Aqbitwise\*(Aq\*(C'\fR. So you may want to use an
ellipsis (something like \f(CW\*(C`(lobj, robj, swap, ...)\*(C'\fR) to skip them.
.PP
The net effect of the \f(CW\*(C`OVERLOAD\*(C'\fR keyword is to add some extra code to
the boot XSUB to register this XSUB as the handler for the specified
overload actions, in the same way that \f(CW\*(C`use overload\*(C'\fR does for Perl
methods.
.PP
See also the file\-scoped FALLBACK keyword for
details of how to set the fallback behaviour for the current package.
.PP
Note that \f(CW\*(C`OVERLOAD\*(C'\fR shouldn\*(Aqt be mixed with the ALIAS keyword; the value of \f(CW\*(C`ix\*(C'\fR will be undefined for any overload
method call.
.PP
The "T_PTROBJ and opaque handles" section contains a fully\-worked
example of using the \f(CW\*(C`T_PTROBJ\*(C'\fR typemap to wrap a simple arithmetic
library. The result of that wrapper allows you to write Perl code such as:
.PP
.Vb 3
\&    my $i2  = My::Num\->new(2);
\&    my $i7  = My::Num\->new(7);
\&    my $i13 = My::Num\->new(13);
\&
\&    my $x = $i13\->add($i7)\->divide($i2);
\&    printf "val=%d\en", $x\->val();
.Ve
.PP
Using overloading, we would like to be able to write those last two lines
more simply as:
.PP
.Vb 2
\&    my $x = ($i13 + $i7)/$i2;
\&    printf "val=%d\en", $x;
.Ve
.PP
The following additions and modifications to that example XS code show how
to add overloading:
.PP
.Vb 1
\&    FALLBACK: UNDEF
\&
\&    int
\&    mynum_val(My::Num x, ...)
\&      OVERLOAD: 0+
\&
\&    My::Num
\&    mynum_add(My::Num x, My::Num y, bool swap)
\&      OVERLOAD: +
\&      C_ARGS: x, y
\&      INIT:
\&        if (swap) {
\&            mynum* tmp = x; x = y; y = tmp;
\&        }
\&
\&     # ... and three similar XSUBs for
\&     # mynum_subtract, mynum_multiply, mynum_divide ...
.Ve
.PP
The \f(CW\*(C`FALLBACK\*(C'\fR line isn\*(Aqt actually necessary as this is the default
anyway, but is included to remind you that the keyword can be used.
.PP
Overloading is added to the \f(CWmynum_val()\fR method so that it automatically
returns the value of an object when used in a numeric context (such as for
the \f(CW\*(C`printf\*(C'\fR above). The ellipsis is added to ignore the extra two
arguments passed to an overload method.
.PP
The \f(CWmynum_add()\fR method from the \f(CW\*(C`T_PTROBJ\*(C'\fR example which, via
aliasing, handled all four of the arithmetic operations, is now split into
four separate XSUBs, since \f(CW\*(C`ALIAS\*(C'\fR and \f(CW\*(C`OVERLOAD\*(C'\fR don\*(Aqt mix.
.PP
The main change to each arithmetic XSUB, apart from adding the \f(CW\*(C`OVERLOAD\*(C'\fR
keyword, is that there is an extra \f(CW\*(C`swap\*(C'\fR parameter. There\*(Aqs no real need
to use it for addition and multiplication, but it is important for the
non\-commutative subtraction and division operations.
.PP
That example uses the \f(CW\*(C`T_PTROBJ\*(C'\fR typemap to process the second argument,
which in the most general usage may not be an object. For example the
second and third of these lines will croak with an \f(CW\*(C`Expected foo to be of
type My::Num, got scalar\*(C'\fR error:
.PP
.Vb 3
\&    $i13 + My::Num\->new(7);
\&    $i13 + 7;
\&    $i13 + "7";
.Ve
.PP
If it is necessary to handle this, then you may need to create your own
typemap: for example, something similar to \f(CW\*(C`T_PTROBJ\*(C'\fR, but with an INPUT
template along the lines of:
.PP
.Vb 8
\&    T_MYNUM
\&        SV *sv = $arg;
\&        SvGETMAGIC(sv);
\&        if (!SvROK(sv)) {
\&            sv = sv_newmortal();
\&            sv_setref_pv(sv, "$ntype", mynum_new(SvIV($arg));
\&        }
\&        ....
.Ve
.PP
Finally, although not directly related to XS, the following could be added
to \fINum.pm\fR to allow integer literals to be used directly:
.PP
.Vb 7
\&    sub import {
\&        overload::constant integer =>
\&            sub {
\&                my $str = shift;
\&                return My::Num\->new($str);
\&            };
\&    }
.Ve
.PP
which then allows these lines:
.PP
.Vb 3
\&    my $i2  = My::Num\->new(2);
\&    my $i7  = My::Num\->new(7);
\&    my $i13 = My::Num\->new(13);
.Ve
.PP
to be rewritten more cleanly as:
.PP
.Vb 3
\&    my $i2  = 2;
\&    my $i7  = 7;
\&    my $i13 = 13;
.Ve
.PP
\fIThe ATTRS: Keyword\fR
.IX Subsection "The ATTRS: Keyword"
.PP
.Vb 1
\&    MODULE = Foo::Bar PACKAGE = Foo::Bar
\&
\&    SV*
\&    debug()
\&      ATTRS: lvalue
\&      PPCODE:
\&        # return $Foo::Bar::DEBUG, creating it if not already present
\&        # (NB: XPUSHs() not needed here as the stack always has one
\&        # allocated slot available when an XSUB is called):
\&        PUSHs(GvSV(gv_fetchpvs("Foo::Bar::DEBUG", GV_ADD, SVt_IV)));
.Ve
.PP
The \f(CW\*(C`ATTRS\*(C'\fR keyword allows you to apply subroutine attributes to an XSUB
in a similar fashion to Perl subroutines. The XSUB in the example above is
equivalent to this Perl:
.PP
.Vb 1
\&    sub debug :lvalue { return $Foo::Bar::DEBUG }
.Ve
.PP
and both can be called like this:
.PP
.Vb 3
\&    use Foo::Bar;
\&    Foo::Bar::debug() = 99;
\&    print "$Foo::Bar::DEBUG\en"; # prints 99
.Ve
.PP
This keyword consumes all lines until the next keyword. The contents of
each line are interpreted as space\-separated attributes. The attributes
are applied at the time the XS module is loaded. This:
.PP
.Vb 4
\&    void
\&    foo(...)
\&      ATTRS: aaa
\&             bbb(x,y) ccc
.Ve
.PP
is approximately equivalent to:
.PP
.Vb 3
\&    use attributes Foo::Bar, \e&foo, \*(Aqaaa\*(Aq;
\&    use attributes Foo::Bar, \e&foo, \*(Aqbbb(x,y)\*(Aq;
\&    use attributes Foo::Bar, \e&foo, \*(Aqccc\*(Aq;
.Ve
.PP
User\-defined attributes, just like with Perl subs, will trigger a call to
\&\f(CWMODIFY_CODE_ATTRIBUTES()\fR, as described in attributes.
.PP
Note that not all built\-in subroutine attributes necessarily make sense
applied to XSUBs.
.PP
Currently the parsing of white\-space is crude: \f(CW\*(C`bbb(x, y)\*(C'\fR is
misinterpreted as two separate attributes, \f(CW\*(Aqbbb(x,\*(Aq\fR and \f(CW\*(Aqy)\*(Aq\fR.
.PP
The \f(CW\*(C`ATTRS\*(C'\fR keyword can\*(Aqt currently be used in conjunction with \f(CW\*(C`ALIAS\*(C'\fR
or \f(CW\*(C`INTERFACE\*(C'\fR; in this case, the attributes are just silently ignored.
.SS "Sharing XSUB bodies"
.IX Subsection "Sharing XSUB bodies"
Sometimes you want to write several XSUBs which are very similar: they
all have the same signature, have the same generated code to convert
arguments and return values between Perl and C, and may only differ in a
few lines in the main body or in which C library function they wrap. It is
in fact possible to share the same XSUB function among multiple Perl CVs.
For example, \f(CW&Foo::Bar::add\fR and \f(CW&Foo::Bar::subtract\fR could be two
separate CVs in the Perl namespace which both point to the same XSUB,
\&\f(CW\*(C`XS_Foo_\|_Bar_\|_add()\*(C'\fR say. But each CV holds some sort of unique
identifier which can be accessed by the XSUB so that it can determine
whether it should behave as \f(CW\*(C`add\*(C'\fR or \f(CW\*(C`subtract\*(C'\fR.
.PP
Both the \f(CW\*(C`ALIAS\*(C'\fR and \f(CW\*(C`INTERFACE\*(C'\fR keywords (described below) allow
multiple CVs to share the same XSUB. The difference between them is that
\&\f(CW\*(C`ALIAS\*(C'\fR is intended for when you supply the main body of the XSUB
yourself (e.g. using \f(CW\*(C`CODE\*(C'\fR): it sets an integer variable, \f(CW\*(C`ix\*(C'\fR (derived
from the passed CV), which you can use in a \f(CWswitch()\fR statement or
similar. Conversely, \f(CW\*(C`INTERFACE\*(C'\fR is intended for use with autocall;
information stored in the CV indicates which C library function should be
autocalled.
.PP
Finally, there is the \f(CW\*(C`CASE\*(C'\fR keyword, which allows the whole body of an
XSUB (not just the \f(CW\*(C`CODE\*(C'\fR part) to have alternate cases. It can be
thought of as a \f(CWswitch()\fR analogue which works at the top\-most XS level
rather than at the C level. The value the \f(CW\*(C`CASE\*(C'\fR acts on could be
\&\f(CW\*(C`items\*(C'\fR for example, or it could be used in conjunction with the \f(CW\*(C`ALIAS\*(C'\fR
keyword and switch on the value of \f(CW\*(C`ix\*(C'\fR.
.PP
\fIThe ALIAS: Keyword\fR
.IX Subsection "The ALIAS: Keyword"
.PP
.Vb 7
\&    int add(int x, int y)
\&      ALIAS:
\&        # implicit: add = 0
\&        subtract = 1
\&        multiply = 2  divide = 3
\&      CODE:
\&        switch (ix) { ... }
.Ve
.PP
Note that this keyword can appear anywhere within the body of an XSUB.
.PP
The \f(CW\*(C`ALIAS\*(C'\fR keyword allows a single XSUB to have two or more Perl names
and to know which of those names was used when it was invoked. Each alias
is given an integer index value, with the main name of the XSUB being
index 0. This index is accessible via the variable \f(CW\*(C`ix\*(C'\fR which is
initialised based on which CV (i.e. which Perl subroutine) was called.
.PP
Note that an XSUB may be shared by multiple CVs, and each CV may have
multiple names. Given the \f(CW\*(C`add\*(C'\fR XSUB definition above, and given this
Perl code:
.PP
.Vb 2
\&    use Foo::Bar;
\&    BEGIN { *addition = *add }
.Ve
.PP
Then in the \f(CW\*(C`Foo::Bar\*(C'\fR namespace, the entries \f(CW\*(C`add\*(C'\fR and \f(CW\*(C`addition\*(C'\fR
point to the same CV, which has index 0 stored in it; while \f(CW\*(C`subtract\*(C'\fR
points to a second CV with index 1, and so on. All four CVs point to the
same C function, \f(CW\*(C`XS_Foo_\|_Bar_\|_add()\*(C'\fR.
.PP
The alias name can be either a simple function name or can include a
package name. The alias value to the right of the \f(CW\*(C`=\*(C'\fR may be either a
literal positive integer or a word (which is expected to be a CPP define
or enum constant).
.PP
The rest of the line following the \f(CW\*(C`ALIAS\*(C'\fR keyword, plus any further
lines until the next keyword, are assumed to contain zero or more alias
name and value pairs.
.PP
A warning will be produced if you create more than one alias to the same
index value. If you want multiple aliases with the same value, then a
backwards\-compatible way of achieving this is via separate CPP defines to
the same value, e.g.
.PP
.Vb 2
\&    #define DIVIDE   3
\&    #define DIVISION 3
\&
\&    ALIAS:
\&      divide   = DIVIDE
\&      division = DIVISION
.Ve
.PP
Since \fIxsubpp\fR 3.51, alias values may refer to other alias names (or to
the main function name) by using \f(CW\*(C`=>\*(C'\fR rather than the \f(CW\*(C`=\*(C'\fR symbol:
.PP
.Vb 3
\&    ALIAS:
\&      divide   =  3
\&      division => divide
.Ve
.PP
Both alias names and \f(CW\*(C`=>\*(C'\fR values may be fully\-qualified:
.PP
.Vb 4
\&    ALIAS:
\&      red         =  1
\&      COLOR::red  => red
\&      COLOUR::red => COLOR::red
.Ve
.PP
Note that any PREFIX is applied to the main
name of the XSUB, but not to any aliases.
.PP
See "T_PTROBJ and opaque handles" for a fully\-worked example using
aliases.
.PP
See INTERFACE below for an alternative to
\&\f(CW\*(C`ALIAS\*(C'\fR which is more suited for autocall. Note that \f(CW\*(C`ALIAS\*(C'\fR should not
be used together with any of \f(CW\*(C`ATTRS\*(C'\fR, \f(CW\*(C`INTERFACE\*(C'\fR, or \f(CW\*(C`OVERLOAD\*(C'\fR.
.PP
\fIThe INTERFACE: Keyword\fR
.IX Subsection "The INTERFACE: Keyword"
.PP
.Vb 1
\&    MODULE = Foo::Bar PACKAGE = Foo::Bar PREFIX = foobar_
\&
\&    int
\&    arith(int a, int b)
\&        INTERFACE: foobar_add    foobar_subtract
\&                   foobar_divide foobar_multiply
.Ve
.PP
This keyword can appear anywhere within the initialisation part of an XSUB.
.PP
This keyword provides similar functionality to \f(CW\*(C`ALIAS\*(C'\fR, but is intended
for XSUBs which use autocall. It allows a single XSUB to have multiple
names in the Perl namespace which, when invoked, will call the correct
wrapped C library function.
.PP
In the example above there is a single C XSUB function created (called
\&\f(CW\*(C`XS_Foo_\|_Bar_arith\*(C'\fR), plus four CVs in the Perl namespace called
\&\f(CW\*(C`Foo::Bar::add\*(C'\fR etc. Calling \f(CWFoo::Bar::add()\fR from Perl invokes
\&\f(CW\*(C`XS_Foo_\|_Bar_arith()\*(C'\fR with some indication of which C function to call,
which is then autocalled. \f(CW\*(C`ALIAS\*(C'\fR achieves this by storing an index value
in each CV and making it available via the \f(CW\*(C`ix\*(C'\fR variable, while
\&\f(CW\*(C`INTERFACE\*(C'\fR currently achieves this by storing a C function pointer in
each CV. So the \f(CWFoo::Bar::add()\fR CV holds a pointer to the
\&\f(CWfoobar_add()\fR C function. The action of the XSUB is to extract the
parameter values from the passed arguments and the function pointer from
the CV, then call the underlying C function.
.PP
Note that storing a function pointer in the CV is an implementation detail
which could change in the future. See "The INTERFACE_MACRO: Keyword" for
details of how to customise the setting and retrieving of this value in
the CV.
.PP
The rest of the line following the \f(CW\*(C`INTERFACE\*(C'\fR keyword, plus any further
lines until the next keyword, are assumed to contain zero or more
interface names, separated by white space (or commas).
.PP
An interface name is always used as\-is for the name of the wrapped C
function. If the name contains a package separator, then it will be
used as\-is to generate the Perl name; otherwise any prefix is stripped and
the current package name is prepended. The following shows how a few such
interface names would be processed (assuming the current PACKAGE and
PREFIX are \f(CW\*(C`Foo::bar\*(C'\fR and \f(CW\*(C`foobar_\*(C'\fR):
.PP
.Vb 5
\&    Interface name     Perl function name   C function name
\&    \-\-\-\-\-\-\-\-\-\-\-\-\-\-     \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-   \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
\&    abc                Foo::Bar::abc        abc
\&    foobar_abc         Foo::Bar::abc        foobar_abc
\&    X::Y::foobar_def   X::Y::foobar_def     X::Y::foobar_def
.Ve
.PP
Unlike \f(CW\*(C`ALIAS\*(C'\fR, the XSUB name is used only as the name of the generated C
function; in the example above, it doesn\*(Aqt cause a Perl function called
\&\f(CWarith()\fR to be created.
.PP
See "T_PTROBJ and opaque handles" for a complete example using
\&\f(CW\*(C`INTERFACE\*(C'\fR with the \f(CW\*(C`T_PTROBJ\*(C'\fR typemap. But note that before \fIxsubpp\fR
3.60, \f(CW\*(C`INTERFACE\*(C'\fR would not work properly on XSUBs used with Perlish
return types (as used by \f(CW\*(C`T_PTROBJ\*(C'\fR), such as
.PP
.Vb 3
\&    Foo::Bar
\&    foo(...)
\&        ....
.Ve
.PP
This has mostly been fixed in 3.60 onwards, but may generate invalid C
code (in particular, invalid function pointer casts) for XSUBs having a
\&\f(CW\*(C`C_ARGS\*(C'\fR keyword, unless the value of \f(CW\*(C`C_ARGS\*(C'\fR is a simple list of
parameter names.
.PP
Note that \f(CW\*(C`INTERFACE\*(C'\fR should not be used together with either of \f(CW\*(C`ALIAS\*(C'\fR
or \f(CW\*(C`ATTRS\*(C'\fR.
.PP
The INTERFACE_MACRO: Keyword
.IX Subsection "The INTERFACE_MACRO: Keyword"
.PP
.Vb 5
\&    int
\&    arith(int a, int b)
\&        INTERFACE:       add subtract divide multiply
\&        INTERFACE_MACRO: MY_FUNC_GET
\&                         MY_FUNC_SET
.Ve
.PP
Note that this keyword is deprecated since it assumes a particular
implementation for the \f(CW\*(C`INTERFACE\*(C'\fR keyword, which might change in future.
.PP
This keyword can appear anywhere within the input
or initialisation parts of an XSUB.
.PP
By default, the C code generated by the \f(CW\*(C`INTERFACE\*(C'\fR keyword plants calls
to two macros, \f(CW\*(C`XSINTERFACE_FUNC_SET\*(C'\fR and \f(CW\*(C`XSINTERFACE_FUNC\*(C'\fR, which are
used respectively to set (at boot time) a field in the CV to the address
of the C function pointer to use, and to retrieve (at run time) that value
from the CV.
.PP
The \f(CW\*(C`INTERFACE_MACRO\*(C'\fR macro allows you to override the names of the two
macros to be used for this purpose. The rest of the line following the
\&\f(CW\*(C`INTERFACE_MACRO\*(C'\fR keyword, plus any further lines until the next keyword,
should contain (in total) two words which are taken to be macro names.
.PP
The get macro takes three parameters: the return type of the function, the
CV which holds the function\*(Aqs pointer value, and the field within the CV
which has the pointer value. It should return a C function pointer. The
setter macro has two parameters: the CV, and the function pointer.
.PP
Suppose that in the example above, pointers to the \f(CWmultiply()\fR,
\&\f(CWdivide()\fR, \f(CWadd()\fR and \f(CWsubtract()\fR functions are kept in a global C
array called \f(CW\*(C`arith_ptrs[]\*(C'\fR with offsets specified by the enum values
\&\f(CW\*(C`multiply_off\*(C'\fR, \f(CW\*(C`divide_off\*(C'\fR, \f(CW\*(C`add_off\*(C'\fR and \f(CW\*(C`subtract_off\*(C'\fR. Then one
could use:
.PP
.Vb 4
\&    #define MY_FUNC_GET(ret, cv, f) \e
\&        ((XSINTERFACE_CVT_ANON(ret))arith_ptrs[CvXSUBANY(cv).any_i32])
\&    #define MY_FUNC_SET(cv, f) \e
\&        CvXSUBANY(cv).any_i32 = CAT2(f, _off)
.Ve
.PP
to store an array index in the CV, rather than storing the actual function
pointer.
.PP
\fIThe CASE: Keyword\fR
.IX Subsection "The CASE: Keyword"
.PP
.Vb 11
\&    int
\&    foo(int a, int b = NO_INIT, int c = NO_INIT)
\&        CASE: items == 1
\&            C_ARGS: 0, a
\&        CASE: items == 2
\&            C_ARGS: b, a
\&        CASE:
\&            CODE:
\&                RETVAL = b > c ? foo(b, a) : bar(b, a);
\&            OUTPUT:
\&                RETVAL
.Ve
.PP
The \f(CW\*(C`CASE\*(C'\fR keyword allows an XSUB to effectively have multiple bodies,
but with only a single Perl name (unlike \f(CW\*(C`ALIAS\*(C'\fR, which has multiple
names). Which body is run depends on which CASE expression is the first to
evaluate to true. Unlike C\*(Aqs \f(CW\*(C`case\*(C'\fR keyword, execution doesn\*(Aqt fall
though to the next branch, so there is no XS equivalent of the \f(CW\*(C`break\*(C'\fR
keyword. The expression for the last CASE is optional, and if not present,
acts as a default branch.
.PP
The example above translates to approximately this C code:
.PP
.Vb 1
\&    if (items < 1 || items > 3) { croak("..."); }
\&
\&    if (items == 1) {
\&        int RETVAL;
\&        int a = (int)SvIV(ST(0)); int b = /* etc */
\&        RETVAL = foo(0, a);
\&        /* ... return RETVAL as ST(0) ... */
\&    }
\&    else if (items == 2) {
\&        int RETVAL;
\&        int a = (int)SvIV(ST(0)); int b = /* etc */
\&        RETVAL = foo(b, a);
\&        /* ... return RETVAL as ST(0) ... */
\&    }
\&    else {
\&        int RETVAL;
\&        int a = (int)SvIV(ST(0)); int b = /* etc */
\&        RETVAL = b > c ? foo(b, a) : bar(b, a);
\&        /* ... return RETVAL as ST(0) ... */
\&    }
\&
\&    XSRETURN(1);
.Ve
.PP
Each \f(CW\*(C`CASE\*(C'\fR keyword precedes an entire normal XSUB body, including all
keywords from \f(CW\*(C`PREINIT\*(C'\fR to \f(CW\*(C`CLEANUP\*(C'\fR. Generic XSUB keywords can be
placed within any \f(CW\*(C`CASE\*(C'\fR body. The code generated for each \f(CW\*(C`if\*(C'\fR/\f(CW\*(C`else\*(C'\fR
branch includes nearly all the code that would usually be generated for a
complete XSUB body, including argument processing and return value
stack processing.
.PP
Note that the CASE expressions are outside of the scope of any parameter
variable declarations, so those values can\*(Aqt be used. Typical values which
\&\fIare\fR in scope and might be used are the \f(CW\*(C`items\*(C'\fR variable which
indicates how many arguments were passed (see "Ellipsis: variable\-length
parameter lists") and, in the presence of \f(CW\*(C`ALIAS\*(C'\fR, the \f(CW\*(C`ix\*(C'\fR variable.
.PP
Here\*(Aqs another example, this time in conjunction with \f(CW\*(C`ALIAS\*(C'\fR to wrap the
same C function as two separate Perl functions, the second of which
(perhaps for backwards compatibility reasons) takes its arguments in the
reverse order. This is a somewhat contrived example, but
demonstrates how the \f(CW\*(C`ALIAS\*(C'\fR keyword must be within one of the \f(CW\*(C`CASE\*(C'\fR
branches (it doesn\*(Aqt matter which), as \f(CW\*(C`CASE\*(C'\fR must always appear in the
outermost scope of the XSUB\*(Aqs body:
.PP
.Vb 6
\&    int
\&    foo(int a, int b)
\&        CASE: ix == 0
\&        CASE: ix == 1
\&            ALIAS: foo_rev = 1
\&            C_ARGS: b, a
.Ve
.PP
Note that using old\-style parameter declarations in conjunction with
\&\f(CW\*(C`INPUT\*(C'\fR allows the types of the parameters to vary between branches:
.PP
.Vb 8
\&    int
\&    foo(a, int b = 0)
\&        CASE: items == 1
\&            INPUT:
\&                short a
\&        CASE: items == 2
\&            INPUT:
\&                long a
.Ve
.PP
In practice, \f(CW\*(C`CASE\*(C'\fR produces bloated code with all the argument and
return value processing duplicated within each branch, is not often all
that useful, and can often be better written just by using a \f(CW\*(C`switch\*(C'\fR
statement within a \f(CW\*(C`CODE\*(C'\fR block.
.SS "Using Typemaps"
.IX Subsection "Using Typemaps"
This section describes the basic facts about using typemaps. For full
information on creating your own typemaps plus a comprehensive list of
what standard typemaps are available, see the perlxstypemap document.
.PP
Typemaps are sets of rules which map C types such as \f(CW\*(C`int\*(C'\fR to logical XS
types such as \f(CW\*(C`T_IV\*(C'\fR, and from there to \f(CW\*(C`INPUT\*(C'\fR and \f(CW\*(C`OUTPUT\*(C'\fR templates
such as \f(CW\*(C`$var = ($type)SvIV($arg)\*(C'\fR and \f(CW\*(C`sv_setiv($arg, (IV)$var)\*(C'\fR which,
after variable expansion, generate C code to convert back and forth
between Perl arguments and C auto variables.
.PP
There is a standard system typemap file bundled with Perl for common C and
Perl types, but in addition, you can add your own typemap file. From
\&\fIxsubpp\fR 3.01 onwards you can also include extra typemap declarations
in\-line within the XS file.
.PP
\fILocations and ordering of typemap processing\fR
.IX Subsection "Locations and ordering of typemap processing"
.PP
Typemap definitions are processed in order, with more recent entries
overriding any earlier ones. Definitions are read in first from files and
then from TYPEMAP sections in the XS file.
.PP
When considering how files are located and read in, note that the XS
parser will initially change directory to the directory containing the
\&\fIFoo.xs\fR file that is about to be processed, which will affect any
subsequent relative paths. Then any typemap files are located and read in.
The files come from two sources: standard and explicit.
.PP
Standard typemap files are always called \f(CW\*(C`typemap\*(C'\fR and are searched for
in a standard set of locations (relative to \f(CW@INC\fR and to the current
directory), and any matched files are read in. These paths are, in order
of processing:
.PP
.Vb 1
\&    "$_/ExtUtils/typemap" for reverse @INC
\&
\&    ../../../../lib/ExtUtils/typemap
\&    ../../../../typemap
\&    ../../../lib/ExtUtils/typemap
\&    ../../../typemap
\&    ../../lib/ExtUtils/typemap
\&    ../../typemap
\&    ../lib/ExtUtils/typemap
\&    ../typemap
\&    typemap
.Ve
.PP
Note that searching \f(CW@INC\fR in reverse order means that typemap files
found earlier in \f(CW@INC\fR are processed later, and thus have higher
priority.
.PP
Explicit typemap files are specified either via \f(CW\*(C`xsubpp \-typemap foo ...\*(C'\fR
command line switches, or programmatically by an array passed as:
.PP
.Vb 1
\&    ExtUtils::ParseXS::process_file(..., typemap => [\*(Aqfoo\*(Aq,...]);
.Ve
.PP
These files are read in order, and the parser dies if any explicitly
listed file is not found.
.PP
Prior to \fIxsubpp\fR 2.09_01, \f(CW@INC\fR wasn\*(Aqt searched, and standard files
were searched for and processed \fIbefore\fR any explicit ones. From 2.09_01
onwards, standard files were processed \fIafter\fR any explicit ones. From
3.60 onwards, explicit files are again processed last, and thus take
priority over standard files. Separately, in 3.01 onwards, \f(CW\*(C`TYPEMAP\*(C'\fR
sections are then processed in order after all files have been processed.
.PP
Note also that \fIExtUtils::MakeMaker\fR usually invokes \fIxsubpp\fR with two
\&\f(CW\*(C`\-typemap\*(C'\fR arguments: the first being the system typemap and the second
being the module\*(Aqs typemap file, if any. This compensates for older Perls
not searching \f(CW@INC\fR.
.PP
For a typical distribution, all this complication usually results in the
typemap file bundled with Perl being read in first, then the typemap file
included with the distribution adding to (and overriding) any standard
definitions, then any \f(CW\*(C`TYPEMAP:\*(C'\fR entries in the XS file overriding
everything.
.PP
\fIReusing, redefining and adding typemap entries\fR
.IX Subsection "Reusing, redefining and adding typemap entries"
.PP
Both typemap files and \f(CW\*(C`TYPEMAP\*(C'\fR blocks can have up to three sections:
\&\f(CW\*(C`TYPEMAP\*(C'\fR (which is implicit at the start of the file or block) and
\&\f(CW\*(C`INPUT\*(C'\fR and \f(CW\*(C`OUTPUT\*(C'\fR. There is no requirement for all three sections to
be present. Whatever \fIis\fR present is added to the global state for that
section, either adding a new entry or redefining an existing entry.
.PP
Probably the simplest use of an additional typemap entry is to map a new C
type to an \fIexisting\fR XS type; for example, given this C type:
.PP
.Vb 1
\&    typedef enum { red, green, blue } colors;
.Ve
.PP
then adding the following C\-to\-XS type\-mapping entry to the typemap would
be sufficient if you just want to treat such enums as simple integers when
used as parameter and return types:
.PP
.Vb 1
\&    colors T_IV
.Ve
.PP
Or you could override just an existing INPUT or OUTPUT template; for
example:
.PP
.Vb 3
\&    OUTPUT
\&    T_IV
\&        my_sv_setiv($arg, (IV)$var);
.Ve
.PP
For a completely novel type you might want to add an entry to all three
sections:
.PP
.Vb 1
\&    foo   T_FOO
\&
\&    INPUT
\&    T_FOO
\&            $var = ($type)get_foo_from_sv($arg);
\&
\&    OUTPUT
\&    T_FOO
\&            set_sv_to_foo($arg, $var);
.Ve
.PP
\fICommon typemaps\fR
.IX Subsection "Common typemaps"
.PP
This section gives an overview of what common typemap entries are
available for use. See the perlxstypemap document for a complete list,
or examine the \fItypemap\fR file which is bundled with the Perl
distribution. Also, see "T_PTROBJ and opaque handles" for a detailed
dive into one particular typemap which is particularly useful for mapping
between Perl objects and C handles. See "Returning Values from an XSUB"
for a general discussion about returning one or more values from an XSUB,
where typemaps can sometimes be of use (and sometimes aren\*(Aqt).
.PP
Standard signed C int types such as \f(CW\*(C`int\*(C'\fR, \f(CW\*(C`long\*(C'\fR and \f(CW\*(C`short\*(C'\fR, are all
mapped to the \f(CW\*(C`T_IV\*(C'\fR XS type. Integer\-like Perl types such as \f(CW\*(C`IV\*(C'\fR and
\&\f(CW\*(C`I32\*(C'\fR are also mapped to this. If a parameter is declared as something
mapping to \f(CW\*(C`T_IV\*(C'\fR, then the \f(CW\*(C`IV\*(C'\fR value of the passed SV will be
extracted (perhaps first converting a string value like \f(CW"123"\fR to an
IV), then that value will be cast to the final C type, with the usual C
rules for casting between integer types. Conversely, when returning a
value, the C value is first cast to \f(CW\*(C`IV\*(C'\fR, then the SV is set to that IV
value.
.PP
Similarly, common C and Perl unsigned types map to \f(CW\*(C`T_UV\*(C'\fR, and values
are converted back and forth via \f(CW\*(C`(UV)\*(C'\fR casts. A few unsigned types such
as \f(CW\*(C`U16\*(C'\fR and \f(CW\*(C`U32\*(C'\fR are instead mapped to \f(CW\*(C`T_U_SHORT\*(C'\fR and \f(CW\*(C`T_U_LONG\*(C'\fR XS
types, but these have the same effect as \f(CW\*(C`T_UV\*(C'\fR.
.PP
The \f(CW\*(C`unsigned char\*(C'\fR type is treated similarly to other \f(CW\*(C`T_UV\*(C'\fR types, but
\&\f(CW\*(C`char\*(C'\fR is treated as a string rather than an integer. A \f(CW\*(C`char\*(C'\fR parameter
will treat its passed argument as a string and set the auto variable to
the first \fIbyte\fR of that string (which may produce weird results with
UTF\-8 strings). Returning a \f(CW\*(C`char\*(C'\fR value will return a one\-character
string to the Perl caller.
.PP
The \f(CW\*(C`char *\*(C'\fR type and its common variants are mapped to \f(CW\*(C`T_PV\*(C'\fR. Passed
parameters will (via \f(CWSvPV()\fR or similar) return a string buffer
representing that SV. This buffer may be part of the SV if that SV has a
string value (or if it can be converted to a string value), or it may be a
temporary buffer otherwise. For example, an SV holding a reference to an
array might return a temporary string buffer with the value
\&\f(CW"ARRAY(0x12345678)"\fR. When an XSUB has a return type which maps to
\&\f(CW\*(C`T_PV\*(C'\fR, the temporary SV which is to be returned gets assigned the
current value of \f(CW\*(C`RETVAL\*(C'\fR, with the string\*(Aqs length being determined by
\&\f(CWstrlen()\fR or its equivalent.
.PP
See "Unicode and UTF\-8" for the difficulties associated with handling
UTF\-8 strings.
.PP
The \f(CW\*(C`float\*(C'\fR, \f(CW\*(C`double\*(C'\fR and \f(CW\*(C`NV\*(C'\fR types map to \f(CW\*(C`T_FLOAT\*(C'\fR, \f(CW\*(C`T_DOUBLE\*(C'\fR and
\&\f(CW\*(C`T_NV\*(C'\fR XS types, which all operate by converting to and from an SV via
\&\f(CWsv_setnv()\fR and \f(CWSvNV(sv)\fR with suitable casting.
.PP
The \f(CW\*(C`SV*\*(C'\fR type maps to \f(CW\*(C`T_SV\*(C'\fR, which basically does no processing and
allows you to access the actual passed SV argument.
.PP
\fIT_PTROBJ and opaque handles\fR
.IX Subsection "T_PTROBJ and opaque handles"
.PP
A common interface arrangement for C libraries is that some sort of
\&\fIcreate\fR function creates and returns a handle, which is a pointer to
some opaque data. Other function calls are then passed that handle as an
argument, until finally some sort of destroy function frees the handle and
its data.
.PP
The \f(CW\*(C`T_PTROBJ\*(C'\fR typemap is one common method for mapping Perl objects to
such C library handles; see "T_PTROBJ" in perlxstypemap. Behind the scenes,
it uses blessed scalar objects with the scalar\*(Aqs integer value set to the
address of the handle. The \f(CW\*(C`INPUT\*(C'\fR code template of the \f(CW\*(C`T_PTROBJ\*(C'\fR
typemap first checks that the passed SV argument is an RV referring to an
object blessed into the Perl class (or a derived class) associated with
the parameter\*(Aqs declared type, and then retrieves the pointer from the
integer value of that object. The \f(CW\*(C`OUTPUT\*(C'\fR template creates a new blessed
RV\-to\-SV with the handle address stored in it.
.PP
For the purposes of an example, we\*(Aqll create here a minimal example C
library called \f(CW\*(C`mynum\*(C'\fR, which we\*(Aqll then proceed to wrap using XS. This
library just stores an integer in its opaque data. In real life you would
be wrapping an existing library which stores something more interesting,
such as a complex number or a multiple precision integer.
.PP
The following sample library code might go in the initial \*(AqC\*(Aq part of the
XS file:
.PP
.Vb 1
\&    typedef struct { int i; } mynum;
\&
\&    mynum* mynum_new(int i)
\&    {
\&        mynum* x = (mynum*)malloc(sizeof(mynum));
\&        x\->i = i;
\&        return x;
\&    }
\&
\&    void   mynum_destroy  (mynum *x)
\&                          { free((void*)x); }
\&
\&    int    mynum_val      (mynum *x)
\&                          { return x\->i; }
\&
\&    mynum* mynum_add      (mynum *x, mynum *y)
\&                          { return mynum_new(x\->i + y\->i); }
\&
\&    mynum* mynum_subtract (mynum *x, mynum *y)
\&                          { return mynum_new(x\->i \- y\->i); }
\&
\&    mynum* mynum_multiply (mynum *x, mynum *y)
\&                          { return mynum_new(x\->i * y\->i); }
\&
\&    mynum* mynum_divide   (mynum *x, mynum *y)
\&                          { return mynum_new(x\->i / y\->i); }
.Ve
.PP
The \f(CW\*(C`mynum\*(C'\fR struct holds the opaque handle data. The \f(CWmynum_new()\fR
function creates a numeric value and returns a handle to it. The other
functions then take such handles as arguments, including a destroy
function to free a handle\*(Aqs data.
.PP
The following XS code shows an example of how this library might be
wrapped and be made accessible from Perl via \f(CW\*(C`My::Num\*(C'\fR objects:
.PP
.Vb 1
\&    typedef mynum *My_\|_Num;
\&
\&    MODULE = My::Num PACKAGE = My::Num PREFIX = mynum_
\&
\&    PROTOTYPES: DISABLE
\&
\&    TYPEMAP: <<EOF
\&    My::Num T_PTROBJ
\&    EOF
\&
\&    My::Num
\&    mynum_new(class, int i)
\&        C_ARGS: i
\&
\&    void
\&    DESTROY(My::Num x)
\&        CODE:
\&            mynum_destroy(x);
\&
\&    int
\&    mynum_val(My::Num x)
\&
\&    My::Num
\&    mynum_add(My::Num x, My::Num y)
\&      ALIAS: subtract = 1
\&             multiply = 2
\&             divide   = 3
\&      CODE:
\&        switch (ix) {
\&            case 0: RETVAL = mynum_add(x, y);      break;
\&            case 1: RETVAL = mynum_subtract(x, y); break;
\&            case 2: RETVAL = mynum_multiply(x, y); break;
\&            case 3: RETVAL = mynum_divide(x, y);   break;
\&        }
\&      OUTPUT:
\&        RETVAL
.Ve
.PP
The XSUBs in this example are mostly declared with parameter and return
types of \f(CW\*(C`My::Num\*(C'\fR which, as explained in "Fully\-qualified type names
and Perl objects", is looked up as\-is in the typemap, but has \f(CW\*(C`s/:/_/g\*(C'\fR
applied to the type name to convert it to the \f(CW\*(C`My_\|_Num\*(C'\fR C type when used
in the declaration of the XSUB\*(Aqs auto variables.
.PP
Going through this code in order: while still in the \*(AqC\*(Aq half of the XS
file, we add a typedef which says that the \f(CW\*(C`My_\|_Num\*(C'\fR C type is equivalent
to a pointer to a handle from that arithmetic library.
.PP
Next, the \f(CW\*(C`MODULE\*(C'\fR line includes a \f(CW\*(C`mynum_\*(C'\fR prefix, which means that
the names of the XSUBs in the Perl namespace will be \f(CWMy::Num::new()\fR etc
rather than \f(CWMy::Num::mynum_new()\fR.
.PP
Then a \f(CW\*(C`TYPEMAP\*(C'\fR declaration is used to map the \f(CW\*(C`My::Num\*(C'\fR pseudo\-type to
the \f(CW\*(C`T_PTROBJ\*(C'\fR XS type.
.PP
Next comes the \f(CWnew()\fR class method. This will be called from perl as
\&\f(CW\*(C`My::Num\->new(99);\*(C'\fR for example. Its first parameter will be the
class name, which we don\*(Aqt use here, and the second parameter is the value
to initialise the object to. The XSUB autocalls the library \f(CWmynum_new()\fR
function with just the \f(CW\*(C`i\*(C'\fR value. This returns a handle, which the
\&\f(CW\*(C`T_PTROBJ\*(C'\fR \f(CW\*(C`OUTPUT\*(C'\fR map converts into a blessed scalar ref containing
the handle.
.PP
Next, the \f(CWDESTROY()\fR method is just a thin wrapper around
\&\f(CWmynum_destroy()\fR, while \f(CWval()\fR returns the integer value of the
object.
.PP
Finally, four binary functions are defined, sharing the same XSUB body via
aliases. As an alternative, the code for the main XSUB could simplified
using the INTERFACE keyword rather than
using aliasing:
.PP
.Vb 7
\&    My::Num
\&    arithmetic_interface(My::Num x, My::Num y)
\&        INTERFACE:
\&            mynum_add
\&            mynum_subtract
\&            mynum_multiply
\&            mynum_divide
.Ve
.PP
but note that \f(CW\*(C`INTERFACE\*(C'\fR only supports Perlish return types such as
\&\f(CW\*(C`My::Num\*(C'\fR from \fIxsubpp\fR 3.60 onwards.
.PP
This XS module might be accessed from Perl using code like this:
.PP
.Vb 1
\&    use My::Num;
\&
\&    my $i2  = My::Num\->new(2);
\&    my $i7  = My::Num\->new(7);
\&    my $i13 = My::Num\->new(13);
\&
\&    my $x = $i13\->add($i7)\->divide($i2);
\&    printf "val=%d\en", $x\->val();  # prints "val=10"
.Ve
.PP
See "The OVERLOAD: Keyword" for an example of how to extend this using
overloading so that the expression could be written more simply as
\&\f(CW\*(C`($i13 + $i7)/$i2\*(C'\fR.
.PP
Note that, as a very special case, the XS compiler translates the XS
typemap name using \f(CW\*(C`s/OBJ$/REF/\*(C'\fR when looking up INPUT typemap entries
for an XSUB named \f(CW\*(C`DESTROY\*(C'\fR. So for such subs, the \f(CW\*(C`T_PTRREF\*(C'\fR typemap
entry will be used instead. This typemap is similar to \f(CW\*(C`T_PTROBJ\*(C'\fR, except
that the class of the object isn\*(Aqt set or checked.
.SS "Using XS With C++"
.IX Subsection "Using XS With C++"
.Vb 1
\&    MODULE = Foo::Bar PACKAGE = Foo::Bar
\&
\&    # Class methods
\&
\&    X::Y*
\&    X::Y::new(int i)
\&
\&    static int
\&    X::Y::foo(int i)
\&
\&    # Object methods
\&
\&    int
\&    X::Y::bar(int i)
\&
\&    int
\&    X::Y::bar2(int i) const
\&
\&    void
\&    X::Y::DESTROY()
\&
\&    # C\-linkage function
\&
\&    extern "C" int
\&    baz(int i)
.Ve
.PP
XS provides limited support for generating C++ (as opposed to C) output
files. Any XSUB whose name includes \f(CW\*(C`::\*(C'\fR is treated as a C++ method. This
triggers two main changes in the way the XSUB\*(Aqs code is generated:
.IP \(bu 4
An implicit first argument is added. For class methods, this will be
called \f(CW\*(C`CLASS\*(C'\fR and will be of type \f(CW\*(C`char *\*(C'\fR. For object methods, it will
be called \f(CW\*(C`THIS\*(C'\fR and be of type \f(CW\*(C`X::Y *\*(C'\fR (where \f(CW\*(C`X::Y::\*(C'\fR is the prefix
of the XSUB\*(Aqs name). XSUBs are treated as class methods if their name is
\&\f(CW\*(C`new\*(C'\fR or their return type has the \f(CW\*(C`static\*(C'\fR prefix.
.IP \(bu 4
Any autocall will generate an appropriate C++ method call rather then a C
function call. In particular, based on the examples above:
.Sp
.Vb 4
\&    new:             RETVAL = new X::Y(i);
\&    static foo:      RETVAL = X::Y::foo(i);
\&    bar (and bar2):  RETVAL = THIS\->bar(i);
\&    DESTROY:         delete THIS;
.Ve
.IP \(bu 4
In addition, if the XSUB declaration has a trailing \f(CW\*(C`const\*(C'\fR, then the
type of \f(CW\*(C`THIS\*(C'\fR will be declared as \f(CW\*(C`const X::Y *\*(C'\fR.
.PP
This is mostly just syntactic sugar. The \f(CW\*(C`bar\*(C'\fR XSUB declaration above
could be written longhand as:
.PP
.Vb 6
\&    int
\&    bar(X::Y* THIS, int i)
\&        CODE:
\&            RETVAL = THIS\->foo(i);
\&        OUTPUT:
\&            RETVAL
.Ve
.PP
Note that the type of \f(CW\*(C`THIS\*(C'\fR (and, since \fIxsubpp\fR 3.55, \f(CW\*(C`CLASS\*(C'\fR) can be
overridden with a line in an \f(CW\*(C`INPUT\*(C'\fR section:
.PP
.Vb 3
\&    int
\&    X::Y::bar(int i)
\&        X::Y::Z *THIS
.Ve
.PP
Finally, a plain C XSUB declaration can be prefixed with \f(CW\*(C`extern "C"\*(C'\fR to
give that XSUB C linkage.
.PP
Some of the methods above might be called from Perl using code like this:
.PP
.Vb 5
\&    {
\&        my $obj = Foo::Bar\->new(1);
\&        $obj\->bar(2);
\&        # implicit $obj\->DESTROY();
\&    }
.Ve
.PP
This example uses \f(CW\*(C`Foo::Bar\*(C'\fR rather than \f(CW\*(C`X::Y\*(C'\fR to emphasise that the
name of the C++ class needn\*(Aqt follow the Perl package name.
.PP
The call to \f(CWnew()\fR will pass the string \f(CW"Foo::Bar"\fR as the first
argument, which can be used to allow multiple Perl classes to share the
same \f(CWnew()\fR method. In the simple worked example below, the package name
is hard\-coded and that parameter is unused. The \f(CWnew()\fR method is
expected to return a Perl object which in some way has a pointer to the
underlying C++ object embedded within it. This is similar to the
"T_PTROBJ and opaque handles" example of wrapping a C library which
uses a handle, although with a subtle difference, as explained below.
.PP
Calling \f(CWbar()\fR passes this Perl object as the first argument, which the
typemap will use to extract the C++ object pointer and assign to the
\&\f(CW\*(C`THIS\*(C'\fR auto variable.
.PP
\fIA complete C++ example\fR
.IX Subsection "A complete C++ example"
.PP
First, you need to tell MakeMaker or similar that the generated file
should be compiled using a C++ compiler. For basic experimentation you may
be able to get by with just adding these two lines to the
\&\f(CWWriteMakefile()\fR method call in \fIMakefile.PL\fR:
.PP
.Vb 2
\&    CC => \*(Aqc++\*(Aq,
\&    LD => \*(Aq$(CC)\*(Aq,
.Ve
.PP
but for portability in production use, you may want to use something like
ExtUtils::CppGuess to automatically generate the correct options for
ExtUtils::MakeMaker or Module::Build based on which C++ compiler
is available.
.PP
Then create a \f(CW\*(C`.xs\*(C'\fR file like this:
.PP
.Vb 1
\&    #define PERL_NO_GET_CONTEXT
\&
\&    #include "EXTERN.h"
\&    #include "perl.h"
\&    #include "XSUB.h"
\&    #include "ppport.h"
\&
\&    namespace Paint {
\&        class color {
\&            int c_R;
\&            int c_G;
\&            int c_B;
\&        public:
\&            color(int r, int g, int b) { c_R = r; c_G = g; c_B = b; }
\&            ~color()                   { printf("destructor called\en"); }
\&            int blue()                 { return c_B; }
\&            void set_blue(int b)       { c_B = b; };
\&            // and similar for red, green
\&        };
\&    }
\&
\&    typedef Paint::color Paint_\|_color;
\&
\&    MODULE = Foo::Bar PACKAGE = Foo::Bar
\&
\&    PROTOTYPES: DISABLE
\&
\&    TYPEMAP: <<EOF
\&    Paint::color * T_PKG_OBJ
\&
\&    INPUT
\&    T_PKG_OBJ
\&            SvGETMAGIC($arg);
\&            if (SvROK($arg) && sv_derived_from($arg, "$Package")) {
\&                IV tmp = SvIV((SV*)SvRV($arg));
\&                $var = INT2PTR($type,tmp);
\&            }
\&            else {
\&                    const char* refstr = SvROK($arg)
\&                        ? "" : SvOK($arg) ? "scalar " : "undef";
\&                Perl_croak_nocontext(
\&                    "%s: Expected %s to be of type %s; got %s%"
\&                    SVf " instead",
\&                            ${$ALIAS?\eq[GvNAME(CvGV(cv))]:\eqq["$pname"]},
\&                            "$var", "$Package",
\&                            refstr, $arg
\&                    );
\&            }
\&
\&    T_PKG_REF
\&            SvGETMAGIC($arg);
\&            if (SvROK($arg)) {
\&                IV tmp = SvIV((SV*)SvRV($arg));
\&                $var = INT2PTR($type,tmp);
\&            }
\&            else
\&                Perl_croak_nocontext("%s: %s is not a reference",
\&                            ${$ALIAS?\eq[GvNAME(CvGV(cv))]:\eqq["$pname"]},
\&                            "$var")
\&
\&    OUTPUT
\&    T_PKG_OBJ
\&            sv_setref_pv($arg, "$Package", (void*)$var);
\&
\&    EOF
\&
\&    Paint::color *
\&    Paint::color::new(int r, int g, int b)
\&
\&    int
\&    Paint::color::blue()
\&
\&    void
\&    Paint::color::set_blue(int b)
\&
\&    void
\&    Paint::color::DESTROY()
.Ve
.PP
In the C part of the XS file (or in this case, the C++ part), a trivial
example C++ class is defined. This would more typically be a pre\-existing
library with just the appropriate \f(CW\*(C`#include\*(C'\fR. The example includes a
namespace to make it clearer when something is a namespace, class name or
Perl package. The Perl package is called \f(CW\*(C`Foo::Bar\*(C'\fR rather than
\&\f(CW\*(C`Paint::color\*(C'\fR to again distinguish it. You could however call the Perl
package \f(CW\*(C`Paint::color\*(C'\fR if you desired.
.PP
A single typedef follows to allow for XS\-mangled class names, as explained
in "Fully\-qualified type names and Perl objects".
.PP
Then the \f(CW\*(C`MODULE\*(C'\fR line starts the XS part of the file.
.PP
Then there follows a full definition of a new typemap called \f(CW\*(C`T_PKG_OBJ\*(C'\fR.
This is actually a direct copy of the \f(CW\*(C`T_PTROBJ\*(C'\fR typemap found in the
system typemap file, except that all occurrences of \f(CW$ntype\fR have been
replaced with \f(CW$Package\fR. It serves the same basic purpose as
\&\f(CW\*(C`T_PTROBJ\*(C'\fR: embedding a pointer within a new blessed Perl object,
and later, retrieving that pointer from the object. The difference is in
terms of what package the object is blessed into. \f(CW\*(C`T_PTROBJ\*(C'\fR expects the
type name (\f(CW\*(C`Paint::color\*(C'\fR) to already be a pointer type, but with a C++
XSUB, the implicit \f(CW\*(C`THIS\*(C'\fR argument is automatically declared to be of
type \f(CW\*(C`Paint::color *\*(C'\fR (so \f(CW\*(C`Paint::color\*(C'\fR itself isn\*(Aqt necessarily a
pointer type). In addition, when the Perl and C++ class names differ we
want the object to be blessed using the Perl package name, not the C++
class name. In this example, the actual values of the two variables when
the typemap template is being evalled, are:
.PP
.Vb 2
\&        $ntype   = "Paint::colorPtr";
\&        $Package = "Foo::Bar";
.Ve
.PP
The typemap also includes an INPUT definition for \f(CW\*(C`T_PKG_REF\*(C'\fR, which is
an \fIexact\fR copy of \f(CW\*(C`T_PTRREF\*(C'\fR. This is needed because, as an
optimisation, the XS parser automatically renames an INPUT typemap using
\&\f(CW\*(C`s/OBJ$/REF/\*(C'\fR if the name of the XSUB is \f(CW\*(C`DESTROY\*(C'\fR, on the grounds that
it\*(Aqs not necessary to check that the object is the right class.
.PP
Finally the XS file includes a few XSUBs which are wrappers around the
class\*(Aqs methods.
.PP
This class might be used like this:
.PP
.Vb 1
\&    use Foo::Bar;
\&
\&    my $color = Foo::Bar\->new(0x10, 0x20, 0xff);
\&    printf "blue=%d\en", $color\->blue();   # prints 255
\&    $color\->set_blue(0x80);
\&    printf "blue=%d\en", $color\->blue();   # prints 128
.Ve
.SS "Safely Storing Static Data in XS"
.IX Subsection "Safely Storing Static Data in XS"
You should generally avoid declaring static variables and similar
\&\fImutable\fR data within an XS file. The Perl interpreter binary is commonly
configured to allow multiple interpreter structures, with a complete set
of interpreter state per interpreter struct. In this case, you usually
need your "static" data to be per\-interpreter rather than a single shared
per\-process value.
.PP
This becomes more important in the presence of multiple threads; either
via \f(CW\*(C`use threads\*(C'\fR or where the Perl interpreter is embedded within
another application (such as a web server) which may manage its own
threads and allocate interpreters to threads as it sees fit.
.PP
A macro framework is available to XS code to allow a single C struct to be
declared and safely accessed. Behind the scenes, the struct will be
allocated per interpreter or thread; on non\-threaded Perl interpreter
builds, the macros gracefully degrade to a single global instance. These
macros have \f(CW\*(C`MY_CXT\*(C'\fR ("my context") as part of their names.
.PP
It is therefore strongly recommended that these macros be used by all XS
modules that make use of static data.
.PP
When creating a new skeleton \fIFoo.xs\fR file, you can use the \f(CW\*(C`\-\-global\*(C'\fR
option of \fIh2xs\fR to also include a skeleton set of macros, e.g.
.PP
.Vb 1
\&    h2xs \-A \-\-global \-n Foo::Bar
.Ve
.PP
Below is a complete example module that makes use of the macros. It tracks
the names of up to three blind mice.
.PP
.Vb 5
\&    #define PERL_NO_GET_CONTEXT
\&    #include "EXTERN.h"
\&    #include "perl.h"
\&    #include "XSUB.h"
\&    #include "ppport.h"
\&
\&    #define MAX_NAME_LEN 100
\&
\&    /* Global Data */
\&
\&    #define MY_CXT_KEY "BlindMice::_guts" XS_VERSION
\&
\&    typedef struct {
\&        int count;
\&        char name[3][MAX_NAME_LEN+1];
\&    } my_cxt_t;
\&
\&    START_MY_CXT
\&
\&    MODULE = BlindMice  PACKAGE = BlindMice
\&
\&    PROTOTYPES: DISABLE
\&
\&    BOOT:
\&    {
\&        MY_CXT_INIT;
\&        MY_CXT.count = 0;
\&    }
\&
\&    int
\&    AddMouse(char *name)
\&      PREINIT:
\&        dMY_CXT;
\&      CODE:
\&        if (strlen(name) > MAX_NAME_LEN)
\&            croak("Mouse name too long\en");
\&
\&        if (MY_CXT.count >= 3) {
\&            warn("Already have 3 blind mice");
\&            RETVAL = 0;
\&        }
\&        else {
\&            RETVAL = ++MY_CXT.count;
\&            strcpy(MY_CXT.name[MY_CXT.count \- 1], name);
\&        }
\&      OUTPUT:
\&        RETVAL
\&
\&    char *
\&    get_mouse_name(int mouse_num)
\&      PREINIT:
\&        dMY_CXT;
\&      CODE:
\&        if (mouse_num < 1 || mouse_num > MY_CXT.count)
\&            croak("There are only %d blind mice.", MY_CXT.count);
\&        else
\&            RETVAL = MY_CXT.name[mouse_num \- 1];
\&      OUTPUT:
\&        RETVAL
\&
\&    void
\&    CLONE(...)
\&      CODE:
\&        MY_CXT_CLONE;
.Ve
.PP
The main points from this example are:
.IP \(bu 4
The \f(CW\*(C`my_cxt_t\*(C'\fR struct will hold all your "static" data.
.IP \(bu 4
The \f(CW\*(C`MY_CXT_KEY\*(C'\fR and \f(CW\*(C`START_MY_CXT\*(C'\fR are boilerplate to make the macro
system work. The former is a string which should be unique to your module.
.IP \(bu 4
The \f(CW\*(C`MY_CXT_INIT\*(C'\fR in the \f(CW\*(C`BOOT\*(C'\fR section allocates the struct when the
module is loaded. You can add further boot code which does any
initialisation you require (such as setting \f(CW\*(C`count\*(C'\fR). \f(CW\*(C`BOOT\*(C'\fR is called
at most once per interpreter, when code in that interpreter instance first
does \f(CW\*(C`use BlindMice\*(C'\fR.
.IP \(bu 4
Each XSUB includes a \f(CW\*(C`dMY_CXT\*(C'\fR declaration, which retrieves a pointer to
the struct associated with the current interpreter and saves it in a
hidden auto variable; \f(CW\*(C`MY_CXT\*(C'\fR allows you to access fields within this
structure.
.IP \(bu 4
\&\f(CW\*(C`MY_CXT_CLONE\*(C'\fR creates a byte\-for\-byte copy of the current struct. This
is called from the special \f(CW\*(C`CLONE\*(C'\fR XSUB, to ensure that each new thread
gets its own copy of the data which is otherwise shared by default.
.PP
\fIMY_CXT macros reference\fR
.IX Subsection "MY_CXT macros reference"
.IP MY_CXT_KEY 5
.IX Item "MY_CXT_KEY"
This macro is used to define a unique key to refer to the static data for
an XS module. The suggested naming scheme, as used by \fIh2xs\fR, is to use a
string that consists of a concatenation of the module name, the string
\&\f(CW\*(C`::_guts\*(C'\fR and the module version number:
.Sp
.Vb 1
\&    #define MY_CXT_KEY "MyModule::_guts" XS_VERSION
.Ve
.IP my_cxt_t 5
.IX Item "my_cxt_t"
The "static" values should be stored within a struct typedef which \fImust\fR
always be called \f(CW\*(C`my_cxt_t\*(C'\fR. The other \f(CW\*(C`*MY_CXT*\*(C'\fR macros assume the
existence of the \f(CW\*(C`my_cxt_t\*(C'\fR typedef name. For example:
.Sp
.Vb 4
\&    typedef struct {
\&        int some_value;
\&        int some_other_value;
\&    } my_cxt_t;
.Ve
.IP START_MY_CXT 5
.IX Item "START_MY_CXT"
This macro contains hidden boilerplate code. Always place the
\&\f(CW\*(C`START_MY_CXT\*(C'\fR macro directly after the declaration of \f(CW\*(C`my_cxt_t\*(C'\fR.
.IP MY_CXT_INIT 5
.IX Item "MY_CXT_INIT"
The \f(CW\*(C`MY_CXT_INIT\*(C'\fR macro initializes storage for the \f(CW\*(C`my_cxt_t\*(C'\fR struct.
.Sp
It must be called \fIexactly once\fR, typically in a BOOT: section. If you
are maintaining multiple interpreters, it should be called once in each
interpreter instance, except for interpreters cloned from existing ones.
(But see "MY_CXT_CLONE" below.)
.IP dMY_CXT 5
.IX Item "dMY_CXT"
Use the \f(CW\*(C`dMY_CXT\*(C'\fR macro (a declaration) at the start of all the XSUBs
(and other functions) that access \f(CW\*(C`MY_CXT\*(C'\fR.
.IP MY_CXT 5
.IX Item "MY_CXT"
Use the \f(CW\*(C`MY_CXT\*(C'\fR macro to access members of the \f(CW\*(C`my_cxt_t\*(C'\fR struct. For
example, if \f(CW\*(C`my_cxt_t\*(C'\fR is
.Sp
.Vb 3
\&    typedef struct {
\&        int index;
\&    } my_cxt_t;
.Ve
.Sp
then use this to access the \f(CW\*(C`index\*(C'\fR member:
.Sp
.Vb 2
\&    dMY_CXT;
\&    MY_CXT.index = 2;
.Ve
.IP aMY_CXT/pMY_CXT 5
.IX Item "aMY_CXT/pMY_CXT"
\&\f(CW\*(C`dMY_CXT\*(C'\fR may be quite expensive to calculate, and to avoid the overhead
of invoking it in each function it is possible to pass the declaration
onto other functions using the argument/parameter \f(CW\*(C`aMY_CXT\*(C'\fR/\f(CW\*(C`pMY_CXT\*(C'\fR
macros, e.g.:
.Sp
.Vb 5
\&    void sub1() {
\&        dMY_CXT;
\&        MY_CXT.index = 1;
\&        sub2(aMY_CXT);
\&    }
\&
\&    void sub2(pMY_CXT) {
\&        MY_CXT.index = 2;
\&    }
.Ve
.Sp
Analogously to \f(CW\*(C`pTHX\*(C'\fR, there are equivalent forms for when the macro is
the first or last in multiple arguments, where an underscore is expanded
to a comma where appropriate, i.e. \f(CW\*(C`_aMY_CXT\*(C'\fR, \f(CW\*(C`aMY_CXT_\*(C'\fR, \f(CW\*(C`_pMY_CXT\*(C'\fR
and \f(CW\*(C`pMY_CXT_\*(C'\fR. These allow for the possibility that those macros might
optimise away any actual argument without leaving a stray comma.
.IP MY_CXT_CLONE 5
.IX Item "MY_CXT_CLONE"
When a new interpreter is created as a copy of an existing one (e.g. via
\&\f(CW\*(C`threads\->create()\*(C'\fR), then by default, both interpreters share the
same physical my_cxt_t structure. Calling \f(CW\*(C`MY_CXT_CLONE\*(C'\fR (typically via
the package\*(Aqs \f(CWCLONE()\fR function), causes a byte\-for\-byte copy of the
structure to be taken (but not a deep copy) and any future \f(CW\*(C`dMY_CXT\*(C'\fR will
cause the copy to be accessed instead.
.Sp
This is typically used within the \f(CW\*(C`CLONE\*(C'\fR method which is called each
time an interpreter is copied (usually when creating a new thread). Other
code can be added to \f(CWCLONE()\fR to deep copy items within the structure.
.IP MY_CXT_INIT_INTERP(my_perl) 5
.IX Item "MY_CXT_INIT_INTERP(my_perl)"
.PD 0
.IP dMY_CXT_INTERP(my_perl) 5
.IX Item "dMY_CXT_INTERP(my_perl)"
.PD
These are variants of the \f(CW\*(C`MY_CXT_INIT\*(C'\fR and \f(CW\*(C`dMY_CXT\*(C'\fR macros which take
an explicit perl interpreter as an argument.
.PP
Note that these macros will only work together within the \fIsame\fR source
file; that is, a \f(CW\*(C`dMY_CXT\*(C'\fR in one source file will access a different
structure than a \f(CW\*(C`dMY_CXT\*(C'\fR in another source file.
.SH EXAMPLES
.IX Header "EXAMPLES"
Fairly complete examples of XS files can be found elsewhere in this
document:
.IP \(bu 4
"T_PTROBJ and opaque handles"
.IP \(bu 4
"A complete C++ example"
.IP \(bu 4
"Safely Storing Static Data in XS"
.PP
while "SYNOPSIS" contains an overview of an XS file and perlxstut
contains various worked examples.
.PP
You can of course look at existing XS distributions on CPAN for
inspiration, although bear in mind that many of these will have been
created before this document was rewritten in 2025, and so may not follow
current best practices.
.PP
Note that when wrapping a real library, you\*(Aqll often need to add a line
like this to the .xs file:
.PP
.Vb 1
\&    #include <foobar.h>
.Ve
.PP
and add entries like:
.PP
.Vb 1
\&    LIBS  => [\*(Aq\-lfoo\*(Aq, \*(Aq\-lbar\*(Aq],
.Ve
.PP
to \fIMakefile.PL\fR or similar. And don\*(Aqt forget to add test scripts under
t/.
.SH CAVEATS
.IX Header "CAVEATS"
.SS "Use of standard C library functions"
.IX Subsection "Use of standard C library functions"
Often, the Perl API contains functions which you should use \fIinstead\fR of
the standard C library ones. See perlclib.  Further, many libc
functions are problematic or need special care to use in conjunction
with perl.  perlclib has specifics, and hints.
.SS "Symbols defined by Perl that are visible to XS code"
.IX Subsection "Symbols defined by Perl that are visible to XS code"
By doing \f(CW\*(C`#include "perl.h"\*(C'\fR, you gain access to thousands of functions
and macros defined by the perl interpreter.  Some of these you
definitely want, such as elements designed to help your job be easier,
described in perlapi.  But some are inadvertently visible, and can be
considered to be polluting your namespace.  Starting in Perl v5.44,
more care is being taken to prevent adding new symbols like this, and we
plan to gradually clean up many of the existing ones.
.PP
In practice, this hasn\*(Aqt been much of a problem.  The universe of
possible names is vast, and you can just choose a synonym or a different
spelling if you find a clash with perl.
.PP
Additionally, functionality has been created that just never got
documented, and hence doesn\*(Aqt appear in perlapi.  If you find yourself
needing something that seems like somebody else could have needed it
too, try perusing the array \f(CW@unresolved_visibility_overrides\fR near the
top of \fIregen/embed.pl\fR for likely sounding candidates, and then
investigate.  If something turns out to be what you want, let us know by
reporting it via <https://github.com/Perl/perl5/issues>, or better yet
submit a patch.  By this time you are probably better equipped to know
what to say in the documentation than anyone else!
.PP
\&\f(CW@unresolved_visibility_overrides\fR lists all the macros that are
visible to your namespace that we haven\*(Aqt decided on what their
disposition should be.  You can look through this list also to find
names to avoid using yourself.
.PP
Perl does reserve for itself names that begin with \f(CW\*(C`PL_\*(C'\fR or have some
form of \f(CW\*(C`perl\*(C'\fR inside them (upper\- and/or lowercase, but delimited in
some way on both ends, such as \f(CW\*(C`/^Perl_/\*(C'\fR.  A pattern giving the exact
spellings is also near the top of the file \fIregen/embed.pl\fR.
.PP
Functions furnished by perl have long come in two forms, one which
begins with \f(CW\*(C`Perl_\*(C'\fR, and a short name that dispenses with that prefix.
If the short name clashes with one of your symbols, you can just
use the long name.  The downsides of doing that, though, are that the
short name hid from you the need (or not) of a thread context parameter,
and \fIppport.h\fR relies on the short name to furnish a fixed or
back\-compat version should that become necessary.  perlapi gives the
prototypes for the available forms of each API element.
.SS "Event loops and control flow"
.IX Subsection "Event loops and control flow"
Some modules have an event loop, waiting for user\-input.  It is highly
unlikely that two such modules would work adequately together in a
single Perl application.
.PP
In general, the perl interpreter views itself as the center of the
universe as far as the Perl program goes.  XS code is viewed as a
help\-mate, to accomplish things that perl doesn\*(Aqt do, or doesn\*(Aqt do fast
enough, but always subservient to perl.  The closer XS code adheres to
this model, the less likely conflicts will occur.
.SH "XS VERSION"
.IX Header "XS VERSION"
This document covers features supported by \fIxsubpp\fR 3.63.
.SH "AUTHOR DIAGNOSTICS"
.IX Header "AUTHOR DIAGNOSTICS"
As of \fIxsubpp\fR 3.49, a few parser warnings are disabled by default. While
developing you can set \f(CW$ENV{AUTHOR_WARNINGS}\fR to true in your
environment or in your Makefile.PL, or set
\&\f(CW$ExtUtils::ParseXS::AUTHOR_WARNINGS\fR to true via code, or pass \f(CW\*(C`author_warnings=>1\*(C'\fR into \fBprocess_file()\fR explicitly.  Currently this will
enable stricter alias checking but more warnings might be added in the
future. The kind of warnings this will enable are only helpful to the
author of the XS file, and the diagnostics produced will not include
installation specific details so they are only useful to the maintainer of
the XS code itself.
.SH AUTHOR
.IX Header "AUTHOR"
Originally written by Dean Roehrich <\fIroehrich@cray.com\fR>.
Completely rewritten in 2025.
.PP
Maintained since 1996 by The Perl Porters, <\fIperl5\-porters@perl.org\fR>.
