{
    "content": [
        {
            "type": "text",
            "text": "# PERLXS (man)\n\n## NAME\n\nperlxs - XS language reference manual\n\n## Sections\n\n- **NAME**\n- **DESCRIPTION** (42 subsections)\n- **EXAMPLES**\n- **CAVEATS**\n- **XS VERSION**\n- **AUTHOR**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "PERLXS",
        "section": "",
        "mode": "man",
        "summary": "perlxs - XS language reference manual",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [
            "File \"RPC.xs\": Interface to some ONC+ RPC bind library functions.",
            "#define PERLNOGETCONTEXT",
            "#include \"EXTERN.h\"",
            "#include \"perl.h\"",
            "#include \"XSUB.h\"",
            "/* Note: On glibc 2.13 and earlier, this needs be <rpc/rpc.h> */",
            "#include <tirpc/rpc.h>",
            "typedef struct netconfig Netconfig;",
            "MODULE = RPC  PACKAGE = RPC",
            "SV *",
            "rpcbgettime(host=\"localhost\")",
            "char *host",
            "PREINIT:",
            "timet  timep;",
            "CODE:",
            "ST(0) = svnewmortal();",
            "if( rpcbgettime( host, &timep ) )",
            "svsetnv( ST(0), (double)timep );",
            "Netconfig *",
            "getnetconfigent(netid=\"udp\")",
            "char *netid",
            "MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb",
            "void",
            "rpcbDESTROY(netconf)",
            "Netconfig *netconf",
            "CODE:",
            "printf(\"NetconfigPtr::DESTROY\\n\");",
            "free( netconf );",
            "File \"typemap\": Custom typemap for RPC.xs. (cf. perlxstypemap)",
            "TYPEMAP",
            "Netconfig *  TPTROBJ",
            "File \"RPC.pm\": Perl module for the RPC extension.",
            "package RPC;",
            "require Exporter;",
            "require DynaLoader;",
            "@ISA = qw(Exporter DynaLoader);",
            "@EXPORT = qw(rpcbgettime getnetconfigent);",
            "bootstrap RPC;",
            "1;",
            "File \"rpctest.pl\": Perl test program for the RPC extension.",
            "use RPC;",
            "$netconf = getnetconfigent();",
            "$a = rpcbgettime();",
            "print \"time = $a\\n\";",
            "print \"netconf = $netconf\\n\";",
            "$netconf = getnetconfigent(\"tcp\");",
            "$a = rpcbgettime(\"poplar\");",
            "print \"time = $a\\n\";",
            "print \"netconf = $netconf\\n\";",
            "In Makefile.PL add -ltirpc and -I/usr/include/tirpc."
        ],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 1,
                "subsections": [
                    {
                        "name": "Introduction",
                        "lines": 64
                    },
                    {
                        "name": "On The Road",
                        "lines": 69
                    },
                    {
                        "name": "The Anatomy of an XSUB",
                        "lines": 69
                    },
                    {
                        "name": "The Argument Stack",
                        "lines": 13
                    },
                    {
                        "name": "The RETVAL Variable",
                        "lines": 21
                    },
                    {
                        "name": "Returning SVs, AVs and HVs through RETVAL",
                        "lines": 58
                    },
                    {
                        "name": "The MODULE Keyword",
                        "lines": 13
                    },
                    {
                        "name": "The PACKAGE Keyword",
                        "lines": 22
                    },
                    {
                        "name": "The PREFIX Keyword",
                        "lines": 11
                    },
                    {
                        "name": "The OUTPUT: Keyword",
                        "lines": 62
                    },
                    {
                        "name": "The CODE: Keyword",
                        "lines": 21
                    },
                    {
                        "name": "The INIT: Keyword",
                        "lines": 43
                    },
                    {
                        "name": "The TYPEMAP: Keyword",
                        "lines": 14
                    },
                    {
                        "name": "Initializing Function Parameters",
                        "lines": 48
                    },
                    {
                        "name": "Default Parameter Values",
                        "lines": 26
                    },
                    {
                        "name": "The PREINIT: Keyword",
                        "lines": 93
                    },
                    {
                        "name": "The SCOPE: Keyword",
                        "lines": 14
                    },
                    {
                        "name": "The INPUT: Keyword",
                        "lines": 139
                    },
                    {
                        "name": "The \"length(NAME)\" Keyword",
                        "lines": 22
                    },
                    {
                        "name": "Variable-length Parameter Lists",
                        "lines": 52
                    },
                    {
                        "name": "The PPCODE: Keyword",
                        "lines": 58
                    },
                    {
                        "name": "Returning Undef And Empty Lists",
                        "lines": 89
                    },
                    {
                        "name": "The REQUIRE: Keyword",
                        "lines": 6
                    },
                    {
                        "name": "The CLEANUP: Keyword",
                        "lines": 5
                    },
                    {
                        "name": "The POSTCALL: Keyword",
                        "lines": 9
                    },
                    {
                        "name": "The BOOT: Keyword",
                        "lines": 13
                    },
                    {
                        "name": "The VERSIONCHECK: Keyword",
                        "lines": 18
                    },
                    {
                        "name": "The PROTOTYPES: Keyword",
                        "lines": 17
                    },
                    {
                        "name": "The PROTOTYPE: Keyword",
                        "lines": 27
                    },
                    {
                        "name": "The ALIAS: Keyword",
                        "lines": 21
                    },
                    {
                        "name": "The OVERLOAD: Keyword",
                        "lines": 33
                    },
                    {
                        "name": "The FALLBACK: Keyword",
                        "lines": 14
                    },
                    {
                        "name": "The INTERFACE: Keyword",
                        "lines": 67
                    },
                    {
                        "name": "The INCLUDE: Keyword",
                        "lines": 36
                    },
                    {
                        "name": "The CASE: Keyword",
                        "lines": 57
                    },
                    {
                        "name": "The & Unary Operator",
                        "lines": 31
                    },
                    {
                        "name": "Inserting POD, Comments and C Preprocessor Directives",
                        "lines": 32
                    },
                    {
                        "name": "Using XS With C++",
                        "lines": 99
                    },
                    {
                        "name": "Interface Strategy",
                        "lines": 47
                    },
                    {
                        "name": "Perl Objects And C Structures",
                        "lines": 56
                    },
                    {
                        "name": "Safely Storing Static Data in XS",
                        "lines": 155
                    },
                    {
                        "name": "Thread-aware system interfaces",
                        "lines": 18
                    }
                ]
            },
            {
                "name": "EXAMPLES",
                "lines": 70,
                "subsections": []
            },
            {
                "name": "CAVEATS",
                "lines": 156,
                "subsections": []
            },
            {
                "name": "XS VERSION",
                "lines": 3,
                "subsections": []
            },
            {
                "name": "AUTHOR",
                "lines": 7,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "perlxs - XS language reference manual\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "",
                "subsections": [
                    {
                        "name": "Introduction",
                        "content": "XS is an interface description file format used to create an extension interface between Perl\nand C code (or a C library) which one wishes to use with Perl.  The XS interface is combined\nwith the library to create a new library which can then be either dynamically loaded or\nstatically linked into perl.  The XS interface description is written in the XS language and\nis the core component of the Perl extension interface.\n\nBefore writing XS, read the \"CAVEATS\" section below.\n\nAn XSUB forms the basic unit of the XS interface.  After compilation by the xsubpp compiler,\neach XSUB amounts to a C function definition which will provide the glue between Perl calling\nconventions and C calling conventions.\n\nThe glue code pulls the arguments from the Perl stack, converts these Perl values to the\nformats expected by a C function, call this C function, transfers the return values of the C\nfunction back to Perl.  Return values here may be a conventional C return value or any C\nfunction arguments that may serve as output parameters.  These return values may be passed\nback to Perl either by putting them on the Perl stack, or by modifying the arguments supplied\nfrom the Perl side.\n\nThe above is a somewhat simplified view of what really happens.  Since Perl allows more\nflexible calling conventions than C, XSUBs may do much more in practice, such as checking\ninput parameters for validity, throwing exceptions (or returning undef/empty list) if the\nreturn value from the C function indicates failure, calling different C functions based on\nnumbers and types of the arguments, providing an object-oriented interface, etc.\n\nOf course, one could write such glue code directly in C.  However, this would be a tedious\ntask, especially if one needs to write glue for multiple C functions, and/or one is not\nfamiliar enough with the Perl stack discipline and other such arcana.  XS comes to the rescue\nhere: instead of writing this glue C code in long-hand, one can write a more concise short-\nhand description of what should be done by the glue, and let the XS compiler xsubpp handle\nthe rest.\n\nThe XS language allows one to describe the mapping between how the C routine is used, and how\nthe corresponding Perl routine is used.  It also allows creation of Perl routines which are\ndirectly translated to C code and which are not related to a pre-existing C function.  In\ncases when the C interface coincides with the Perl interface, the XSUB declaration is almost\nidentical to a declaration of a C function (in K&R style).  In such circumstances, there is\nanother tool called \"h2xs\" that is able to translate an entire C header file into a\ncorresponding XS file that will provide glue to the functions/macros described in the header\nfile.\n\nThe XS compiler is called xsubpp.  This compiler creates the constructs necessary to let an\nXSUB manipulate Perl values, and creates the glue necessary to let Perl call the XSUB.  The\ncompiler uses typemaps to determine how to map C function parameters and output values to\nPerl values and back.  The default typemap (which comes with Perl) handles many common C\ntypes.  A supplementary typemap may also be needed to handle any special structures and types\nfor the library being linked. For more information on typemaps, see perlxstypemap.\n\nA file in XS format starts with a C language section which goes until the first \"MODULE =\"\ndirective.  Other XS directives and XSUB definitions may follow this line.  The \"language\"\nused in this part of the file is usually referred to as the XS language.  xsubpp recognizes\nand skips POD (see perlpod) in both the C and XS language sections, which allows the XS file\nto contain embedded documentation.\n\nSee perlxstut for a tutorial on the whole extension creation process.\n\nNote: For some extensions, Dave Beazley's SWIG system may provide a significantly more\nconvenient mechanism for creating the extension glue code.  See <http://www.swig.org/> for\nmore information.\n\nFor simple bindings to C libraries as well as other machine code libraries, consider instead\nusing the much simpler libffi <http://sourceware.org/libffi/> interface via CPAN modules like\nFFI::Platypus or FFI::Raw.\n"
                    },
                    {
                        "name": "On The Road",
                        "content": "Many of the examples which follow will concentrate on creating an interface between Perl and\nthe ONC+ RPC bind library functions.  The rpcbgettime() function is used to demonstrate many\nfeatures of the XS language.  This function has two parameters; the first is an input\nparameter and the second is an output parameter.  The function also returns a status value.\n\nboolt rpcbgettime(const char *host, timet *timep);\n\nFrom C this function will be called with the following statements.\n\n#include <rpc/rpc.h>\nboolt status;\ntimet timep;\nstatus = rpcbgettime( \"localhost\", &timep );\n\nIf an XSUB is created to offer a direct translation between this function and Perl, then this\nXSUB will be used from Perl with the following code.  The $status and $timep variables will\ncontain the output of the function.\n\nuse RPC;\n$status = rpcbgettime( \"localhost\", $timep );\n\nThe following XS file shows an XS subroutine, or XSUB, which demonstrates one possible\ninterface to the rpcbgettime() function.  This XSUB represents a direct translation between\nC and Perl and so preserves the interface even from Perl.  This XSUB will be invoked from\nPerl with the usage shown above.  Note that the first three #include statements, for\n\"EXTERN.h\", \"perl.h\", and \"XSUB.h\", will always be present at the beginning of an XS file.\nThis approach and others will be expanded later in this document.  A #define for\n\"PERLNOGETCONTEXT\" should be present to fetch the interpreter context more efficiently,\nsee perlguts for details.\n\n#define PERLNOGETCONTEXT\n#include \"EXTERN.h\"\n#include \"perl.h\"\n#include \"XSUB.h\"\n#include <rpc/rpc.h>\n\nMODULE = RPC  PACKAGE = RPC\n\nboolt\nrpcbgettime(host,timep)\nchar *host\ntimet &timep\nOUTPUT:\ntimep\n\nAny extension to Perl, including those containing XSUBs, should have a Perl module to serve\nas the bootstrap which pulls the extension into Perl.  This module will export the\nextension's functions and variables to the Perl program and will cause the extension's XSUBs\nto be linked into Perl.  The following module will be used for most of the examples in this\ndocument and should be used from Perl with the \"use\" command as shown earlier.  Perl modules\nare explained in more detail later in this document.\n\npackage RPC;\n\nrequire Exporter;\nrequire DynaLoader;\n@ISA = qw(Exporter DynaLoader);\n@EXPORT = qw( rpcbgettime );\n\nbootstrap RPC;\n1;\n\nThroughout this document a variety of interfaces to the rpcbgettime() XSUB will be explored.\nThe XSUBs will take their parameters in different orders or will take different numbers of\nparameters.  In each case the XSUB is an abstraction between Perl and the real C\nrpcbgettime() function, and the XSUB must always ensure that the real rpcbgettime()\nfunction is called with the correct parameters.  This abstraction will allow the programmer\nto create a more Perl-like interface to the C function.\n"
                    },
                    {
                        "name": "The Anatomy of an XSUB",
                        "content": "The simplest XSUBs consist of 3 parts: a description of the return value, the name of the\nXSUB routine and the names of its arguments, and a description of types or formats of the\narguments.\n\nThe following XSUB allows a Perl program to access a C library function called sin().  The\nXSUB will imitate the C function which takes a single argument and returns a single value.\n\ndouble\nsin(x)\ndouble x\n\nOptionally, one can merge the description of types and the list of argument names, rewriting\nthis as\n\ndouble\nsin(double x)\n\nThis makes this XSUB look similar to an ANSI C declaration.  An optional semicolon is allowed\nafter the argument list, as in\n\ndouble\nsin(double x);\n\nParameters with C pointer types can have different semantic: C functions with similar\ndeclarations\n\nbool stringlooksasanumber(char *s);\nbool makecharuppercase(char *c);\n\nare used in absolutely incompatible manner.  Parameters to these functions could be described\nxsubpp like this:\n\nchar *  s\nchar    &c\n\nBoth these XS declarations correspond to the \"char*\" C type, but they have different\nsemantics, see \"The & Unary Operator\".\n\nIt is convenient to think that the indirection operator \"*\" should be considered as a part of\nthe type and the address operator \"&\" should be considered part of the variable.  See\nperlxstypemap for more info about handling qualifiers and unary operators in C types.\n\nThe function name and the return type must be placed on separate lines and should be flush\nleft-adjusted.\n\nINCORRECT                        CORRECT\n\ndouble sin(x)                    double\ndouble x                       sin(x)\ndouble x\n\nThe rest of the function description may be indented or left-adjusted. The following example\nshows a function with its body left-adjusted.  Most examples in this document will indent the\nbody for better readability.\n\nCORRECT\n\ndouble\nsin(x)\ndouble x\n\nMore complicated XSUBs may contain many other sections.  Each section of an XSUB starts with\nthe corresponding keyword, such as INIT: or CLEANUP:.  However, the first two lines of an\nXSUB always contain the same data: descriptions of the return type and the names of the\nfunction and its parameters.  Whatever immediately follows these is considered to be an\nINPUT: section unless explicitly marked with another keyword.  (See \"The INPUT: Keyword\".)\n\nAn XSUB section continues until another section-start keyword is found.\n"
                    },
                    {
                        "name": "The Argument Stack",
                        "content": "The Perl argument stack is used to store the values which are sent as parameters to the XSUB\nand to store the XSUB's return value(s).  In reality all Perl functions (including non-XSUB\nones) keep their values on this stack all the same time, each limited to its own range of\npositions on the stack.  In this document the first position on that stack which belongs to\nthe active function will be referred to as position 0 for that function.\n\nXSUBs refer to their stack arguments with the macro ST(x), where x refers to a position in\nthis XSUB's part of the stack.  Position 0 for that function would be known to the XSUB as\nST(0).  The XSUB's incoming parameters and outgoing return values always begin at ST(0).  For\nmany simple cases the xsubpp compiler will generate the code necessary to handle the argument\nstack by embedding code fragments found in the typemaps.  In more complex cases the\nprogrammer must supply the code.\n"
                    },
                    {
                        "name": "The RETVAL Variable",
                        "content": "The RETVAL variable is a special C variable that is declared automatically for you.  The C\ntype of RETVAL matches the return type of the C library function.  The xsubpp compiler will\ndeclare this variable in each XSUB with non-\"void\" return type.  By default the generated C\nfunction will use RETVAL to hold the return value of the C library function being called.  In\nsimple cases the value of RETVAL will be placed in ST(0) of the argument stack where it can\nbe received by Perl as the return value of the XSUB.\n\nIf the XSUB has a return type of \"void\" then the compiler will not declare a RETVAL variable\nfor that function.  When using a PPCODE: section no manipulation of the RETVAL variable is\nrequired, the section may use direct stack manipulation to place output values on the stack.\n\nIf PPCODE: directive is not used, \"void\" return value should be used only for subroutines\nwhich do not return a value, even if CODE: directive is used which sets ST(0) explicitly.\n\nOlder versions of this document recommended to use \"void\" return value in such cases. It was\ndiscovered that this could lead to segfaults in cases when XSUB was truly \"void\". This\npractice is now deprecated, and may be not supported at some future version. Use the return\nvalue \"SV *\" in such cases. (Currently \"xsubpp\" contains some heuristic code which tries to\ndisambiguate between \"truly-void\" and \"old-practice-declared-as-void\" functions. Hence your\ncode is at mercy of this heuristics unless you use \"SV *\" as return value.)\n"
                    },
                    {
                        "name": "Returning SVs, AVs and HVs through RETVAL",
                        "content": "When you're using RETVAL to return an \"SV *\", there's some magic going on behind the scenes\nthat should be mentioned. When you're manipulating the argument stack using the ST(x) macro,\nfor example, you usually have to pay special attention to reference counts. (For more about\nreference counts, see perlguts.) To make your life easier, the typemap file automatically\nmakes \"RETVAL\" mortal when you're returning an \"SV *\". Thus, the following two XSUBs are more\nor less equivalent:\n\nvoid\nalpha()\nPPCODE:\nST(0) = newSVpv(\"Hello World\",0);\nsv2mortal(ST(0));\nXSRETURN(1);\n\nSV *\nbeta()\nCODE:\nRETVAL = newSVpv(\"Hello World\",0);\nOUTPUT:\nRETVAL\n\nThis is quite useful as it usually improves readability. While this works fine for an \"SV *\",\nit's unfortunately not as easy to have \"AV *\" or \"HV *\" as a return value. You should be able\nto write:\n\nAV *\narray()\nCODE:\nRETVAL = newAV();\n/* do something with RETVAL */\nOUTPUT:\nRETVAL\n\nBut due to an unfixable bug (fixing it would break lots of existing CPAN modules) in the\ntypemap file, the reference count of the \"AV *\" is not properly decremented. Thus, the above\nXSUB would leak memory whenever it is being called. The same problem exists for \"HV *\", \"CV\n*\", and \"SVREF\" (which indicates a scalar reference, not a general \"SV *\").  In XS code on\nperls starting with perl 5.16, you can override the typemaps for any of these types with a\nversion that has proper handling of refcounts. In your \"TYPEMAP\" section, do\n\nAV*   TAVREFREFCOUNTFIXED\n\nto get the repaired variant. For backward compatibility with older versions of perl, you can\ninstead decrement the reference count manually when you're returning one of the\naforementioned types using \"sv2mortal\":\n\nAV *\narray()\nCODE:\nRETVAL = newAV();\nsv2mortal((SV*)RETVAL);\n/* do something with RETVAL */\nOUTPUT:\nRETVAL\n\nRemember that you don't have to do this for an \"SV *\". The reference documentation for all\ncore typemaps can be found in perlxstypemap.\n"
                    },
                    {
                        "name": "The MODULE Keyword",
                        "content": "The MODULE keyword is used to start the XS code and to specify the package of the functions\nwhich are being defined.  All text preceding the first MODULE keyword is considered C code\nand is passed through to the output with POD stripped, but otherwise untouched.  Every XS\nmodule will have a bootstrap function which is used to hook the XSUBs into Perl.  The package\nname of this bootstrap function will match the value of the last MODULE statement in the XS\nsource files.  The value of MODULE should always remain constant within the same XS file,\nthough this is not required.\n\nThe following example will start the XS code and will place all functions in a package named\nRPC.\n\nMODULE = RPC\n"
                    },
                    {
                        "name": "The PACKAGE Keyword",
                        "content": "When functions within an XS source file must be separated into packages the PACKAGE keyword\nshould be used.  This keyword is used with the MODULE keyword and must follow immediately\nafter it when used.\n\nMODULE = RPC  PACKAGE = RPC\n\n[ XS code in package RPC ]\n\nMODULE = RPC  PACKAGE = RPCB\n\n[ XS code in package RPCB ]\n\nMODULE = RPC  PACKAGE = RPC\n\n[ XS code in package RPC ]\n\nThe same package name can be used more than once, allowing for non-contiguous code. This is\nuseful if you have a stronger ordering principle than package names.\n\nAlthough this keyword is optional and in some cases provides redundant information it should\nalways be used.  This keyword will ensure that the XSUBs appear in the desired package.\n"
                    },
                    {
                        "name": "The PREFIX Keyword",
                        "content": "The PREFIX keyword designates prefixes which should be removed from the Perl function names.\nIf the C function is \"rpcbgettime()\" and the PREFIX value is \"rpcb\" then Perl will see this\nfunction as \"gettime()\".\n\nThis keyword should follow the PACKAGE keyword when used.  If PACKAGE is not used then PREFIX\nshould follow the MODULE keyword.\n\nMODULE = RPC  PREFIX = rpc\n\nMODULE = RPC  PACKAGE = RPCB  PREFIX = rpcb\n"
                    },
                    {
                        "name": "The OUTPUT: Keyword",
                        "content": "The OUTPUT: keyword indicates that certain function parameters should be updated (new values\nmade visible to Perl) when the XSUB terminates or that certain values should be returned to\nthe calling Perl function.  For simple functions which have no CODE: or PPCODE: section, such\nas the sin() function above, the RETVAL variable is automatically designated as an output\nvalue.  For more complex functions the xsubpp compiler will need help to determine which\nvariables are output variables.\n\nThis keyword will normally be used to complement the CODE: keyword.  The RETVAL variable is\nnot recognized as an output variable when the CODE: keyword is present.  The OUTPUT: keyword\nis used in this situation to tell the compiler that RETVAL really is an output variable.\n\nThe OUTPUT: keyword can also be used to indicate that function parameters are output\nvariables.  This may be necessary when a parameter has been modified within the function and\nthe programmer would like the update to be seen by Perl.\n\nboolt\nrpcbgettime(host,timep)\nchar *host\ntimet &timep\nOUTPUT:\ntimep\n\nThe OUTPUT: keyword will also allow an output parameter to be mapped to a matching piece of\ncode rather than to a typemap.\n\nboolt\nrpcbgettime(host,timep)\nchar *host\ntimet &timep\nOUTPUT:\ntimep svsetnv(ST(1), (double)timep);\n\nxsubpp emits an automatic \"SvSETMAGIC()\" for all parameters in the OUTPUT section of the\nXSUB, except RETVAL.  This is the usually desired behavior, as it takes care of properly\ninvoking 'set' magic on output parameters (needed for hash or array element parameters that\nmust be created if they didn't exist).  If for some reason, this behavior is not desired, the\nOUTPUT section may contain a \"SETMAGIC: DISABLE\" line to disable it for the remainder of the\nparameters in the OUTPUT section.  Likewise, \"SETMAGIC: ENABLE\" can be used to reenable it\nfor the remainder of the OUTPUT section.  See perlguts for more details about 'set' magic.\n\nThe NOOUTPUT Keyword\nThe NOOUTPUT can be placed as the first token of the XSUB.  This keyword indicates that\nwhile the C subroutine we provide an interface to has a non-\"void\" return type, the return\nvalue of this C subroutine should not be returned from the generated Perl subroutine.\n\nWith this keyword present \"The RETVAL Variable\" is created, and in the generated call to the\nsubroutine this variable is assigned to, but the value of this variable is not going to be\nused in the auto-generated code.\n\nThis keyword makes sense only if \"RETVAL\" is going to be accessed by the user-supplied code.\nIt is especially useful to make a function interface more Perl-like, especially when the C\nreturn value is just an error condition indicator.  For example,\n\nNOOUTPUT int\ndeletefile(char *name)\nPOSTCALL:\nif (RETVAL != 0)\ncroak(\"Error %d while deleting file '%s'\", RETVAL, name);\n\nHere the generated XS function returns nothing on success, and will die() with a meaningful\nerror message on error.\n"
                    },
                    {
                        "name": "The CODE: Keyword",
                        "content": "This keyword is used in more complicated XSUBs which require special handling for the C\nfunction.  The RETVAL variable is still declared, but it will not be returned unless it is\nspecified in the OUTPUT: section.\n\nThe following XSUB is for a C function which requires special handling of its parameters.\nThe Perl usage is given first.\n\n$status = rpcbgettime( \"localhost\", $timep );\n\nThe XSUB follows.\n\nboolt\nrpcbgettime(host,timep)\nchar *host\ntimet timep\nCODE:\nRETVAL = rpcbgettime( host, &timep );\nOUTPUT:\ntimep\nRETVAL\n"
                    },
                    {
                        "name": "The INIT: Keyword",
                        "content": "The INIT: keyword allows initialization to be inserted into the XSUB before the compiler\ngenerates the call to the C function.  Unlike the CODE: keyword above, this keyword does not\naffect the way the compiler handles RETVAL.\n\nboolt\nrpcbgettime(host,timep)\nchar *host\ntimet &timep\nINIT:\nprintf(\"# Host is %s\\n\", host );\nOUTPUT:\ntimep\n\nAnother use for the INIT: section is to check for preconditions before making a call to the C\nfunction:\n\nlong long\nlldiv(a,b)\nlong long a\nlong long b\nINIT:\nif (a == 0 && b == 0)\nXSRETURNUNDEF;\nif (b == 0)\ncroak(\"lldiv: cannot divide by 0\");\n\nThe NOINIT Keyword\nThe NOINIT keyword is used to indicate that a function parameter is being used only as an\noutput value.  The xsubpp compiler will normally generate code to read the values of all\nfunction parameters from the argument stack and assign them to C variables upon entry to the\nfunction.  NOINIT will tell the compiler that some parameters will be used for output rather\nthan for input and that they will be handled before the function terminates.\n\nThe following example shows a variation of the rpcbgettime() function.  This function uses\nthe timep variable only as an output variable and does not care about its initial contents.\n\nboolt\nrpcbgettime(host,timep)\nchar *host\ntimet &timep = NOINIT\nOUTPUT:\ntimep\n"
                    },
                    {
                        "name": "The TYPEMAP: Keyword",
                        "content": "Starting with Perl 5.16, you can embed typemaps into your XS code instead of or in addition\nto typemaps in a separate file.  Multiple such embedded typemaps will be processed in order\nof appearance in the XS code and like local typemap files take precedence over the default\ntypemap, the embedded typemaps may overwrite previous definitions of TYPEMAP, INPUT, and\nOUTPUT stanzas.  The syntax for embedded typemaps is\n\nTYPEMAP: <<HERE\n... your typemap code here ...\nHERE\n\nwhere the \"TYPEMAP\" keyword must appear in the first column of a new line.\n\nRefer to perlxstypemap for details on writing typemaps.\n"
                    },
                    {
                        "name": "Initializing Function Parameters",
                        "content": "C function parameters are normally initialized with their values from the argument stack\n(which in turn contains the parameters that were passed to the XSUB from Perl).  The typemaps\ncontain the code segments which are used to translate the Perl values to the C parameters.\nThe programmer, however, is allowed to override the typemaps and supply alternate (or\nadditional) initialization code.  Initialization code starts with the first \"=\", \";\" or \"+\"\non a line in the INPUT: section.  The only exception happens if this \";\" terminates the line,\nthen this \";\" is quietly ignored.\n\nThe following code demonstrates how to supply initialization code for function parameters.\nThe initialization code is eval'ed within double quotes by the compiler before it is added to\nthe output so anything which should be interpreted literally [mainly \"$\", \"@\", or \"\\\\\"] must\nbe protected with backslashes.  The variables $var, $arg, and $type can be used as in\ntypemaps.\n\nboolt\nrpcbgettime(host,timep)\nchar *host = (char *)SvPVbytenolen($arg);\ntimet &timep = 0;\nOUTPUT:\ntimep\n\nThis should not be used to supply default values for parameters.  One would normally use this\nwhen a function parameter must be processed by another library function before it can be\nused.  Default parameters are covered in the next section.\n\nIf the initialization begins with \"=\", then it is output in the declaration for the input\nvariable, replacing the initialization supplied by the typemap.  If the initialization begins\nwith \";\" or \"+\", then it is performed after all of the input variables have been declared.\nIn the \";\" case the initialization normally supplied by the typemap is not performed.  For\nthe \"+\" case, the declaration for the variable will include the initialization from the\ntypemap.  A global variable, %v, is available for the truly rare case where information from\none initialization is needed in another initialization.\n\nHere's a truly obscure example:\n\nboolt\nrpcbgettime(host,timep)\ntimet &timep; /* \\$v{timep}=@{[$v{timep}=$arg]} */\nchar *host + SvOK($v{timep}) ? SvPVbytenolen($arg) : NULL;\nOUTPUT:\ntimep\n\nThe construct \"\\$v{timep}=@{[$v{timep}=$arg]}\" used in the above example has a two-fold\npurpose: first, when this line is processed by xsubpp, the Perl snippet \"$v{timep}=$arg\" is\nevaluated.  Second, the text of the evaluated snippet is output into the generated C file\n(inside a C comment)!  During the processing of \"char *host\" line, $arg will evaluate to\nST(0), and $v{timep} will evaluate to ST(1).\n"
                    },
                    {
                        "name": "Default Parameter Values",
                        "content": "Default values for XSUB arguments can be specified by placing an assignment statement in the\nparameter list.  The default value may be a number, a string or the special string \"NOINIT\".\nDefaults should always be used on the right-most parameters only.\n\nTo allow the XSUB for rpcbgettime() to have a default host value the parameters to the XSUB\ncould be rearranged.  The XSUB will then call the real rpcbgettime() function with the\nparameters in the correct order.  This XSUB can be called from Perl with either of the\nfollowing statements:\n\n$status = rpcbgettime( $timep, $host );\n\n$status = rpcbgettime( $timep );\n\nThe XSUB will look like the code which follows.  A CODE: block is used to call the real\nrpcbgettime() function with the parameters in the correct order for that function.\n\nboolt\nrpcbgettime(timep,host=\"localhost\")\nchar *host\ntimet timep = NOINIT\nCODE:\nRETVAL = rpcbgettime( host, &timep );\nOUTPUT:\ntimep\nRETVAL\n"
                    },
                    {
                        "name": "The PREINIT: Keyword",
                        "content": "The PREINIT: keyword allows extra variables to be declared immediately before or after the\ndeclarations of the parameters from the INPUT: section are emitted.\n\nIf a variable is declared inside a CODE: section it will follow any typemap code that is\nemitted for the input parameters.  This may result in the declaration ending up after C code,\nwhich is C syntax error.  Similar errors may happen with an explicit \";\"-type or \"+\"-type\ninitialization of parameters is used (see \"Initializing Function Parameters\").  Declaring\nthese variables in an INIT: section will not help.\n\nIn such cases, to force an additional variable to be declared together with declarations of\nother variables, place the declaration into a PREINIT: section.  The PREINIT: keyword may be\nused one or more times within an XSUB.\n\nThe following examples are equivalent, but if the code is using complex typemaps then the\nfirst example is safer.\n\nboolt\nrpcbgettime(timep)\ntimet timep = NOINIT\nPREINIT:\nchar *host = \"localhost\";\nCODE:\nRETVAL = rpcbgettime( host, &timep );\nOUTPUT:\ntimep\nRETVAL\n\nFor this particular case an INIT: keyword would generate the same C code as the PREINIT:\nkeyword.  Another correct, but error-prone example:\n\nboolt\nrpcbgettime(timep)\ntimet timep = NOINIT\nCODE:\nchar *host = \"localhost\";\nRETVAL = rpcbgettime( host, &timep );\nOUTPUT:\ntimep\nRETVAL\n\nAnother way to declare \"host\" is to use a C block in the CODE: section:\n\nboolt\nrpcbgettime(timep)\ntimet timep = NOINIT\nCODE:\n{\nchar *host = \"localhost\";\nRETVAL = rpcbgettime( host, &timep );\n}\nOUTPUT:\ntimep\nRETVAL\n\nThe ability to put additional declarations before the typemap entries are processed is very\nhandy in the cases when typemap conversions manipulate some global state:\n\nMyObject\nmutate(o)\nPREINIT:\nMyState st = globalstate;\nINPUT:\nMyObject o;\nCLEANUP:\nresetto(globalstate, st);\n\nHere we suppose that conversion to \"MyObject\" in the INPUT: section and from MyObject when\nprocessing RETVAL will modify a global variable \"globalstate\".  After these conversions are\nperformed, we restore the old value of \"globalstate\" (to avoid memory leaks, for example).\n\nThere is another way to trade clarity for compactness: INPUT sections allow declaration of C\nvariables which do not appear in the parameter list of a subroutine.  Thus the above code for\nmutate() can be rewritten as\n\nMyObject\nmutate(o)\nMyState st = globalstate;\nMyObject o;\nCLEANUP:\nresetto(globalstate, st);\n\nand the code for rpcbgettime() can be rewritten as\n\nboolt\nrpcbgettime(timep)\ntimet timep = NOINIT\nchar *host = \"localhost\";\nCARGS:\nhost, &timep\nOUTPUT:\ntimep\nRETVAL\n"
                    },
                    {
                        "name": "The SCOPE: Keyword",
                        "content": "The SCOPE: keyword allows scoping to be enabled for a particular XSUB. If enabled, the XSUB\nwill invoke ENTER and LEAVE automatically.\n\nTo support potentially complex type mappings, if a typemap entry used by an XSUB contains a\ncomment like \"/*scope*/\" then scoping will be automatically enabled for that XSUB.\n\nTo enable scoping:\n\nSCOPE: ENABLE\n\nTo disable scoping:\n\nSCOPE: DISABLE\n"
                    },
                    {
                        "name": "The INPUT: Keyword",
                        "content": "The XSUB's parameters are usually evaluated immediately after entering the XSUB.  The INPUT:\nkeyword can be used to force those parameters to be evaluated a little later.  The INPUT:\nkeyword can be used multiple times within an XSUB and can be used to list one or more input\nvariables.  This keyword is used with the PREINIT: keyword.\n\nThe following example shows how the input parameter \"timep\" can be evaluated late, after a\nPREINIT.\n\nboolt\nrpcbgettime(host,timep)\nchar *host\nPREINIT:\ntimet tt;\nINPUT:\ntimet timep\nCODE:\nRETVAL = rpcbgettime( host, &tt );\ntimep = tt;\nOUTPUT:\ntimep\nRETVAL\n\nThe next example shows each input parameter evaluated late.\n\nboolt\nrpcbgettime(host,timep)\nPREINIT:\ntimet tt;\nINPUT:\nchar *host\nPREINIT:\nchar *h;\nINPUT:\ntimet timep\nCODE:\nh = host;\nRETVAL = rpcbgettime( h, &tt );\ntimep = tt;\nOUTPUT:\ntimep\nRETVAL\n\nSince INPUT sections allow declaration of C variables which do not appear in the parameter\nlist of a subroutine, this may be shortened to:\n\nboolt\nrpcbgettime(host,timep)\ntimet tt;\nchar *host;\nchar *h = host;\ntimet timep;\nCODE:\nRETVAL = rpcbgettime( h, &tt );\ntimep = tt;\nOUTPUT:\ntimep\nRETVAL\n\n(We used our knowledge that input conversion for \"char *\" is a \"simple\" one, thus \"host\" is\ninitialized on the declaration line, and our assignment \"h = host\" is not performed too\nearly.  Otherwise one would need to have the assignment \"h = host\" in a CODE: or INIT:\nsection.)\n\nThe IN/OUTLIST/INOUTLIST/OUT/INOUT Keywords\nIn the list of parameters for an XSUB, one can precede parameter names by the\n\"IN\"/\"OUTLIST\"/\"INOUTLIST\"/\"OUT\"/\"INOUT\" keywords.  \"IN\" keyword is the default, the other\nkeywords indicate how the Perl interface should differ from the C interface.\n\nParameters preceded by \"OUTLIST\"/\"INOUTLIST\"/\"OUT\"/\"INOUT\" keywords are considered to be\nused by the C subroutine via pointers.  \"OUTLIST\"/\"OUT\" keywords indicate that the C\nsubroutine does not inspect the memory pointed by this parameter, but will write through this\npointer to provide additional return values.\n\nParameters preceded by \"OUTLIST\" keyword do not appear in the usage signature of the\ngenerated Perl function.\n\nParameters preceded by \"INOUTLIST\"/\"INOUT\"/\"OUT\" do appear as parameters to the Perl\nfunction.  With the exception of \"OUT\"-parameters, these parameters are converted to the\ncorresponding C type, then pointers to these data are given as arguments to the C function.\nIt is expected that the C function will write through these pointers.\n\nThe return list of the generated Perl function consists of the C return value from the\nfunction (unless the XSUB is of \"void\" return type or \"The NOOUTPUT Keyword\" was used)\nfollowed by all the \"OUTLIST\" and \"INOUTLIST\" parameters (in the order of appearance).  On\nthe return from the XSUB the \"INOUT\"/\"OUT\" Perl parameter will be modified to have the\nvalues written by the C function.\n\nFor example, an XSUB\n\nvoid\ndaymonth(OUTLIST day, IN unixtime, OUTLIST month)\nint day\nint unixtime\nint month\n\nshould be used from Perl as\n\nmy ($day, $month) = daymonth(time);\n\nThe C signature of the corresponding function should be\n\nvoid daymonth(int *day, int unixtime, int *month);\n\nThe \"IN\"/\"OUTLIST\"/\"INOUTLIST\"/\"INOUT\"/\"OUT\" keywords can be mixed with ANSI-style\ndeclarations, as in\n\nvoid\ndaymonth(OUTLIST int day, int unixtime, OUTLIST int month)\n\n(here the optional \"IN\" keyword is omitted).\n\nThe \"INOUT\" parameters are identical with parameters introduced with \"The & Unary Operator\"\nand put into the \"OUTPUT:\" section (see \"The OUTPUT: Keyword\").  The \"INOUTLIST\" parameters\nare very similar, the only difference being that the value C function writes through the\npointer would not modify the Perl parameter, but is put in the output list.\n\nThe \"OUTLIST\"/\"OUT\" parameter differ from \"INOUTLIST\"/\"INOUT\" parameters only by the\ninitial value of the Perl parameter not being read (and not being given to the C function -\nwhich gets some garbage instead).  For example, the same C function as above can be\ninterfaced with as\n\nvoid daymonth(OUT int day, int unixtime, OUT int month);\n\nor\n\nvoid\ndaymonth(day, unixtime, month)\nint &day = NOINIT\nint  unixtime\nint &month = NOINIT\nOUTPUT:\nday\nmonth\n\nHowever, the generated Perl function is called in very C-ish style:\n\nmy ($day, $month);\ndaymonth($day, time, $month);\n"
                    },
                    {
                        "name": "The \"length(NAME)\" Keyword",
                        "content": "If one of the input arguments to the C function is the length of a string argument \"NAME\",\none can substitute the name of the length-argument by \"length(NAME)\" in the XSUB declaration.\nThis argument must be omitted when the generated Perl function is called.  E.g.,\n\nvoid\ndumpchars(char *s, short l)\n{\nshort n = 0;\nwhile (n < l) {\nprintf(\"s[%d] = \\\"\\\\%#03o\\\"\\n\", n, (int)s[n]);\nn++;\n}\n}\n\nMODULE = x            PACKAGE = x\n\nvoid dumpchars(char *s, short length(s))\n\nshould be called as \"dumpchars($string)\".\n\nThis directive is supported with ANSI-type function declarations only.\n"
                    },
                    {
                        "name": "Variable-length Parameter Lists",
                        "content": "XSUBs can have variable-length parameter lists by specifying an ellipsis \"(...)\" in the\nparameter list.  This use of the ellipsis is similar to that found in ANSI C.  The programmer\nis able to determine the number of arguments passed to the XSUB by examining the \"items\"\nvariable which the xsubpp compiler supplies for all XSUBs.  By using this mechanism one can\ncreate an XSUB which accepts a list of parameters of unknown length.\n\nThe host parameter for the rpcbgettime() XSUB can be optional so the ellipsis can be used to\nindicate that the XSUB will take a variable number of parameters.  Perl should be able to\ncall this XSUB with either of the following statements.\n\n$status = rpcbgettime( $timep, $host );\n\n$status = rpcbgettime( $timep );\n\nThe XS code, with ellipsis, follows.\n\nboolt\nrpcbgettime(timep, ...)\ntimet timep = NOINIT\nPREINIT:\nchar *host = \"localhost\";\nCODE:\nif( items > 1 )\nhost = (char *)SvPVbytenolen(ST(1));\nRETVAL = rpcbgettime( host, &timep );\nOUTPUT:\ntimep\nRETVAL\n\nThe CARGS: Keyword\nThe CARGS: keyword allows creating of XSUBS which have different calling sequence from Perl\nthan from C, without a need to write CODE: or PPCODE: section.  The contents of the CARGS:\nparagraph is put as the argument to the called C function without any change.\n\nFor example, suppose that a C function is declared as\n\nsymbolic nthderivative(int n, symbolic function, int flags);\n\nand that the default flags are kept in a global C variable \"defaultflags\".  Suppose that you\nwant to create an interface which is called as\n\n$secondderiv = $function->nthderivative(2);\n\nTo do this, declare the XSUB as\n\nsymbolic\nnthderivative(function, n)\nsymbolic        function\nint             n\nCARGS:\nn, function, defaultflags\n"
                    },
                    {
                        "name": "The PPCODE: Keyword",
                        "content": "The PPCODE: keyword is an alternate form of the CODE: keyword and is used to tell the xsubpp\ncompiler that the programmer is supplying the code to control the argument stack for the\nXSUBs return values.  Occasionally one will want an XSUB to return a list of values rather\nthan a single value.  In these cases one must use PPCODE: and then explicitly push the list\nof values on the stack.  The PPCODE: and CODE: keywords should not be used together within\nthe same XSUB.\n\nThe actual difference between PPCODE: and CODE: sections is in the initialization of \"SP\"\nmacro (which stands for the current Perl stack pointer), and in the handling of data on the\nstack when returning from an XSUB.  In CODE: sections SP preserves the value which was on\nentry to the XSUB: SP is on the function pointer (which follows the last parameter).  In\nPPCODE: sections SP is moved backward to the beginning of the parameter list, which allows\n\"PUSH*()\" macros to place output values in the place Perl expects them to be when the XSUB\nreturns back to Perl.\n\nThe generated trailer for a CODE: section ensures that the number of return values Perl will\nsee is either 0 or 1 (depending on the \"void\"ness of the return value of the C function, and\nheuristics mentioned in \"The RETVAL Variable\").  The trailer generated for a PPCODE: section\nis based on the number of return values and on the number of times \"SP\" was updated by\n\"[X]PUSH*()\" macros.\n\nNote that macros ST(i), \"XSTm*()\" and \"XSRETURN*()\" work equally well in CODE: sections and\nPPCODE: sections.\n\nThe following XSUB will call the C rpcbgettime() function and will return its two output\nvalues, timep and status, to Perl as a single list.\n\nvoid\nrpcbgettime(host)\nchar *host\nPREINIT:\ntimet  timep;\nboolt  status;\nPPCODE:\nstatus = rpcbgettime( host, &timep );\nEXTEND(SP, 2);\nPUSHs(sv2mortal(newSViv(status)));\nPUSHs(sv2mortal(newSViv(timep)));\n\nNotice that the programmer must supply the C code necessary to have the real rpcbgettime()\nfunction called and to have the return values properly placed on the argument stack.\n\nThe \"void\" return type for this function tells the xsubpp compiler that the RETVAL variable\nis not needed or used and that it should not be created.  In most scenarios the void return\ntype should be used with the PPCODE: directive.\n\nThe EXTEND() macro is used to make room on the argument stack for 2 return values.  The\nPPCODE: directive causes the xsubpp compiler to create a stack pointer available as \"SP\", and\nit is this pointer which is being used in the EXTEND() macro.  The values are then pushed\nonto the stack with the PUSHs() macro.\n\nNow the rpcbgettime() function can be used from Perl with the following statement.\n\n($status, $timep) = rpcbgettime(\"localhost\");\n\nWhen handling output parameters with a PPCODE section, be sure to handle 'set' magic\nproperly.  See perlguts for details about 'set' magic.\n"
                    },
                    {
                        "name": "Returning Undef And Empty Lists",
                        "content": "Occasionally the programmer will want to return simply \"undef\" or an empty list if a function\nfails rather than a separate status value.  The rpcbgettime() function offers just this\nsituation.  If the function succeeds we would like to have it return the time and if it fails\nwe would like to have undef returned.  In the following Perl code the value of $timep will\neither be undef or it will be a valid time.\n\n$timep = rpcbgettime( \"localhost\" );\n\nThe following XSUB uses the \"SV *\" return type as a mnemonic only, and uses a CODE: block to\nindicate to the compiler that the programmer has supplied all the necessary code.  The\nsvnewmortal() call will initialize the return value to undef, making that the default return\nvalue.\n\nSV *\nrpcbgettime(host)\nchar *  host\nPREINIT:\ntimet  timep;\nboolt x;\nCODE:\nST(0) = svnewmortal();\nif( rpcbgettime( host, &timep ) )\nsvsetnv( ST(0), (double)timep);\n\nThe next example demonstrates how one would place an explicit undef in the return value,\nshould the need arise.\n\nSV *\nrpcbgettime(host)\nchar *  host\nPREINIT:\ntimet  timep;\nboolt x;\nCODE:\nif( rpcbgettime( host, &timep ) ){\nST(0) = svnewmortal();\nsvsetnv( ST(0), (double)timep);\n}\nelse{\nST(0) = &PLsvundef;\n}\n\nTo return an empty list one must use a PPCODE: block and then not push return values on the\nstack.\n\nvoid\nrpcbgettime(host)\nchar *host\nPREINIT:\ntimet  timep;\nPPCODE:\nif( rpcbgettime( host, &timep ) )\nPUSHs(sv2mortal(newSViv(timep)));\nelse{\n/* Nothing pushed on stack, so an empty\n* list is implicitly returned. */\n}\n\nSome people may be inclined to include an explicit \"return\" in the above XSUB, rather than\nletting control fall through to the end.  In those situations \"XSRETURNEMPTY\" should be\nused, instead.  This will ensure that the XSUB stack is properly adjusted.  Consult perlapi\nfor other \"XSRETURN\" macros.\n\nSince \"XSRETURN*\" macros can be used with CODE blocks as well, one can rewrite this example\nas:\n\nint\nrpcbgettime(host)\nchar *host\nPREINIT:\ntimet  timep;\nCODE:\nRETVAL = rpcbgettime( host, &timep );\nif (RETVAL == 0)\nXSRETURNUNDEF;\nOUTPUT:\nRETVAL\n\nIn fact, one can put this check into a POSTCALL: section as well.  Together with PREINIT:\nsimplifications, this leads to:\n\nint\nrpcbgettime(host)\nchar *host\ntimet  timep;\nPOSTCALL:\nif (RETVAL == 0)\nXSRETURNUNDEF;\n"
                    },
                    {
                        "name": "The REQUIRE: Keyword",
                        "content": "The REQUIRE: keyword is used to indicate the minimum version of the xsubpp compiler needed to\ncompile the XS module.  An XS module which contains the following statement will compile with\nonly xsubpp version 1.922 or greater:\n\nREQUIRE: 1.922\n"
                    },
                    {
                        "name": "The CLEANUP: Keyword",
                        "content": "This keyword can be used when an XSUB requires special cleanup procedures before it\nterminates.  When the CLEANUP: keyword is used it must follow any CODE:, or OUTPUT: blocks\nwhich are present in the XSUB.  The code specified for the cleanup block will be added as the\nlast statements in the XSUB.\n"
                    },
                    {
                        "name": "The POSTCALL: Keyword",
                        "content": "This keyword can be used when an XSUB requires special procedures executed after the C\nsubroutine call is performed.  When the POSTCALL: keyword is used it must precede OUTPUT: and\nCLEANUP: blocks which are present in the XSUB.\n\nSee examples in \"The NOOUTPUT Keyword\" and \"Returning Undef And Empty Lists\".\n\nThe POSTCALL: block does not make a lot of sense when the C subroutine call is supplied by\nuser by providing either CODE: or PPCODE: section.\n"
                    },
                    {
                        "name": "The BOOT: Keyword",
                        "content": "The BOOT: keyword is used to add code to the extension's bootstrap function.  The bootstrap\nfunction is generated by the xsubpp compiler and normally holds the statements necessary to\nregister any XSUBs with Perl.  With the BOOT: keyword the programmer can tell the compiler to\nadd extra statements to the bootstrap function.\n\nThis keyword may be used any time after the first MODULE keyword and should appear on a line\nby itself.  The first blank line after the keyword will terminate the code block.\n\nBOOT:\n# The following message will be printed when the\n# bootstrap function executes.\nprintf(\"Hello from the bootstrap!\\n\");\n"
                    },
                    {
                        "name": "The VERSIONCHECK: Keyword",
                        "content": "The VERSIONCHECK: keyword corresponds to xsubpp's \"-versioncheck\" and \"-noversioncheck\"\noptions.  This keyword overrides the command line options.  Version checking is enabled by\ndefault.  When version checking is enabled the XS module will attempt to verify that its\nversion matches the version of the PM module.\n\nTo enable version checking:\n\nVERSIONCHECK: ENABLE\n\nTo disable version checking:\n\nVERSIONCHECK: DISABLE\n\nNote that if the version of the PM module is an NV (a floating point number), it will be\nstringified with a possible loss of precision (currently chopping to nine decimal places) so\nthat it may not match the version of the XS module anymore. Quoting the $VERSION declaration\nto make it a string is recommended if long version numbers are used.\n"
                    },
                    {
                        "name": "The PROTOTYPES: Keyword",
                        "content": "The PROTOTYPES: keyword corresponds to xsubpp's \"-prototypes\" and \"-noprototypes\" options.\nThis keyword overrides the command line options.  Prototypes are disabled by default.  When\nprototypes are enabled, XSUBs will be given Perl prototypes.  This keyword may be used\nmultiple times in an XS module to enable and disable prototypes for different parts of the\nmodule.  Note that xsubpp will nag you if you don't explicitly enable or disable prototypes,\nwith:\n\nPlease specify prototyping behavior for Foo.xs (see perlxs manual)\n\nTo enable prototypes:\n\nPROTOTYPES: ENABLE\n\nTo disable prototypes:\n\nPROTOTYPES: DISABLE\n"
                    },
                    {
                        "name": "The PROTOTYPE: Keyword",
                        "content": "This keyword is similar to the PROTOTYPES: keyword above but can be used to force xsubpp to\nuse a specific prototype for the XSUB.  This keyword overrides all other prototype options\nand keywords but affects only the current XSUB.  Consult \"Prototypes\" in perlsub for\ninformation about Perl prototypes.\n\nboolt\nrpcbgettime(timep, ...)\ntimet timep = NOINIT\nPROTOTYPE: $;$\nPREINIT:\nchar *host = \"localhost\";\nCODE:\nif( items > 1 )\nhost = (char *)SvPVbytenolen(ST(1));\nRETVAL = rpcbgettime( host, &timep );\nOUTPUT:\ntimep\nRETVAL\n\nIf the prototypes are enabled, you can disable it locally for a given XSUB as in the\nfollowing example:\n\nvoid\nrpcbgettimenoproto()\nPROTOTYPE: DISABLE\n...\n"
                    },
                    {
                        "name": "The ALIAS: Keyword",
                        "content": "The ALIAS: keyword allows an XSUB to have two or more unique Perl names and to know which of\nthose names was used when it was invoked.  The Perl names may be fully-qualified with package\nnames.  Each alias is given an index.  The compiler will setup a variable called \"ix\" which\ncontain the index of the alias which was used.  When the XSUB is called with its declared\nname \"ix\" will be 0.\n\nThe following example will create aliases \"FOO::gettime()\" and \"BAR::getit()\" for this\nfunction.\n\nboolt\nrpcbgettime(host,timep)\nchar *host\ntimet &timep\nALIAS:\nFOO::gettime = 1\nBAR::getit = 2\nINIT:\nprintf(\"# ix = %d\\n\", ix );\nOUTPUT:\ntimep\n"
                    },
                    {
                        "name": "The OVERLOAD: Keyword",
                        "content": "Instead of writing an overloaded interface using pure Perl, you can also use the OVERLOAD\nkeyword to define additional Perl names for your functions (like the ALIAS: keyword above).\nHowever, the overloaded functions must be defined in such a way as to accept the number of\nparameters supplied by perl's overload system.  For most overload methods, it will be three\nparameters; for the \"nomethod\" function it will be four.  However, the bitwise operators \"&\",\n\"|\", \"^\", and \"~\" may be called with three or five arguments (see overload).\n\nIf any function has the OVERLOAD: keyword, several additional lines will be defined in the c\nfile generated by xsubpp in order to register with the overload magic.\n\nSince blessed objects are actually stored as RV's, it is useful to use the typemap features\nto preprocess parameters and extract the actual SV stored within the blessed RV.  See the\nsample for TPTROBJSPECIAL below.\n\nTo use the OVERLOAD: keyword, create an XS function which takes three input parameters (or\nuse the C-style '...' definition) like this:\n\nSV *\ncmp (lobj, robj, swap)\nMyModuleobj    lobj\nMyModuleobj    robj\nIV               swap\nOVERLOAD: cmp <=>\n{ /* function defined here */}\n\nIn this case, the function will overload both of the three way comparison operators.  For all\noverload operations using non-alpha characters, you must type the parameter without quoting,\nseparating multiple overloads with whitespace.  Note that \"\" (the stringify overload) should\nbe entered as \\\"\\\" (i.e. escaped).\n\nSince, as mentioned above, bitwise operators may take extra arguments, you may want to use\nsomething like \"(lobj, robj, swap, ...)\" (with literal \"...\") as your parameter list.\n"
                    },
                    {
                        "name": "The FALLBACK: Keyword",
                        "content": "In addition to the OVERLOAD keyword, if you need to control how Perl autogenerates missing\noverloaded operators, you can set the FALLBACK keyword in the module header section, like\nthis:\n\nMODULE = RPC  PACKAGE = RPC\n\nFALLBACK: TRUE\n...\n\nwhere FALLBACK can take any of the three values TRUE, FALSE, or UNDEF.  If you do not set any\nFALLBACK value when using OVERLOAD, it defaults to UNDEF.  FALLBACK is not used except when\none or more functions using OVERLOAD have been defined.  Please see \"fallback\" in overload\nfor more details.\n"
                    },
                    {
                        "name": "The INTERFACE: Keyword",
                        "content": "This keyword declares the current XSUB as a keeper of the given calling signature.  If some\ntext follows this keyword, it is considered as a list of functions which have this signature,\nand should be attached to the current XSUB.\n\nFor example, if you have 4 C functions multiply(), divide(), add(), subtract() all having the\nsignature:\n\nsymbolic f(symbolic, symbolic);\n\nyou can make them all to use the same XSUB using this:\n\nsymbolic\ninterfacesss(arg1, arg2)\nsymbolic        arg1\nsymbolic        arg2\nINTERFACE:\nmultiply divide\nadd subtract\n\n(This is the complete XSUB code for 4 Perl functions!)  Four generated Perl function share\nnames with corresponding C functions.\n\nThe advantage of this approach comparing to ALIAS: keyword is that there is no need to code a\nswitch statement, each Perl function (which shares the same XSUB) knows which C function it\nshould call.  Additionally, one can attach an extra function remainder() at runtime by using\n\nCV *mycv = newXSproto(\"Symbolic::remainder\",\nXSSymbolicinterfacesss, FILE, \"$$\");\nXSINTERFACEFUNCSET(mycv, remainder);\n\nsay, from another XSUB.  (This example supposes that there was no INTERFACEMACRO: section,\notherwise one needs to use something else instead of \"XSINTERFACEFUNCSET\", see the next\nsection.)\n\nThe INTERFACEMACRO: Keyword\nThis keyword allows one to define an INTERFACE using a different way to extract a function\npointer from an XSUB.  The text which follows this keyword should give the name of macros\nwhich would extract/set a function pointer.  The extractor macro is given return type, \"CV*\",\nand \"XSANY.anydptr\" for this \"CV*\".  The setter macro is given cv, and the function pointer.\n\nThe default value is \"XSINTERFACEFUNC\" and \"XSINTERFACEFUNCSET\".  An INTERFACE keyword\nwith an empty list of functions can be omitted if INTERFACEMACRO keyword is used.\n\nSuppose that in the previous example functions pointers for multiply(), divide(), add(),\nsubtract() are kept in a global C array \"fp[]\" with offsets being \"multiplyoff\",\n\"divideoff\", \"addoff\", \"subtractoff\".  Then one can use\n\n#define XSINTERFACEFUNCBYOFFSET(ret,cv,f) \\\n((XSINTERFACECVTANON(ret))fp[CvXSUBANY(cv).anyi32])\n#define XSINTERFACEFUNCBYOFFSETset(cv,f) \\\nCvXSUBANY(cv).anyi32 = CAT2( f, off )\n\nin C section,\n\nsymbolic\ninterfacesss(arg1, arg2)\nsymbolic        arg1\nsymbolic        arg2\nINTERFACEMACRO:\nXSINTERFACEFUNCBYOFFSET\nXSINTERFACEFUNCBYOFFSETset\nINTERFACE:\nmultiply divide\nadd subtract\n\nin XSUB section.\n"
                    },
                    {
                        "name": "The INCLUDE: Keyword",
                        "content": "This keyword can be used to pull other files into the XS module.  The other files may have XS\ncode.  INCLUDE: can also be used to run a command to generate the XS code to be pulled into\nthe module.\n\nThe file Rpcb1.xsh contains our \"rpcbgettime()\" function:\n\nboolt\nrpcbgettime(host,timep)\nchar *host\ntimet &timep\nOUTPUT:\ntimep\n\nThe XS module can use INCLUDE: to pull that file into it.\n\nINCLUDE: Rpcb1.xsh\n\nIf the parameters to the INCLUDE: keyword are followed by a pipe (\"|\") then the compiler will\ninterpret the parameters as a command. This feature is mildly deprecated in favour of the\n\"INCLUDECOMMAND:\" directive, as documented below.\n\nINCLUDE: cat Rpcb1.xsh |\n\nDo not use this to run perl: \"INCLUDE: perl |\" will run the perl that happens to be the first\nin your path and not necessarily the same perl that is used to run \"xsubpp\". See \"The\nINCLUDECOMMAND: Keyword\".\n\nThe INCLUDECOMMAND: Keyword\nRuns the supplied command and includes its output into the current XS document.\n\"INCLUDECOMMAND\" assigns special meaning to the $^X token in that it runs the same perl\ninterpreter that is running \"xsubpp\":\n\nINCLUDECOMMAND: cat Rpcb1.xsh\n\nINCLUDECOMMAND: $^X -e ...\n"
                    },
                    {
                        "name": "The CASE: Keyword",
                        "content": "The CASE: keyword allows an XSUB to have multiple distinct parts with each part acting as a\nvirtual XSUB.  CASE: is greedy and if it is used then all other XS keywords must be contained\nwithin a CASE:.  This means nothing may precede the first CASE: in the XSUB and anything\nfollowing the last CASE: is included in that case.\n\nA CASE: might switch via a parameter of the XSUB, via the \"ix\" ALIAS: variable (see \"The\nALIAS: Keyword\"), or maybe via the \"items\" variable (see \"Variable-length Parameter Lists\").\nThe last CASE: becomes the default case if it is not associated with a conditional.  The\nfollowing example shows CASE switched via \"ix\" with a function \"rpcbgettime()\" having an\nalias \"xgettime()\".  When the function is called as \"rpcbgettime()\" its parameters are the\nusual \"(char *host, timet *timep)\", but when the function is called as \"xgettime()\" its\nparameters are reversed, \"(timet *timep, char *host)\".\n\nlong\nrpcbgettime(a,b)\nCASE: ix == 1\nALIAS:\nxgettime = 1\nINPUT:\n# 'a' is timep, 'b' is host\nchar *b\ntimet a = NOINIT\nCODE:\nRETVAL = rpcbgettime( b, &a );\nOUTPUT:\na\nRETVAL\nCASE:\n# 'a' is host, 'b' is timep\nchar *a\ntimet &b = NOINIT\nOUTPUT:\nb\nRETVAL\n\nThat function can be called with either of the following statements.  Note the different\nargument lists.\n\n$status = rpcbgettime( $host, $timep );\n\n$status = xgettime( $timep, $host );\n\nThe EXPORTXSUBSYMBOLS: Keyword\nThe EXPORTXSUBSYMBOLS: keyword is likely something you will never need.  In perl versions\nearlier than 5.16.0, this keyword does nothing. Starting with 5.16, XSUB symbols are no\nlonger exported by default. That is, they are \"static\" functions. If you include\n\nEXPORTXSUBSYMBOLS: ENABLE\n\nin your XS code, the XSUBs following this line will not be declared \"static\".  You can later\ndisable this with\n\nEXPORTXSUBSYMBOLS: DISABLE\n\nwhich, again, is the default that you should probably never change.  You cannot use this\nkeyword on versions of perl before 5.16 to make XSUBs \"static\".\n"
                    },
                    {
                        "name": "The & Unary Operator",
                        "content": "The \"&\" unary operator in the INPUT: section is used to tell xsubpp that it should convert a\nPerl value to/from C using the C type to the left of \"&\", but provide a pointer to this value\nwhen the C function is called.\n\nThis is useful to avoid a CODE: block for a C function which takes a parameter by reference.\nTypically, the parameter should be not a pointer type (an \"int\" or \"long\" but not an \"int*\"\nor \"long*\").\n\nThe following XSUB will generate incorrect C code.  The xsubpp compiler will turn this into\ncode which calls \"rpcbgettime()\" with parameters \"(char *host, timet timep)\", but the real\n\"rpcbgettime()\" wants the \"timep\" parameter to be of type \"timet*\" rather than \"timet\".\n\nboolt\nrpcbgettime(host,timep)\nchar *host\ntimet timep\nOUTPUT:\ntimep\n\nThat problem is corrected by using the \"&\" operator.  The xsubpp compiler will now turn this\ninto code which calls \"rpcbgettime()\" correctly with parameters \"(char *host, timet\n*timep)\".  It does this by carrying the \"&\" through, so the function call looks like\n\"rpcbgettime(host, &timep)\".\n\nboolt\nrpcbgettime(host,timep)\nchar *host\ntimet &timep\nOUTPUT:\ntimep\n"
                    },
                    {
                        "name": "Inserting POD, Comments and C Preprocessor Directives",
                        "content": "C preprocessor directives are allowed within BOOT:, PREINIT: INIT:, CODE:, PPCODE:,\nPOSTCALL:, and CLEANUP: blocks, as well as outside the functions.  Comments are allowed\nanywhere after the MODULE keyword.  The compiler will pass the preprocessor directives\nthrough untouched and will remove the commented lines. POD documentation is allowed at any\npoint, both in the C and XS language sections. POD must be terminated with a \"=cut\" command;\n\"xsubpp\" will exit with an error if it does not. It is very unlikely that human generated C\ncode will be mistaken for POD, as most indenting styles result in whitespace in front of any\nline starting with \"=\". Machine generated XS files may fall into this trap unless care is\ntaken to ensure that a space breaks the sequence \"\\n=\".\n\nComments can be added to XSUBs by placing a \"#\" as the first non-whitespace of a line.  Care\nshould be taken to avoid making the comment look like a C preprocessor directive, lest it be\ninterpreted as such.  The simplest way to prevent this is to put whitespace in front of the\n\"#\".\n\nIf you use preprocessor directives to choose one of two versions of a function, use\n\n#if ... version1\n#else /* ... version2  */\n#endif\n\nand not\n\n#if ... version1\n#endif\n#if ... version2\n#endif\n\nbecause otherwise xsubpp will believe that you made a duplicate definition of the function.\nAlso, put a blank line before the #else/#endif so it will not be seen as part of the function\nbody.\n"
                    },
                    {
                        "name": "Using XS With C++",
                        "content": "If an XSUB name contains \"::\", it is considered to be a C++ method.  The generated Perl\nfunction will assume that its first argument is an object pointer.  The object pointer will\nbe stored in a variable called THIS.  The object should have been created by C++ with the\nnew() function and should be blessed by Perl with the svsetrefpv() macro.  The blessing of\nthe object by Perl can be handled by a typemap.  An example typemap is shown at the end of\nthis section.\n\nIf the return type of the XSUB includes \"static\", the method is considered to be a static\nmethod.  It will call the C++ function using the class::method() syntax.  If the method is\nnot static the function will be called using the THIS->method() syntax.\n\nThe next examples will use the following C++ class.\n\nclass color {\npublic:\ncolor();\n~color();\nint blue();\nvoid setblue( int );\n\nprivate:\nint cblue;\n};\n\nThe XSUBs for the blue() and setblue() methods are defined with the class name but the\nparameter for the object (THIS, or \"self\") is implicit and is not listed.\n\nint\ncolor::blue()\n\nvoid\ncolor::setblue( val )\nint val\n\nBoth Perl functions will expect an object as the first parameter.  In the generated C++ code\nthe object is called \"THIS\", and the method call will be performed on this object.  So in the\nC++ code the blue() and setblue() methods will be called as this:\n\nRETVAL = THIS->blue();\n\nTHIS->setblue( val );\n\nYou could also write a single get/set method using an optional argument:\n\nint\ncolor::blue( val = NOINIT )\nint val\nPROTOTYPE $;$\nCODE:\nif (items > 1)\nTHIS->setblue( val );\nRETVAL = THIS->blue();\nOUTPUT:\nRETVAL\n\nIf the function's name is DESTROY then the C++ \"delete\" function will be called and \"THIS\"\nwill be given as its parameter.  The generated C++ code for\n\nvoid\ncolor::DESTROY()\n\nwill look like this:\n\ncolor *THIS = ...;  // Initialized as in typemap\n\ndelete THIS;\n\nIf the function's name is new then the C++ \"new\" function will be called to create a dynamic\nC++ object.  The XSUB will expect the class name, which will be kept in a variable called\n\"CLASS\", to be given as the first argument.\n\ncolor *\ncolor::new()\n\nThe generated C++ code will call \"new\".\n\nRETVAL = new color();\n\nThe following is an example of a typemap that could be used for this C++ example.\n\nTYPEMAP\ncolor *  OOBJECT\n\nOUTPUT\n# The Perl object is blessed into 'CLASS', which should be a\n# char* having the name of the package for the blessing.\nOOBJECT\nsvsetrefpv( $arg, CLASS, (void*)$var );\n\nINPUT\nOOBJECT\nif( svisobject($arg) && (SvTYPE(SvRV($arg)) == SVtPVMG) )\n$var = ($type)SvIV((SV*)SvRV( $arg ));\nelse{\nwarn(\\\"${Package}::$funcname() -- \\\"\n\\\"$var is not a blessed SV reference\\\");\nXSRETURNUNDEF;\n}\n"
                    },
                    {
                        "name": "Interface Strategy",
                        "content": "When designing an interface between Perl and a C library a straight translation from C to XS\n(such as created by \"h2xs -x\") is often sufficient.  However, sometimes the interface will\nlook very C-like and occasionally nonintuitive, especially when the C function modifies one\nof its parameters, or returns failure inband (as in \"negative return values mean failure\").\nIn cases where the programmer wishes to create a more Perl-like interface the following\nstrategy may help to identify the more critical parts of the interface.\n\nIdentify the C functions with input/output or output parameters.  The XSUBs for these\nfunctions may be able to return lists to Perl.\n\nIdentify the C functions which use some inband info as an indication of failure.  They may be\ncandidates to return undef or an empty list in case of failure.  If the failure may be\ndetected without a call to the C function, you may want to use an INIT: section to report the\nfailure.  For failures detectable after the C function returns one may want to use a\nPOSTCALL: section to process the failure.  In more complicated cases use CODE: or PPCODE:\nsections.\n\nIf many functions use the same failure indication based on the return value, you may want to\ncreate a special typedef to handle this situation.  Put\n\ntypedef int negativeisfailure;\n\nnear the beginning of XS file, and create an OUTPUT typemap entry for \"negativeisfailure\"\nwhich converts negative values to \"undef\", or maybe croak()s.  After this the return value of\ntype \"negativeisfailure\" will create more Perl-like interface.\n\nIdentify which values are used by only the C and XSUB functions themselves, say, when a\nparameter to a function should be a contents of a global variable.  If Perl does not need to\naccess the contents of the value then it may not be necessary to provide a translation for\nthat value from C to Perl.\n\nIdentify the pointers in the C function parameter lists and return values.  Some pointers may\nbe used to implement input/output or output parameters, they can be handled in XS with the\n\"&\" unary operator, and, possibly, using the NOINIT keyword.  Some others will require\nhandling of types like \"int *\", and one needs to decide what a useful Perl translation will\ndo in such a case.  When the semantic is clear, it is advisable to put the translation into a\ntypemap file.\n\nIdentify the structures used by the C functions.  In many cases it may be helpful to use the\nTPTROBJ typemap for these structures so they can be manipulated by Perl as blessed objects.\n(This is handled automatically by \"h2xs -x\".)\n\nIf the same C type is used in several different contexts which require different\ntranslations, \"typedef\" several new types mapped to this C type, and create separate typemap\nentries for these new types.  Use these types in declarations of return type and parameters\nto XSUBs.\n"
                    },
                    {
                        "name": "Perl Objects And C Structures",
                        "content": "When dealing with C structures one should select either TPTROBJ or TPTRREF for the XS type.\nBoth types are designed to handle pointers to complex objects.  The TPTRREF type will allow\nthe Perl object to be unblessed while the TPTROBJ type requires that the object be blessed.\nBy using TPTROBJ one can achieve a form of type-checking because the XSUB will attempt to\nverify that the Perl object is of the expected type.\n\nThe following XS code shows the getnetconfigent() function which is used with ONC+ TIRPC.\nThe getnetconfigent() function will return a pointer to a C structure and has the C prototype\nshown below.  The example will demonstrate how the C pointer will become a Perl reference.\nPerl will consider this reference to be a pointer to a blessed object and will attempt to\ncall a destructor for the object.  A destructor will be provided in the XS source to free the\nmemory used by getnetconfigent().  Destructors in XS can be created by specifying an XSUB\nfunction whose name ends with the word DESTROY.  XS destructors can be used to free memory\nwhich may have been malloc'd by another XSUB.\n\nstruct netconfig *getnetconfigent(const char *netid);\n\nA \"typedef\" will be created for \"struct netconfig\".  The Perl object will be blessed in a\nclass matching the name of the C type, with the tag \"Ptr\" appended, and the name should not\nhave embedded spaces if it will be a Perl package name.  The destructor will be placed in a\nclass corresponding to the class of the object and the PREFIX keyword will be used to trim\nthe name to the word DESTROY as Perl will expect.\n\ntypedef struct netconfig Netconfig;\n\nMODULE = RPC  PACKAGE = RPC\n\nNetconfig *\ngetnetconfigent(netid)\nchar *netid\n\nMODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb\n\nvoid\nrpcbDESTROY(netconf)\nNetconfig *netconf\nCODE:\nprintf(\"Now in NetconfigPtr::DESTROY\\n\");\nfree( netconf );\n\nThis example requires the following typemap entry.  Consult perlxstypemap for more\ninformation about adding new typemaps for an extension.\n\nTYPEMAP\nNetconfig *  TPTROBJ\n\nThis example will be used with the following Perl statements.\n\nuse RPC;\n$netconf = getnetconfigent(\"udp\");\n\nWhen Perl destroys the object referenced by $netconf it will send the object to the supplied\nXSUB DESTROY function.  Perl cannot determine, and does not care, that this object is a C\nstruct and not a Perl object.  In this sense, there is no difference between the object\ncreated by the getnetconfigent() XSUB and an object created by a normal Perl subroutine.\n"
                    },
                    {
                        "name": "Safely Storing Static Data in XS",
                        "content": "Starting with Perl 5.8, a macro framework has been defined to allow static data to be safely\nstored in XS modules that will be accessed from a multi-threaded Perl.\n\nAlthough primarily designed for use with multi-threaded Perl, the macros have been designed\nso that they will work with non-threaded Perl as well.\n\nIt is therefore strongly recommended that these macros be used by all XS modules that make\nuse of static data.\n\nThe easiest way to get a template set of macros to use is by specifying the \"-g\" (\"--global\")\noption with h2xs (see h2xs).\n\nBelow is an example module that makes use of the macros.\n\n#define PERLNOGETCONTEXT\n#include \"EXTERN.h\"\n#include \"perl.h\"\n#include \"XSUB.h\"\n\n/* Global Data */\n\n#define MYCXTKEY \"BlindMice::guts\" XSVERSION\n\ntypedef struct {\nint count;\nchar name[3][100];\n} mycxtt;\n\nSTARTMYCXT\n\nMODULE = BlindMice           PACKAGE = BlindMice\n\nBOOT:\n{\nMYCXTINIT;\nMYCXT.count = 0;\nstrcpy(MYCXT.name[0], \"None\");\nstrcpy(MYCXT.name[1], \"None\");\nstrcpy(MYCXT.name[2], \"None\");\n}\n\nint\nnewMouse(char * name)\nPREINIT:\ndMYCXT;\nCODE:\nif (MYCXT.count >= 3) {\nwarn(\"Already have 3 blind mice\");\nRETVAL = 0;\n}\nelse {\nRETVAL = ++ MYCXT.count;\nstrcpy(MYCXT.name[MYCXT.count - 1], name);\n}\nOUTPUT:\nRETVAL\n\nchar *\ngetmousename(index)\nint index\nPREINIT:\ndMYCXT;\nCODE:\nif (index > MYCXT.count)\ncroak(\"There are only 3 blind mice.\");\nelse\nRETVAL = MYCXT.name[index - 1];\nOUTPUT:\nRETVAL\n\nvoid\nCLONE(...)\nCODE:\nMYCXTCLONE;\n\nMYCXT REFERENCE\n\nMYCXTKEY\nThis macro is used to define a unique key to refer to the static data for an XS module.\nThe suggested naming scheme, as used by h2xs, is to use a string that consists of the\nmodule name, the string \"::guts\" and the module version number.\n\n#define MYCXTKEY \"MyModule::guts\" XSVERSION\n\ntypedef mycxtt\nThis struct typedef must always be called \"mycxtt\". The other \"CXT*\" macros assume the\nexistence of the \"mycxtt\" typedef name.\n\nDeclare a typedef named \"mycxtt\" that is a structure that contains all the data that\nneeds to be interpreter-local.\n\ntypedef struct {\nint somevalue;\n} mycxtt;\n\nSTARTMYCXT\nAlways place the STARTMYCXT macro directly after the declaration of \"mycxtt\".\n\nMYCXTINIT\nThe MYCXTINIT macro initializes storage for the \"mycxtt\" struct.\n\nIt must be called exactly once, typically in a BOOT: section. If you are maintaining\nmultiple interpreters, it should be called once in each interpreter instance, except for\ninterpreters cloned from existing ones.  (But see \"MYCXTCLONE\" below.)\n\ndMYCXT\nUse the dMYCXT macro (a declaration) in all the functions that access MYCXT.\n\nMYCXT\nUse the MYCXT macro to access members of the \"mycxtt\" struct. For example, if\n\"mycxtt\" is\n\ntypedef struct {\nint index;\n} mycxtt;\n\nthen use this to access the \"index\" member\n\ndMYCXT;\nMYCXT.index = 2;\n\naMYCXT/pMYCXT\n\"dMYCXT\" may be quite expensive to calculate, and to avoid the overhead of invoking it\nin each function it is possible to pass the declaration onto other functions using the\n\"aMYCXT\"/\"pMYCXT\" macros, eg\n\nvoid sub1() {\ndMYCXT;\nMYCXT.index = 1;\nsub2(aMYCXT);\n}\n\nvoid sub2(pMYCXT) {\nMYCXT.index = 2;\n}\n\nAnalogously to \"pTHX\", there are equivalent forms for when the macro is the first or\nlast in multiple arguments, where an underscore represents a comma, i.e.  \"aMYCXT\",\n\"aMYCXT\", \"pMYCXT\" and \"pMYCXT\".\n\nMYCXTCLONE\nBy default, when a new interpreter is created as a copy of an existing one (eg via\n\"threads->create()\"), both interpreters share the same physical mycxtt structure.\nCalling \"MYCXTCLONE\" (typically via the package's \"CLONE()\" function), causes a byte-\nfor-byte copy of the structure to be taken, and any future dMYCXT will cause the copy\nto be accessed instead.\n\nMYCXTINITINTERP(myperl)\ndMYCXTINTERP(myperl)\nThese are versions of the macros which take an explicit interpreter as an argument.\n\nNote that these macros will only work together within the same source file; that is, a\ndMYCTX in one source file will access a different structure than a dMYCTX in another source\nfile.\n"
                    },
                    {
                        "name": "Thread-aware system interfaces",
                        "content": "Starting from Perl 5.8, in C/C++ level Perl knows how to wrap system/library interfaces that\nhave thread-aware versions (e.g. getpwentr()) into frontend macros (e.g. getpwent()) that\ncorrectly handle the multithreaded interaction with the Perl interpreter.  This will happen\ntransparently, the only thing you need to do is to instantiate a Perl interpreter.\n\nThis wrapping happens always when compiling Perl core source (PERLCORE is defined) or the\nPerl core extensions (PERLEXT is defined).  When compiling XS code outside of the Perl core,\nthe wrapping does not take place before Perl 5.28.  Starting in that release you can\n\n#define PERLREENTRANT\n\nin your code to enable the wrapping.  It is advisable to do so if you are using such\nfunctions, as intermixing the \"r\"-forms (as Perl compiled for multithreaded operation will\ndo) and the \"r\"-less forms is neither well-defined (inconsistent results, data corruption,\nor even crashes become more likely), nor is it very portable.  Unfortunately, not all systems\nhave all the \"r\" forms, but using this \"#define\" gives you whatever protection that Perl is\naware is available on each system.\n"
                    }
                ]
            },
            "EXAMPLES": {
                "content": "File \"RPC.xs\": Interface to some ONC+ RPC bind library functions.\n\n#define PERLNOGETCONTEXT\n#include \"EXTERN.h\"\n#include \"perl.h\"\n#include \"XSUB.h\"\n\n/* Note: On glibc 2.13 and earlier, this needs be <rpc/rpc.h> */\n#include <tirpc/rpc.h>\n\ntypedef struct netconfig Netconfig;\n\nMODULE = RPC  PACKAGE = RPC\n\nSV *\nrpcbgettime(host=\"localhost\")\nchar *host\nPREINIT:\ntimet  timep;\nCODE:\nST(0) = svnewmortal();\nif( rpcbgettime( host, &timep ) )\nsvsetnv( ST(0), (double)timep );\n\nNetconfig *\ngetnetconfigent(netid=\"udp\")\nchar *netid\n\nMODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb\n\nvoid\nrpcbDESTROY(netconf)\nNetconfig *netconf\nCODE:\nprintf(\"NetconfigPtr::DESTROY\\n\");\nfree( netconf );\n\nFile \"typemap\": Custom typemap for RPC.xs. (cf. perlxstypemap)\n\nTYPEMAP\nNetconfig *  TPTROBJ\n\nFile \"RPC.pm\": Perl module for the RPC extension.\n\npackage RPC;\n\nrequire Exporter;\nrequire DynaLoader;\n@ISA = qw(Exporter DynaLoader);\n@EXPORT = qw(rpcbgettime getnetconfigent);\n\nbootstrap RPC;\n1;\n\nFile \"rpctest.pl\": Perl test program for the RPC extension.\n\nuse RPC;\n\n$netconf = getnetconfigent();\n$a = rpcbgettime();\nprint \"time = $a\\n\";\nprint \"netconf = $netconf\\n\";\n\n$netconf = getnetconfigent(\"tcp\");\n$a = rpcbgettime(\"poplar\");\nprint \"time = $a\\n\";\nprint \"netconf = $netconf\\n\";\n\nIn Makefile.PL add -ltirpc and -I/usr/include/tirpc.\n",
                "subsections": []
            },
            "CAVEATS": {
                "content": "XS code has full access to system calls including C library functions.  It thus has the\ncapability of interfering with things that the Perl core or other modules have set up, such\nas signal handlers or file handles.  It could mess with the memory, or any number of harmful\nthings.  Don't.\n\nSome modules have an event loop, waiting for user-input.  It is highly unlikely that two such\nmodules would work adequately together in a single Perl application.\n\nIn general, the perl interpreter views itself as the center of the universe as far as the\nPerl program goes.  XS code is viewed as a help-mate, to accomplish things that perl doesn't\ndo, or doesn't do fast enough, but always subservient to perl.  The closer XS code adheres to\nthis model, the less likely conflicts will occur.\n\nOne area where there has been conflict is in regards to C locales.  (See perllocale.)  perl,\nwith one exception and unless told otherwise, sets up the underlying locale the program is\nrunning in to the locale passed into it from the environment.  This is an important\ndifference from a generic C language program, where the underlying locale is the \"C\" locale\nunless the program changes it.  As of v5.20, this underlying locale is completely hidden from\npure Perl code outside the lexical scope of \"use locale\" except for a couple of function\ncalls in the POSIX module which of necessity use it.  But the underlying locale, with that\none exception is exposed to XS code, affecting all C library routines whose behavior is\nlocale-dependent.  Your XS code better not assume that the underlying locale is \"C\".  The\nexception is the \"LCNUMERIC\" locale category, and the reason it is an exception is that\nexperience has shown that it can be problematic for XS code, whereas we have not had reports\nof problems with the other locale categories.  And the reason for this one category being\nproblematic is that the character used as a decimal point can vary.  Many European languages\nuse a comma, whereas English, and hence Perl are expecting a dot (U+002E: FULL STOP).  Many\nmodules can handle only the radix character being a dot, and so perl attempts to make it so.\nUp through Perl v5.20, the attempt was merely to set \"LCNUMERIC\" upon startup to the \"C\"\nlocale.  Any setlocale() otherwise would change it; this caused some failures.  Therefore,\nstarting in v5.22, perl tries to keep \"LCNUMERIC\" always set to \"C\" for XS code.\n\nTo summarize, here's what to expect and how to handle locales in XS code:\n\nNon-locale-aware XS code\nKeep in mind that even if you think your code is not locale-aware, it may call a library\nfunction that is.  Hopefully the man page for such a function will indicate that\ndependency, but the documentation is imperfect.\n\nThe current locale is exposed to XS code except possibly \"LCNUMERIC\" (explained in the\nnext paragraph).  There have not been reports of problems with the other categories.\nPerl initializes things on start-up so that the current locale is the one which is\nindicated by the user's environment in effect at that time.  See \"ENVIRONMENT\" in\nperllocale.\n\nHowever, up through v5.20, Perl initialized things on start-up so that \"LCNUMERIC\" was\nset to the \"C\" locale.  But if any code anywhere changed it, it would stay changed.  This\nmeans that your module can't count on \"LCNUMERIC\" being something in particular, and you\ncan't expect floating point numbers (including version strings) to have dots in them.  If\nyou don't allow for a non-dot, your code could break if anyone anywhere changed the\nlocale.  For this reason, v5.22 changed the behavior so that Perl tries to keep\n\"LCNUMERIC\" in the \"C\" locale except around the operations internally where it should be\nsomething else.  Misbehaving XS code will always be able to change the locale anyway, but\nthe most common instance of this is checked for and handled.\n\nLocale-aware XS code\nIf the locale from the user's environment is desired, there should be no need for XS code\nto set the locale except for \"LCNUMERIC\", as perl has already set the others up.  XS\ncode should avoid changing the locale, as it can adversely affect other, unrelated, code\nand may not be thread-safe.  To minimize problems, the macros\n\"STORELCNUMERICSETTONEEDED\" in perlapi, \"STORELCNUMERICFORCETOUNDERLYING\" in\nperlapi, and \"RESTORELCNUMERIC\" in perlapi should be used to affect any needed change.\n\nBut, starting with Perl v5.28, locales are thread-safe on platforms that support this\nfunctionality.  Windows has this starting with Visual Studio 2005.  Many other modern\nplatforms support the thread-safe POSIX 2008 functions.  The C \"#define\"\n\"USETHREADSAFELOCALE\" will be defined iff this build is using these.  From Perl-space,\nthe read-only variable \"${SAFELOCALES}\" is 1 if either the build is not threaded, or if\n\"USETHREADSAFELOCALE\" is defined; otherwise it is 0.\n\nThe way this works under-the-hood is that every thread has a choice of using a locale\nspecific to it (this is the Windows and POSIX 2008 functionality), or the global locale\nthat is accessible to all threads (this is the functionality that has always been there).\nThe implementations for Windows and POSIX are completely different.  On Windows, the\nruntime can be set up so that the standard setlocale(3) function either only knows about\nthe global locale or the locale for this thread.  On POSIX, \"setlocale\" always deals with\nthe global locale, and other functions have been created to handle per-thread locales.\nPerl makes this transparent to perl-space code.  It continues to use\n\"POSIX::setlocale()\", and the interpreter translates that into the per-thread functions.\n\nAll other locale-sensitive functions automatically use the per-thread locale, if that is\nturned on, and failing that, the global locale.  Thus calls to \"setlocale\" are\nineffective on POSIX systems for the current thread if that thread is using a per-thread\nlocale.  If perl is compiled for single-thread operation, it does not use the per-thread\nfunctions, so \"setlocale\" does work as expected.\n\nIf you have loaded the \"POSIX\" module you can use the methods given in perlcall to call\n\"POSIX::setlocale\" to safely change or query the locale (on systems where it is safe to\ndo so), or you can use the new 5.28 function \"Perlsetlocale\" in perlapi instead, which\nis a drop-in replacement for the system setlocale(3), and handles single-threaded and\nmulti-threaded applications transparently.\n\nThere are some locale-related library calls that still aren't thread-safe because they\nreturn data in a buffer global to all threads.  In the past, these didn't matter as\nlocales weren't thread-safe at all.  But now you have to be aware of them in case your\nmodule is called in a multi-threaded application.  The known ones are\n\nasctime()\nctime()\ngcvt() [POSIX.1-2001 only (function removed in POSIX.1-2008)]\ngetdate()\nwcrtomb() if its final argument is NULL\nwcsrtombs() if its final argument is NULL\nwcstombs()\nwctomb()\n\nSome of these shouldn't really be called in a Perl application, and for others there are\nthread-safe versions of these already implemented:\n\nasctimer()\nctimer()\nPerllanginfo()\n\nThe \"r\" forms are automatically used, starting in Perl 5.28, if you compile your code,\nwith\n\n#define PERLREENTRANT\n\nSee also \"Perllanginfo\" in perlapi.  You can use the methods given in perlcall, to get\nthe best available locale-safe versions of these\n\nPOSIX::localeconv()\nPOSIX::wcstombs()\nPOSIX::wctomb()\n\nAnd note, that some items returned by \"Localeconv\" are available through \"Perllanginfo\"\nin perlapi.\n\nThe others shouldn't be used in a threaded application.\n\nSome modules may call a non-perl library that is locale-aware.  This is fine as long as\nit doesn't try to query or change the locale using the system \"setlocale\".  But if these\ndo call the system \"setlocale\", those calls may be ineffective.  Instead,\n\"Perlsetlocale\" works in all circumstances.  Plain setlocale is ineffective on multi-\nthreaded POSIX 2008 systems.  It operates only on the global locale, whereas each thread\nhas its own locale, paying no attention to the global one.  Since converting these non-\nPerl libraries to \"Perlsetlocale\" is out of the question, there is a new function in\nv5.28 \"switchtogloballocale\" that will switch the thread it is called from so that any\nsystem \"setlocale\" calls will have their desired effect.  The function \"synclocale\" must\nbe called before returning to perl.\n\nThis thread can change the locale all it wants and it won't affect any other thread,\nexcept any that also have been switched to the global locale.  This means that a multi-\nthreaded application can have a single thread using an alien library without a problem;\nbut no more than a single thread can be so-occupied.  Bad results likely will happen.\n\nIn perls without multi-thread locale support, some alien libraries, such as \"Gtk\" change\nlocales.  This can cause problems for the Perl core and other modules.  For these, before\ncontrol is returned to perl, starting in v5.20.1, calling the function synclocale() from\nXS should be sufficient to avoid most of these problems.  Prior to this, you need a pure\nPerl statement that does this:\n\nPOSIX::setlocale(LCALL, POSIX::setlocale(LCALL));\n\nor use the methods given in perlcall.\n",
                "subsections": []
            },
            "XS VERSION": {
                "content": "This document covers features supported by \"ExtUtils::ParseXS\" (also known as \"xsubpp\")\n3.1301.\n",
                "subsections": []
            },
            "AUTHOR": {
                "content": "Originally written by Dean Roehrich <roehrich@cray.com>.\n\nMaintained since 1996 by The Perl Porters <perlbug@perl.org>.\n\n\n\nperl v5.34.0                                 2025-07-25                                    PERLXS(1)",
                "subsections": []
            }
        }
    }
}