{
    "content": [
        {
            "type": "text",
            "text": "# perlxstut (man)\n\n## NAME\n\nperlxstut - Tutorial for writing XSUBs\n\n## DESCRIPTION\n\nThis tutorial will educate the reader on the steps involved in creating a Perl extension.\nThe reader is assumed to have access to perlguts, perlapi and perlxs.\n\n## Sections\n\n- **NAME**\n- **DESCRIPTION**\n- **SPECIAL NOTES** (3 subsections)\n- **TUTORIAL** (22 subsections)\n- **Author** (1 subsections)\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "perlxstut",
        "section": "",
        "mode": "man",
        "summary": "perlxstut - Tutorial for writing XSUBs",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 11,
                "subsections": []
            },
            {
                "name": "SPECIAL NOTES",
                "lines": 1,
                "subsections": [
                    {
                        "name": "make",
                        "lines": 5
                    },
                    {
                        "name": "Version caveat",
                        "lines": 26
                    },
                    {
                        "name": "Dynamic Loading versus Static Loading",
                        "lines": 29
                    }
                ]
            },
            {
                "name": "TUTORIAL",
                "lines": 186,
                "subsections": [
                    {
                        "name": "What has gone on?",
                        "lines": 54
                    },
                    {
                        "name": "Writing good test scripts",
                        "lines": 70
                    },
                    {
                        "name": "What's new here?",
                        "lines": 8
                    },
                    {
                        "name": "Input and Output Parameters",
                        "lines": 10
                    },
                    {
                        "name": "The XSUBPP Program",
                        "lines": 4
                    },
                    {
                        "name": "The TYPEMAP file",
                        "lines": 44
                    },
                    {
                        "name": "Warning about Output Arguments",
                        "lines": 144
                    },
                    {
                        "name": "What has happened here?",
                        "lines": 30
                    },
                    {
                        "name": "Anatomy of .xs file",
                        "lines": 25
                    },
                    {
                        "name": "Getting the fat out of XSUBs",
                        "lines": 73
                    },
                    {
                        "name": "More about XSUB arguments",
                        "lines": 64
                    },
                    {
                        "name": "The Argument Stack",
                        "lines": 38
                    },
                    {
                        "name": "Extending your Extension",
                        "lines": 7
                    },
                    {
                        "name": "Documenting your Extension",
                        "lines": 10
                    },
                    {
                        "name": "Installing your Extension",
                        "lines": 59
                    },
                    {
                        "name": "New Things in this Example",
                        "lines": 111
                    },
                    {
                        "name": "New Things in this Example",
                        "lines": 49
                    },
                    {
                        "name": "EXAMPLE 7 (Coming Soon)",
                        "lines": 2
                    },
                    {
                        "name": "EXAMPLE 8 (Coming Soon)",
                        "lines": 2
                    },
                    {
                        "name": "EXAMPLE 9 Passing open files to XSes",
                        "lines": 94
                    },
                    {
                        "name": "Troubleshooting these Examples",
                        "lines": 22
                    },
                    {
                        "name": "See also",
                        "lines": 2
                    }
                ]
            },
            {
                "name": "Author",
                "lines": 10,
                "subsections": [
                    {
                        "name": "Last Changed",
                        "lines": 5
                    }
                ]
            }
        ],
        "sections": {
            "NAME": {
                "content": "perlxstut - Tutorial for writing XSUBs\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "This tutorial will educate the reader on the steps involved in creating a Perl extension.\nThe reader is assumed to have access to perlguts, perlapi and perlxs.\n\nThis tutorial starts with very simple examples and becomes more complex, with each new\nexample adding new features.  Certain concepts may not be completely explained until later in\nthe tutorial in order to slowly ease the reader into building extensions.\n\nThis tutorial was written from a Unix point of view.  Where I know them to be otherwise\ndifferent for other platforms (e.g. Win32), I will list them.  If you find something that was\nmissed, please let me know.\n",
                "subsections": []
            },
            "SPECIAL NOTES": {
                "content": "",
                "subsections": [
                    {
                        "name": "make",
                        "content": "This tutorial assumes that the make program that Perl is configured to use is called \"make\".\nInstead of running \"make\" in the examples that follow, you may have to substitute whatever\nmake program Perl has been configured to use.  Running perl -V:make should tell you what it\nis.\n"
                    },
                    {
                        "name": "Version caveat",
                        "content": "When writing a Perl extension for general consumption, one should expect that the extension\nwill be used with versions of Perl different from the version available on your machine.\nSince you are reading this document, the version of Perl on your machine is probably 5.005 or\nlater, but the users of your extension may have more ancient versions.\n\nTo understand what kinds of incompatibilities one may expect, and in the rare case that the\nversion of Perl on your machine is older than this document, see the section on\n\"Troubleshooting these Examples\" for more information.\n\nIf your extension uses some features of Perl which are not available on older releases of\nPerl, your users would appreciate an early meaningful warning.  You would probably put this\ninformation into the README file, but nowadays installation of extensions may be performed\nautomatically, guided by CPAN.pm module or other tools.\n\nIn MakeMaker-based installations, Makefile.PL provides the earliest opportunity to perform\nversion checks.  One can put something like this in Makefile.PL for this purpose:\n\neval { require 5.007 }\nor die <<EOD;\n############\n### This module uses frobnication framework which is not available\n### before version 5.007 of Perl.  Upgrade your Perl before\n### installing Kara::Mba.\n############\nEOD\n"
                    },
                    {
                        "name": "Dynamic Loading versus Static Loading",
                        "content": "It is commonly thought that if a system does not have the capability to dynamically load a\nlibrary, you cannot build XSUBs.  This is incorrect.  You can build them, but you must link\nthe XSUBs subroutines with the rest of Perl, creating a new executable.  This situation is\nsimilar to Perl 4.\n\nThis tutorial can still be used on such a system.  The XSUB build mechanism will check the\nsystem and build a dynamically-loadable library if possible, or else a static library and\nthen, optionally, a new statically-linked executable with that static library linked in.\n\nShould you wish to build a statically-linked executable on a system which can dynamically\nload libraries, you may, in all the following examples, where the command \"\"make\"\" with no\narguments is executed, run the command \"\"make perl\"\" instead.\n\nIf you have generated such a statically-linked executable by choice, then instead of saying\n\"\"make test\"\", you should say \"\"make teststatic\"\".  On systems that cannot build\ndynamically-loadable libraries at all, simply saying \"\"make test\"\" is sufficient.\n\nThreads and PERLNOGETCONTEXT\nFor threaded builds, perl requires the context pointer for the current thread, without\n\"PERLNOGETCONTEXT\", perl will call a function to retrieve the context.\n\nFor improved performance, include:\n\n#define PERLNOGETCONTEXT\n\nas shown below.\n\nFor more details, see perlguts.\n"
                    }
                ]
            },
            "TUTORIAL": {
                "content": "Now let's go on with the show!\n\nEXAMPLE 1\nOur first extension will be very simple.  When we call the routine in the extension, it will\nprint out a well-known message and return.\n\nRun \"\"h2xs -A -n Mytest\"\".  This creates a directory named Mytest, possibly under ext/ if\nthat directory exists in the current working directory.  Several files will be created under\nthe Mytest dir, including MANIFEST, Makefile.PL, lib/Mytest.pm, Mytest.xs, t/Mytest.t, and\nChanges.\n\nThe MANIFEST file contains the names of all the files just created in the Mytest directory.\n\nThe file Makefile.PL should look something like this:\n\nuse ExtUtils::MakeMaker;\n\n# See lib/ExtUtils/MakeMaker.pm for details of how to influence\n# the contents of the Makefile that is written.\nWriteMakefile(\nNAME         => 'Mytest',\nVERSIONFROM => 'Mytest.pm', # finds $VERSION\nLIBS         => [''],        # e.g., '-lm'\nDEFINE       => '',          # e.g., '-DHAVESOMETHING'\nINC          => '-I',        # e.g., '-I. -I/usr/include/other'\n);\n\nThe file Mytest.pm should start with something like this:\n\npackage Mytest;\n\nuse 5.008008;\nuse strict;\nuse warnings;\n\nrequire Exporter;\n\nour @ISA = qw(Exporter);\nour %EXPORTTAGS = ( 'all' => [ qw(\n\n) ] );\n\nour @EXPORTOK = ( @{ $EXPORTTAGS{'all'} } );\n\nour @EXPORT = qw(\n\n);\n\nour $VERSION = '0.01';\n\nrequire XSLoader;\nXSLoader::load('Mytest', $VERSION);\n\n# Preloaded methods go here.\n\n1;\nEND\n# Below is the stub of documentation for your module. You better\n# edit it!\n\nThe rest of the .pm file contains sample code for providing documentation for the extension.\n\nFinally, the Mytest.xs file should look something like this:\n\n#define PERLNOGETCONTEXT\n#include \"EXTERN.h\"\n#include \"perl.h\"\n#include \"XSUB.h\"\n\n#include \"ppport.h\"\n\nMODULE = Mytest             PACKAGE = Mytest\n\nLet's edit the .xs file by adding this to the end of the file:\n\nvoid\nhello()\nCODE:\nprintf(\"Hello, world!\\n\");\n\nIt is okay for the lines starting at the \"CODE:\" line to not be indented.  However, for\nreadability purposes, it is suggested that you indent CODE: one level and the lines following\none more level.\n\nNow we'll run \"\"perl Makefile.PL\"\".  This will create a real Makefile, which make needs.  Its\noutput looks something like:\n\n% perl Makefile.PL\nChecking if your kit is complete...\nLooks good\nWriting Makefile for Mytest\n%\n\nNow, running make will produce output that looks something like this (some long lines have\nbeen shortened for clarity and some extraneous lines have been deleted):\n\n% make\ncp lib/Mytest.pm blib/lib/Mytest.pm\nperl xsubpp  -typemap typemap  Mytest.xs > Mytest.xsc && \\\nmv Mytest.xsc Mytest.c\nPlease specify prototyping behavior for Mytest.xs (see perlxs manual)\ncc -c     Mytest.c\nRunning Mkbootstrap for Mytest ()\nchmod 644 Mytest.bs\nrm -f blib/arch/auto/Mytest/Mytest.so\ncc -shared -L/usr/local/lib Mytest.o -o blib/arch/auto/Mytest/Mytest.so\n\nchmod 755 blib/arch/auto/Mytest/Mytest.so\ncp Mytest.bs blib/arch/auto/Mytest/Mytest.bs\nchmod 644 blib/arch/auto/Mytest/Mytest.bs\nManifying blib/man3/Mytest.3pm\n%\n\nYou can safely ignore the line about \"prototyping behavior\" - it is explained in \"The\nPROTOTYPES: Keyword\" in perlxs.\n\nPerl has its own special way of easily writing test scripts, but for this example only, we'll\ncreate our own test script.  Create a file called hello that looks like this:\n\n#! /opt/perl5/bin/perl\n\nuse ExtUtils::testlib;\n\nuse Mytest;\n\nMytest::hello();\n\nNow we make the script executable (\"chmod +x hello\"), run the script and we should see the\nfollowing output:\n\n% ./hello\nHello, world!\n%\n\nEXAMPLE 2\nNow let's add to our extension a subroutine that will take a single numeric argument as input\nand return 1 if the number is even or 0 if the number is odd.\n\nAdd the following to the end of Mytest.xs:\n\nint\niseven(input)\nint input\nCODE:\nRETVAL = (input % 2 == 0);\nOUTPUT:\nRETVAL\n\nThere does not need to be whitespace at the start of the \"\"int input\"\" line, but it is useful\nfor improving readability.  Placing a semi-colon at the end of that line is also optional.\nAny amount and kind of whitespace may be placed between the \"\"int\"\" and \"\"input\"\".\n\nNow re-run make to rebuild our new shared library.\n\nNow perform the same steps as before, generating a Makefile from the Makefile.PL file, and\nrunning make.\n\nIn order to test that our extension works, we now need to look at the file Mytest.t.  This\nfile is set up to imitate the same kind of testing structure that Perl itself has.  Within\nthe test script, you perform a number of tests to confirm the behavior of the extension,\nprinting \"ok\" when the test is correct, \"not ok\" when it is not.\n\nuse Test::More tests => 4;\nBEGIN { useok('Mytest') };\n\n#########################\n\n# Insert your test code below, the Test::More module is use()ed here\n# so read its man page ( perldoc Test::More ) for help writing this\n# test script.\n\nis( Mytest::iseven(0), 1 );\nis( Mytest::iseven(1), 0 );\nis( Mytest::iseven(2), 1 );\n\nWe will be calling the test script through the command \"\"make test\"\".  You should see output\nthat looks something like this:\n\n%make test\nPERLDLNONLAZY=1 /usr/bin/perl \"-MExtUtils::Command::MM\" \"-e\"\n\"testharness(0, 'blib/lib', 'blib/arch')\" t/*.t\nt/Mytest....ok\nAll tests successful.\nFiles=1, Tests=4, 0 wallclock secs ( 0.03 cusr + 0.00 csys = 0.03 CPU)\n%\n",
                "subsections": [
                    {
                        "name": "What has gone on?",
                        "content": "The program h2xs is the starting point for creating extensions.  In later examples we'll see\nhow we can use h2xs to read header files and generate templates to connect to C routines.\n\nh2xs creates a number of files in the extension directory.  The file Makefile.PL is a perl\nscript which will generate a true Makefile to build the extension.  We'll take a closer look\nat it later.\n\nThe .pm and .xs files contain the meat of the extension.  The .xs file holds the C routines\nthat make up the extension.  The .pm file contains routines that tell Perl how to load your\nextension.\n\nGenerating the Makefile and running \"make\" created a directory called blib (which stands for\n\"build library\") in the current working directory.  This directory will contain the shared\nlibrary that we will build.  Once we have tested it, we can install it into its final\nlocation.\n\nInvoking the test script via \"\"make test\"\" did something very important.  It invoked perl\nwith all those \"-I\" arguments so that it could find the various files that are part of the\nextension.  It is very important that while you are still testing extensions that you use\n\"\"make test\"\".  If you try to run the test script all by itself, you will get a fatal error.\nAnother reason it is important to use \"\"make test\"\" to run your test script is that if you\nare testing an upgrade to an already-existing version, using \"\"make test\"\" ensures that you\nwill test your new extension, not the already-existing version.\n\nWhen Perl sees a \"use extension;\", it searches for a file with the same name as the \"use\"'d\nextension that has a .pm suffix.  If that file cannot be found, Perl dies with a fatal error.\nThe default search path is contained in the @INC array.\n\nIn our case, Mytest.pm tells perl that it will need the Exporter and Dynamic Loader\nextensions.  It then sets the @ISA and @EXPORT arrays and the $VERSION scalar; finally it\ntells perl to bootstrap the module.  Perl will call its dynamic loader routine (if there is\none) and load the shared library.\n\nThe two arrays @ISA and @EXPORT are very important.  The @ISA array contains a list of other\npackages in which to search for methods (or subroutines) that do not exist in the current\npackage.  This is usually only important for object-oriented extensions (which we will talk\nabout much later), and so usually doesn't need to be modified.\n\nThe @EXPORT array tells Perl which of the extension's variables and subroutines should be\nplaced into the calling package's namespace.  Because you don't know if the user has already\nused your variable and subroutine names, it's vitally important to carefully select what to\nexport.  Do not export method or variable names by default without a good reason.\n\nAs a general rule, if the module is trying to be object-oriented then don't export anything.\nIf it's just a collection of functions and variables, then you can export them via another\narray, called @EXPORTOK.  This array does not automatically place its subroutine and\nvariable names into the namespace unless the user specifically requests that this be done.\n\nSee perlmod for more information.\n\nThe $VERSION variable is used to ensure that the .pm file and the shared library are \"in\nsync\" with each other.  Any time you make changes to the .pm or .xs files, you should\nincrement the value of this variable.\n"
                    },
                    {
                        "name": "Writing good test scripts",
                        "content": "The importance of writing good test scripts cannot be over-emphasized.  You should closely\nfollow the \"ok/not ok\" style that Perl itself uses, so that it is very easy and unambiguous\nto determine the outcome of each test case.  When you find and fix a bug, make sure you add a\ntest case for it.\n\nBy running \"\"make test\"\", you ensure that your Mytest.t script runs and uses the correct\nversion of your extension.  If you have many test cases, save your test files in the \"t\"\ndirectory and use the suffix \".t\".  When you run \"\"make test\"\", all of these test files will\nbe executed.\n\nEXAMPLE 3\nOur third extension will take one argument as its input, round off that value, and set the\nargument to the rounded value.\n\nAdd the following to the end of Mytest.xs:\n\nvoid\nround(arg)\ndouble  arg\nCODE:\nif (arg > 0.0) {\narg = floor(arg + 0.5);\n} else if (arg < 0.0) {\narg = ceil(arg - 0.5);\n} else {\narg = 0.0;\n}\nOUTPUT:\narg\n\nEdit the Makefile.PL file so that the corresponding line looks like this:\n\nLIBS      => ['-lm'],   # e.g., '-lm'\n\nGenerate the Makefile and run make.  Change the test number in Mytest.t to \"9\" and add the\nfollowing tests:\n\nmy $i;\n\n$i = -1.5;\nMytest::round($i);\nis( $i, -2.0, 'Rounding -1.5 to -2.0' );\n\n$i = -1.1;\nMytest::round($i);\nis( $i, -1.0, 'Rounding -1.1 to -1.0' );\n\n$i = 0.0;\nMytest::round($i);\nis( $i, 0.0, 'Rounding 0.0 to 0.0' );\n\n$i = 0.5;\nMytest::round($i);\nis( $i, 1.0, 'Rounding 0.5 to 1.0' );\n\n$i = 1.2;\nMytest::round($i);\nis( $i, 1.0, 'Rounding 1.2 to 1.0' );\n\nRunning \"\"make test\"\" should now print out that all nine tests are okay.\n\nNotice that in these new test cases, the argument passed to round was a scalar variable.  You\nmight be wondering if you can round a constant or literal.  To see what happens, temporarily\nadd the following line to Mytest.t:\n\nMytest::round(3);\n\nRun \"\"make test\"\" and notice that Perl dies with a fatal error.  Perl won't let you change\nthe value of constants!\n"
                    },
                    {
                        "name": "What's new here?",
                        "content": "•   We've made some changes to Makefile.PL.  In this case, we've specified an extra library\nto be linked into the extension's shared library, the math library libm in this case.\nWe'll talk later about how to write XSUBs that can call every routine in a library.\n\n•   The value of the function is not being passed back as the function's return value, but by\nchanging the value of the variable that was passed into the function.  You might have\nguessed that when you saw that the return value of round is of type \"void\".\n"
                    },
                    {
                        "name": "Input and Output Parameters",
                        "content": "You specify the parameters that will be passed into the XSUB on the line(s) after you declare\nthe function's return value and name.  Each input parameter line starts with optional\nwhitespace, and may have an optional terminating semicolon.\n\nThe list of output parameters occurs at the very end of the function, just after the OUTPUT:\ndirective.  The use of RETVAL tells Perl that you wish to send this value back as the return\nvalue of the XSUB function.  In Example 3, we wanted the \"return value\" placed in the\noriginal variable which we passed in, so we listed it (and not RETVAL) in the OUTPUT:\nsection.\n"
                    },
                    {
                        "name": "The XSUBPP Program",
                        "content": "The xsubpp program takes the XS code in the .xs file and translates it into C code, placing\nit in a file whose suffix is .c.  The C code created makes heavy use of the C functions\nwithin Perl.\n"
                    },
                    {
                        "name": "The TYPEMAP file",
                        "content": "The xsubpp program uses rules to convert from Perl's data types (scalar, array, etc.) to C's\ndata types (int, char, etc.).  These rules are stored in the typemap file\n($PERLLIB/ExtUtils/typemap).  There's a brief discussion below, but all the nitty-gritty\ndetails can be found in perlxstypemap.  If you have a new-enough version of perl (5.16 and\nup) or an upgraded XS compiler (\"ExtUtils::ParseXS\" 3.1301 or better), then you can inline\ntypemaps in your XS instead of writing separate files.  Either way, this typemap thing is\nsplit into three parts:\n\nThe first section maps various C data types to a name, which corresponds somewhat with the\nvarious Perl types.  The second section contains C code which xsubpp uses to handle input\nparameters.  The third section contains C code which xsubpp uses to handle output parameters.\n\nLet's take a look at a portion of the .c file created for our extension.  The file name is\nMytest.c:\n\nXS(XSMytestround)\n{\ndXSARGS;\nif (items != 1)\nPerlcroak(aTHX \"Usage: Mytest::round(arg)\");\nPERLUNUSEDVAR(cv); /* -W */\n{\ndouble  arg = (double)SvNV(ST(0));      /* XXXXX */\nif (arg > 0.0) {\narg = floor(arg + 0.5);\n} else if (arg < 0.0) {\narg = ceil(arg - 0.5);\n} else {\narg = 0.0;\n}\nsvsetnv(ST(0), (double)arg);   /* XXXXX */\nSvSETMAGIC(ST(0));\n}\nXSRETURNEMPTY;\n}\n\nNotice the two lines commented with \"XXXXX\".  If you check the first part of the typemap file\n(or section), you'll see that doubles are of type TDOUBLE.  In the INPUT part of the\ntypemap, an argument that is TDOUBLE is assigned to the variable arg by calling the routine\nSvNV on something, then casting it to double, then assigned to the variable arg.  Similarly,\nin the OUTPUT section, once arg has its final value, it is passed to the svsetnv function to\nbe passed back to the calling subroutine.  These two functions are explained in perlguts;\nwe'll talk more later about what that \"ST(0)\" means in the section on the argument stack.\n"
                    },
                    {
                        "name": "Warning about Output Arguments",
                        "content": "In general, it's not a good idea to write extensions that modify their input parameters, as\nin Example 3.  Instead, you should probably return multiple values in an array and let the\ncaller handle them (we'll do this in a later example).  However, in order to better\naccommodate calling pre-existing C routines, which often do modify their input parameters,\nthis behavior is tolerated.\n\nEXAMPLE 4\nIn this example, we'll now begin to write XSUBs that will interact with pre-defined C\nlibraries.  To begin with, we will build a small library of our own, then let h2xs write our\n.pm and .xs files for us.\n\nCreate a new directory called Mytest2 at the same level as the directory Mytest.  In the\nMytest2 directory, create another directory called mylib, and cd into that directory.\n\nHere we'll create some files that will generate a test library.  These will include a C\nsource file and a header file.  We'll also create a Makefile.PL in this directory.  Then\nwe'll make sure that running make at the Mytest2 level will automatically run this\nMakefile.PL file and the resulting Makefile.\n\nIn the mylib directory, create a file mylib.h that looks like this:\n\n#define TESTVAL 4\n\nextern double   foo(int, long, const char*);\n\nAlso create a file mylib.c that looks like this:\n\n#include <stdlib.h>\n#include \"mylib.h\"\n\ndouble\nfoo(int a, long b, const char *c)\n{\nreturn (a + b + atof(c) + TESTVAL);\n}\n\nAnd finally create a file Makefile.PL that looks like this:\n\nuse ExtUtils::MakeMaker;\n$Verbose = 1;\nWriteMakefile(\nNAME  => 'Mytest2::mylib',\nSKIP  => [qw(all static staticlib dynamic dynamiclib)],\nclean => {'FILES' => 'libmylib$(LIBEXT)'},\n);\n\n\nsub MY::toptargets {\n'\nall :: static\n\npureall :: static\n\nstatic ::       libmylib$(LIBEXT)\n\nlibmylib$(LIBEXT): $(OFILES)\n$(AR) cr libmylib$(LIBEXT) $(OFILES)\n$(RANLIB) libmylib$(LIBEXT)\n\n';\n}\n\nMake sure you use a tab and not spaces on the lines beginning with \"$(AR)\" and \"$(RANLIB)\".\nMake will not function properly if you use spaces.  It has also been reported that the \"cr\"\nargument to $(AR) is unnecessary on Win32 systems.\n\nWe will now create the main top-level Mytest2 files.  Change to the directory above Mytest2\nand run the following command:\n\n% h2xs -O -n Mytest2 Mytest2/mylib/mylib.h\n\nThis will print out a warning about overwriting Mytest2, but that's okay.  Our files are\nstored in Mytest2/mylib, and will be untouched.\n\nThe normal Makefile.PL that h2xs generates doesn't know about the mylib directory.  We need\nto tell it that there is a subdirectory and that we will be generating a library in it.\nLet's add the argument MYEXTLIB to the WriteMakefile call so that it looks like this:\n\nWriteMakefile(\nNAME         => 'Mytest2',\nVERSIONFROM => 'Mytest2.pm', # finds $VERSION\nLIBS         => [''],   # e.g., '-lm'\nDEFINE       => '',     # e.g., '-DHAVESOMETHING'\nINC          => '',     # e.g., '-I/usr/include/other'\nMYEXTLIB     => 'mylib/libmylib$(LIBEXT)',\n);\n\nand then at the end add a subroutine (which will override the pre-existing subroutine).\nRemember to use a tab character to indent the line beginning with \"cd\"!\n\nsub MY::postamble {\n'\n$(MYEXTLIB): mylib/Makefile\ncd mylib && $(MAKE) $(PASSTHRU)\n';\n}\n\nLet's also fix the MANIFEST file by appending the following three lines:\n\nmylib/Makefile.PL\nmylib/mylib.c\nmylib/mylib.h\n\nTo keep our namespace nice and unpolluted, edit the .pm file and change the variable @EXPORT\nto @EXPORTOK.  Finally, in the .xs file, edit the #include line to read:\n\n#include \"mylib/mylib.h\"\n\nAnd also add the following function definition to the end of the .xs file:\n\ndouble\nfoo(a,b,c)\nint             a\nlong            b\nconst char *    c\nOUTPUT:\nRETVAL\n\nNow we also need to create a typemap because the default Perl doesn't currently support the\n\"const char *\" type.  Include a new TYPEMAP section in your XS code before the above\nfunction:\n\nTYPEMAP: <<END\nconst char *    TPV\nEND\n\nNow run perl on the top-level Makefile.PL.  Notice that it also created a Makefile in the\nmylib directory.  Run make and watch that it does cd into the mylib directory and run make in\nthere as well.\n\nNow edit the Mytest2.t script and change the number of tests to \"5\", and add the following\nlines to the end of the script:\n\nis( Mytest2::foo( 1, 2, \"Hello, world!\" ), 7 );\nis( Mytest2::foo( 1, 2, \"0.0\" ),           7 );\nok( abs( Mytest2::foo( 0, 0, \"-3.4\" ) - 0.6 ) <= 0.01 );\n\n(When dealing with floating-point comparisons, it is best to not check for equality, but\nrather that the difference between the expected and actual result is below a certain amount\n(called epsilon) which is 0.01 in this case)\n\nRun \"\"make test\"\" and all should be well. There are some warnings on missing tests for the\nMytest2::mylib extension, but you can ignore them.\n"
                    },
                    {
                        "name": "What has happened here?",
                        "content": "Unlike previous examples, we've now run h2xs on a real include file.  This has caused some\nextra goodies to appear in both the .pm and .xs files.\n\n•   In the .xs file, there's now a #include directive with the absolute path to the mylib.h\nheader file.  We changed this to a relative path so that we could move the extension\ndirectory if we wanted to.\n\n•   There's now some new C code that's been added to the .xs file.  The purpose of the\n\"constant\" routine is to make the values that are #define'd in the header file accessible\nby the Perl script (by calling either \"TESTVAL\" or &Mytest2::TESTVAL).  There's also some\nXS code to allow calls to the \"constant\" routine.\n\n•   The .pm file originally exported the name \"TESTVAL\" in the @EXPORT array.  This could\nlead to name clashes.  A good rule of thumb is that if the #define is only going to be\nused by the C routines themselves, and not by the user, they should be removed from the\n@EXPORT array.  Alternately, if you don't mind using the \"fully qualified name\" of a\nvariable, you could move most or all of the items from the @EXPORT array into the\n@EXPORTOK array.\n\n•   If our include file had contained #include directives, these would not have been\nprocessed by h2xs.  There is no good solution to this right now.\n\n•   We've also told Perl about the library that we built in the mylib subdirectory.  That\nrequired only the addition of the \"MYEXTLIB\" variable to the WriteMakefile call and the\nreplacement of the postamble subroutine to cd into the subdirectory and run make.  The\nMakefile.PL for the library is a bit more complicated, but not excessively so.  Again we\nreplaced the postamble subroutine to insert our own code.  This code simply specified\nthat the library to be created here was a static archive library (as opposed to a\ndynamically loadable library) and provided the commands to build it.\n"
                    },
                    {
                        "name": "Anatomy of .xs file",
                        "content": "The .xs file of \"EXAMPLE 4\" contained some new elements.  To understand the meaning of these\nelements, pay attention to the line which reads\n\nMODULE = Mytest2                PACKAGE = Mytest2\n\nAnything before this line is plain C code which describes which headers to include, and\ndefines some convenience functions.  No translations are performed on this part, apart from\nhaving embedded POD documentation skipped over (see perlpod) it goes into the generated\noutput C file as is.\n\nAnything after this line is the description of XSUB functions.  These descriptions are\ntranslated by xsubpp into C code which implements these functions using Perl calling\nconventions, and which makes these functions visible from Perl interpreter.\n\nPay a special attention to the function \"constant\".  This name appears twice in the generated\n.xs file: once in the first part, as a static C function, then another time in the second\npart, when an XSUB interface to this static C function is defined.\n\nThis is quite typical for .xs files: usually the .xs file provides an interface to an\nexisting C function.  Then this C function is defined somewhere (either in an external\nlibrary, or in the first part of .xs file), and a Perl interface to this function (i.e. \"Perl\nglue\") is described in the second part of .xs file.  The situation in \"EXAMPLE 1\", \"EXAMPLE\n2\", and \"EXAMPLE 3\", when all the work is done inside the \"Perl glue\", is somewhat of an\nexception rather than the rule.\n"
                    },
                    {
                        "name": "Getting the fat out of XSUBs",
                        "content": "In \"EXAMPLE 4\" the second part of .xs file contained the following description of an XSUB:\n\ndouble\nfoo(a,b,c)\nint             a\nlong            b\nconst char *    c\nOUTPUT:\nRETVAL\n\nNote that in contrast with \"EXAMPLE 1\", \"EXAMPLE 2\" and \"EXAMPLE 3\", this description does\nnot contain the actual code for what is done during a call to Perl function foo().  To\nunderstand what is going on here, one can add a CODE section to this XSUB:\n\ndouble\nfoo(a,b,c)\nint             a\nlong            b\nconst char *    c\nCODE:\nRETVAL = foo(a,b,c);\nOUTPUT:\nRETVAL\n\nHowever, these two XSUBs provide almost identical generated C code: xsubpp compiler is smart\nenough to figure out the \"CODE:\" section from the first two lines of the description of XSUB.\nWhat about \"OUTPUT:\" section?  In fact, that is absolutely the same!  The \"OUTPUT:\" section\ncan be removed as well, as far as \"CODE:\" section or \"PPCODE:\" section is not specified:\nxsubpp can see that it needs to generate a function call section, and will autogenerate the\nOUTPUT section too.  Thus one can shortcut the XSUB to become:\n\ndouble\nfoo(a,b,c)\nint             a\nlong            b\nconst char *    c\n\nCan we do the same with an XSUB\n\nint\niseven(input)\nint     input\nCODE:\nRETVAL = (input % 2 == 0);\nOUTPUT:\nRETVAL\n\nof \"EXAMPLE 2\"?  To do this, one needs to define a C function \"int iseven(int input)\".  As\nwe saw in \"Anatomy of .xs file\", a proper place for this definition is in the first part of\n.xs file.  In fact a C function\n\nint\niseven(int arg)\n{\nreturn (arg % 2 == 0);\n}\n\nis probably overkill for this.  Something as simple as a \"#define\" will do too:\n\n#define iseven(arg)    ((arg) % 2 == 0)\n\nAfter having this in the first part of .xs file, the \"Perl glue\" part becomes as simple as\n\nint\niseven(input)\nint     input\n\nThis technique of separation of the glue part from the workhorse part has obvious tradeoffs:\nif you want to change a Perl interface, you need to change two places in your code.  However,\nit removes a lot of clutter, and makes the workhorse part independent from idiosyncrasies of\nPerl calling convention.  (In fact, there is nothing Perl-specific in the above description,\na different version of xsubpp might have translated this to TCL glue or Python glue as well.)\n"
                    },
                    {
                        "name": "More about XSUB arguments",
                        "content": "With the completion of Example 4, we now have an easy way to simulate some real-life\nlibraries whose interfaces may not be the cleanest in the world.  We shall now continue with\na discussion of the arguments passed to the xsubpp compiler.\n\nWhen you specify arguments to routines in the .xs file, you are really passing three pieces\nof information for each argument listed.  The first piece is the order of that argument\nrelative to the others (first, second, etc).  The second is the type of argument, and\nconsists of the type declaration of the argument (e.g., int, char*, etc).  The third piece is\nthe calling convention for the argument in the call to the library function.\n\nWhile Perl passes arguments to functions by reference, C passes arguments by value; to\nimplement a C function which modifies data of one of the \"arguments\", the actual argument of\nthis C function would be a pointer to the data.  Thus two C functions with declarations\n\nint stringlength(char *s);\nint uppercasechar(char *cp);\n\nmay have completely different semantics: the first one may inspect an array of chars pointed\nby s, and the second one may immediately dereference \"cp\" and manipulate *cp only (using the\nreturn value as, say, a success indicator).  From Perl one would use these functions in a\ncompletely different manner.\n\nOne conveys this info to xsubpp by replacing \"*\" before the argument by \"&\".  \"&\" means that\nthe argument should be passed to a library function by its address.  The above two function\nmay be XSUB-ified as\n\nint\nstringlength(s)\nchar *  s\n\nint\nuppercasechar(cp)\nchar    &cp\n\nFor example, consider:\n\nint\nfoo(a,b)\nchar    &a\nchar *  b\n\nThe first Perl argument to this function would be treated as a char and assigned to the\nvariable a, and its address would be passed into the function foo. The second Perl argument\nwould be treated as a string pointer and assigned to the variable b. The value of b would be\npassed into the function foo.  The actual call to the function foo that xsubpp generates\nwould look like this:\n\nfoo(&a, b);\n\nxsubpp will parse the following function argument lists identically:\n\nchar    &a\nchar&a\nchar    & a\n\nHowever, to help ease understanding, it is suggested that you place a \"&\" next to the\nvariable name and away from the variable type), and place a \"*\" near the variable type, but\naway from the variable name (as in the call to foo above).  By doing so, it is easy to\nunderstand exactly what will be passed to the C function; it will be whatever is in the \"last\ncolumn\".\n\nYou should take great pains to try to pass the function the type of variable it wants, when\npossible.  It will save you a lot of trouble in the long run.\n"
                    },
                    {
                        "name": "The Argument Stack",
                        "content": "If we look at any of the C code generated by any of the examples except example 1, you will\nnotice a number of references to ST(n), where n is usually 0.  \"ST\" is actually a macro that\npoints to the n'th argument on the argument stack.  ST(0) is thus the first argument on the\nstack and therefore the first argument passed to the XSUB, ST(1) is the second argument, and\nso on.\n\nWhen you list the arguments to the XSUB in the .xs file, that tells xsubpp which argument\ncorresponds to which of the argument stack (i.e., the first one listed is the first argument,\nand so on).  You invite disaster if you do not list them in the same order as the function\nexpects them.\n\nThe actual values on the argument stack are pointers to the values passed in.  When an\nargument is listed as being an OUTPUT value, its corresponding value on the stack (i.e.,\nST(0) if it was the first argument) is changed.  You can verify this by looking at the C code\ngenerated for Example 3.  The code for the round() XSUB routine contains lines that look like\nthis:\n\ndouble  arg = (double)SvNV(ST(0));\n/* Round the contents of the variable arg */\nsvsetnv(ST(0), (double)arg);\n\nThe arg variable is initially set by taking the value from ST(0), then is stored back into\nST(0) at the end of the routine.\n\nXSUBs are also allowed to return lists, not just scalars.  This must be done by manipulating\nstack values ST(0), ST(1), etc, in a subtly different way.  See perlxs for details.\n\nXSUBs are also allowed to avoid automatic conversion of Perl function arguments to C function\narguments.  See perlxs for details.  Some people prefer manual conversion by inspecting ST(i)\neven in the cases when automatic conversion will do, arguing that this makes the logic of an\nXSUB call clearer.  Compare with \"Getting the fat out of XSUBs\" for a similar tradeoff of a\ncomplete separation of \"Perl glue\" and \"workhorse\" parts of an XSUB.\n\nWhile experts may argue about these idioms, a novice to Perl guts may prefer a way which is\nas little Perl-guts-specific as possible, meaning automatic conversion and automatic call\ngeneration, as in \"Getting the fat out of XSUBs\".  This approach has the additional benefit\nof protecting the XSUB writer from future changes to the Perl API.\n"
                    },
                    {
                        "name": "Extending your Extension",
                        "content": "Sometimes you might want to provide some extra methods or subroutines to assist in making the\ninterface between Perl and your extension simpler or easier to understand.  These routines\nshould live in the .pm file.  Whether they are automatically loaded when the extension itself\nis loaded or only loaded when called depends on where in the .pm file the subroutine\ndefinition is placed.  You can also consult AutoLoader for an alternate way to store and load\nyour extra subroutines.\n"
                    },
                    {
                        "name": "Documenting your Extension",
                        "content": "There is absolutely no excuse for not documenting your extension.  Documentation belongs in\nthe .pm file.  This file will be fed to pod2man, and the embedded documentation will be\nconverted to the manpage format, then placed in the blib directory.  It will be copied to\nPerl's manpage directory when the extension is installed.\n\nYou may intersperse documentation and Perl code within the .pm file.  In fact, if you want to\nuse method autoloading, you must do this, as the comment inside the .pm file explains.\n\nSee perlpod for more information about the pod format.\n"
                    },
                    {
                        "name": "Installing your Extension",
                        "content": "Once your extension is complete and passes all its tests, installing it is quite simple: you\nsimply run \"make install\".  You will either need to have write permission into the\ndirectories where Perl is installed, or ask your system administrator to run the make for\nyou.\n\nAlternately, you can specify the exact directory to place the extension's files by placing a\n\"PREFIX=/destination/directory\" after the make install (or in between the make and install if\nyou have a brain-dead version of make).  This can be very useful if you are building an\nextension that will eventually be distributed to multiple systems.  You can then just archive\nthe files in the destination directory and distribute them to your destination systems.\n\nEXAMPLE 5\nIn this example, we'll do some more work with the argument stack.  The previous examples have\nall returned only a single value.  We'll now create an extension that returns an array.\n\nThis extension is very Unix-oriented (struct statfs and the statfs system call).  If you are\nnot running on a Unix system, you can substitute for statfs any other function that returns\nmultiple values, you can hard-code values to be returned to the caller (although this will be\na bit harder to test the error case), or you can simply not do this example.  If you change\nthe XSUB, be sure to fix the test cases to match the changes.\n\nReturn to the Mytest directory and add the following code to the end of Mytest.xs:\n\nvoid\nstatfs(path)\nchar *  path\nINIT:\nint i;\nstruct statfs buf;\n\nPPCODE:\ni = statfs(path, &buf);\nif (i == 0) {\nXPUSHs(sv2mortal(newSVnv(buf.fbavail)));\nXPUSHs(sv2mortal(newSVnv(buf.fbfree)));\nXPUSHs(sv2mortal(newSVnv(buf.fblocks)));\nXPUSHs(sv2mortal(newSVnv(buf.fbsize)));\nXPUSHs(sv2mortal(newSVnv(buf.fffree)));\nXPUSHs(sv2mortal(newSVnv(buf.ffiles)));\nXPUSHs(sv2mortal(newSVnv(buf.ftype)));\n} else {\nXPUSHs(sv2mortal(newSVnv(errno)));\n}\n\nYou'll also need to add the following code to the top of the .xs file, just after the include\nof \"XSUB.h\":\n\n#include <sys/vfs.h>\n\nAlso add the following code segment to Mytest.t while incrementing the \"9\" tests to \"11\":\n\nmy @a;\n\n@a = Mytest::statfs(\"/blech\");\nok( scalar(@a) == 1 && $a[0] == 2 );\n\n@a = Mytest::statfs(\"/\");\nis( scalar(@a), 7 );\n"
                    },
                    {
                        "name": "New Things in this Example",
                        "content": "This example added quite a few new concepts.  We'll take them one at a time.\n\n•   The INIT: directive contains code that will be placed immediately after the argument\nstack is decoded.  C does not allow variable declarations at arbitrary locations inside a\nfunction, so this is usually the best way to declare local variables needed by the XSUB.\n(Alternatively, one could put the whole \"PPCODE:\" section into braces, and put these\ndeclarations on top.)\n\n•   This routine also returns a different number of arguments depending on the success or\nfailure of the call to statfs.  If there is an error, the error number is returned as a\nsingle-element array.  If the call is successful, then a 7-element array is returned.\nSince only one argument is passed into this function, we need room on the stack to hold\nthe 7 values which may be returned.\n\nWe do this by using the PPCODE: directive, rather than the CODE: directive.  This tells\nxsubpp that we will be managing the return values that will be put on the argument stack\nby ourselves.\n\n•   When we want to place values to be returned to the caller onto the stack, we use the\nseries of macros that begin with \"XPUSH\".  There are five different versions, for placing\nintegers, unsigned integers, doubles, strings, and Perl scalars on the stack.  In our\nexample, we placed a Perl scalar onto the stack.  (In fact this is the only macro which\ncan be used to return multiple values.)\n\nThe XPUSH* macros will automatically extend the return stack to prevent it from being\noverrun.  You push values onto the stack in the order you want them seen by the calling\nprogram.\n\n•   The values pushed onto the return stack of the XSUB are actually mortal SV's.  They are\nmade mortal so that once the values are copied by the calling program, the SV's that held\nthe returned values can be deallocated.  If they were not mortal, then they would\ncontinue to exist after the XSUB routine returned, but would not be accessible.  This is\na memory leak.\n\n•   If we were interested in performance, not in code compactness, in the success branch we\nwould not use \"XPUSHs\" macros, but \"PUSHs\" macros, and would pre-extend the stack before\npushing the return values:\n\nEXTEND(SP, 7);\n\nThe tradeoff is that one needs to calculate the number of return values in advance\n(though overextending the stack will not typically hurt anything but memory consumption).\n\nSimilarly, in the failure branch we could use \"PUSHs\" without extending the stack: the\nPerl function reference comes to an XSUB on the stack, thus the stack is always large\nenough to take one return value.\n\nEXAMPLE 6\nIn this example, we will accept a reference to an array as an input parameter, and return a\nreference to an array of hashes.  This will demonstrate manipulation of complex Perl data\ntypes from an XSUB.\n\nThis extension is somewhat contrived.  It is based on the code in the previous example.  It\ncalls the statfs function multiple times, accepting a reference to an array of filenames as\ninput, and returning a reference to an array of hashes containing the data for each of the\nfilesystems.\n\nReturn to the Mytest directory and add the following code to the end of Mytest.xs:\n\nSV *\nmultistatfs(paths)\nSV * paths\nINIT:\nAV * results;\nSSizet numpaths = 0, n;\nint i;\nstruct statfs buf;\n\nSvGETMAGIC(paths);\nif ((!SvROK(paths))\n|| (SvTYPE(SvRV(paths)) != SVtPVAV)\n|| ((numpaths = avtopindex((AV *)SvRV(paths))) < 0))\n{\nXSRETURNUNDEF;\n}\nresults = (AV *)sv2mortal((SV *)newAV());\nCODE:\nfor (n = 0; n <= numpaths; n++) {\nHV * rh;\nSTRLEN l;\nSV * path = *avfetch((AV *)SvRV(paths), n, 0);\nchar * fn = SvPVbyte(path, l);\n\ni = statfs(fn, &buf);\nif (i != 0) {\navpush(results, newSVnv(errno));\ncontinue;\n}\n\nrh = (HV *)sv2mortal((SV *)newHV());\n\nhvstore(rh, \"fbavail\", 8, newSVnv(buf.fbavail), 0);\nhvstore(rh, \"fbfree\",  7, newSVnv(buf.fbfree),  0);\nhvstore(rh, \"fblocks\", 8, newSVnv(buf.fblocks), 0);\nhvstore(rh, \"fbsize\",  7, newSVnv(buf.fbsize),  0);\nhvstore(rh, \"fffree\",  7, newSVnv(buf.fffree),  0);\nhvstore(rh, \"ffiles\",  7, newSVnv(buf.ffiles),  0);\nhvstore(rh, \"ftype\",   6, newSVnv(buf.ftype),   0);\n\navpush(results, newRVinc((SV *)rh));\n}\nRETVAL = newRVinc((SV *)results);\nOUTPUT:\nRETVAL\n\nAnd add the following code to Mytest.t, while incrementing the \"11\" tests to \"13\":\n\nmy $results = Mytest::multistatfs([ '/', '/blech' ]);\nok( ref $results->[0] );\nok( ! ref $results->[1] );\n"
                    },
                    {
                        "name": "New Things in this Example",
                        "content": "There are a number of new concepts introduced here, described below:\n\n•   This function does not use a typemap.  Instead, we declare it as accepting one SV*\n(scalar) parameter, and returning an SV* value, and we take care of populating these\nscalars within the code.  Because we are only returning one value, we don't need a\n\"PPCODE:\" directive - instead, we use \"CODE:\" and \"OUTPUT:\" directives.\n\n•   When dealing with references, it is important to handle them with caution.  The \"INIT:\"\nblock first calls SvGETMAGIC(paths), in case paths is a tied variable.  Then it checks\nthat \"SvROK\" returns true, which indicates that paths is a valid reference.  (Simply\nchecking \"SvROK\" won't trigger FETCH on a tied variable.)  It then verifies that the\nobject referenced by paths is an array, using \"SvRV\" to dereference paths, and \"SvTYPE\"\nto discover its type.  As an added test, it checks that the array referenced by paths is\nnon-empty, using the \"avtopindex\" function (which returns -1 if the array is empty).\nThe XSRETURNUNDEF macro is used to abort the XSUB and return the undefined value\nwhenever all three of these conditions are not met.\n\n•   We manipulate several arrays in this XSUB.  Note that an array is represented internally\nby an AV* pointer.  The functions and macros for manipulating arrays are similar to the\nfunctions in Perl: \"avtopindex\" returns the highest index in an AV*, much like $#array;\n\"avfetch\" fetches a single scalar value from an array, given its index; \"avpush\" pushes\na scalar value onto the end of the array, automatically extending the array as necessary.\n\nSpecifically, we read pathnames one at a time from the input array, and store the results\nin an output array (results) in the same order.  If statfs fails, the element pushed onto\nthe return array is the value of errno after the failure.  If statfs succeeds, though,\nthe value pushed onto the return array is a reference to a hash containing some of the\ninformation in the statfs structure.\n\nAs with the return stack, it would be possible (and a small performance win) to pre-\nextend the return array before pushing data into it, since we know how many elements we\nwill return:\n\navextend(results, numpaths);\n\n•   We are performing only one hash operation in this function, which is storing a new scalar\nunder a key using \"hvstore\".  A hash is represented by an HV* pointer.  Like arrays, the\nfunctions for manipulating hashes from an XSUB mirror the functionality available from\nPerl.  See perlguts and perlapi for details.\n\n•   To create a reference, we use the \"newRVinc\" function.  Note that you can cast an AV* or\nan HV* to type SV* in this case (and many others).  This allows you to take references to\narrays, hashes and scalars with the same function.  Conversely, the \"SvRV\" function\nalways returns an SV*, which may need to be cast to the appropriate type if it is\nsomething other than a scalar (check with \"SvTYPE\").\n\n•   At this point, xsubpp is doing very little work - the differences between Mytest.xs and\nMytest.c are minimal.\n"
                    },
                    {
                        "name": "EXAMPLE 7 (Coming Soon)",
                        "content": "XPUSH args AND set RETVAL AND assign return value to array\n"
                    },
                    {
                        "name": "EXAMPLE 8 (Coming Soon)",
                        "content": "Setting $!\n"
                    },
                    {
                        "name": "EXAMPLE 9 Passing open files to XSes",
                        "content": "You would think passing files to an XS is difficult, with all the typeglobs and stuff. Well,\nit isn't.\n\nSuppose that for some strange reason we need a wrapper around the standard C library function\n\"fputs()\". This is all we need:\n\n#define PERLIONOTSTDIO 0  /* For co-existence with stdio only */\n#define PERLNOGETCONTEXT /* This is more efficient */\n#include \"EXTERN.h\"\n#include \"perl.h\"\n#include \"XSUB.h\"\n\n#include <stdio.h>\n\nint\nfputs(s, stream)\nchar *          s\nFILE *          stream\n\nThe real work is done in the standard typemap.\n\nFor more details, see \"Co-existence with stdio\" in perlapio.\n\nBut you lose all the fine stuff done by the perlio layers. This calls the stdio function\n\"fputs()\", which knows nothing about them.\n\nThe standard typemap offers three variants of PerlIO *: \"InputStream\" (TIN), \"InOutStream\"\n(TINOUT) and \"OutputStream\" (TOUT). A bare \"PerlIO *\" is considered a TINOUT. If it\nmatters in your code (see below for why it might) #define or typedef one of the specific\nnames and use that as the argument or result type in your XS file.\n\nThe standard typemap does not contain PerlIO * before perl 5.7, but it has the three stream\nvariants. Using a PerlIO * directly is not backwards compatible unless you provide your own\ntypemap.\n\nFor streams coming from perl the main difference is that \"OutputStream\" will get the output\nPerlIO * - which may make a difference on a socket. Like in our example...\n\nFor streams being handed to perl a new file handle is created (i.e. a reference to a new\nglob) and associated with the PerlIO * provided. If the read/write state of the PerlIO * is\nnot correct then you may get errors or warnings from when the file handle is used.  So if you\nopened the PerlIO * as \"w\" it should really be an \"OutputStream\" if open as \"r\" it should be\nan \"InputStream\".\n\nNow, suppose you want to use perlio layers in your XS. We'll use the perlio \"PerlIOputs()\"\nfunction as an example.\n\nIn the C part of the XS file (above the first MODULE line) you have\n\n#define OutputStream    PerlIO *\nor\ntypedef PerlIO *        OutputStream;\n\nAnd this is the XS code:\n\nint\nperlioputs(s, stream)\nchar *          s\nOutputStream    stream\nCODE:\nRETVAL = PerlIOputs(stream, s);\nOUTPUT:\nRETVAL\n\nWe have to use a \"CODE\" section because \"PerlIOputs()\" has the arguments reversed compared\nto \"fputs()\", and we want to keep the arguments the same.\n\nWanting to explore this thoroughly, we want to use the stdio \"fputs()\" on a PerlIO *. This\nmeans we have to ask the perlio system for a stdio \"FILE *\":\n\nint\nperliofputs(s, stream)\nchar *          s\nOutputStream    stream\nPREINIT:\nFILE *fp = PerlIOfindFILE(stream);\nCODE:\nif (fp != (FILE*) 0) {\nRETVAL = fputs(s, fp);\n} else {\nRETVAL = -1;\n}\nOUTPUT:\nRETVAL\n\nNote: \"PerlIOfindFILE()\" will search the layers for a stdio layer. If it can't find one, it\nwill call \"PerlIOexportFILE()\" to generate a new stdio \"FILE\". Please only call\n\"PerlIOexportFILE()\" if you want a new \"FILE\". It will generate one on each call and push a\nnew stdio layer. So don't call it repeatedly on the same file. \"PerlIOfindFILE()\" will\nretrieve the stdio layer once it has been generated by \"PerlIOexportFILE()\".\n\nThis applies to the perlio system only. For versions before 5.7, \"PerlIOexportFILE()\" is\nequivalent to \"PerlIOfindFILE()\".\n"
                    },
                    {
                        "name": "Troubleshooting these Examples",
                        "content": "As mentioned at the top of this document, if you are having problems with these example\nextensions, you might see if any of these help you.\n\n•   In versions of 5.002 prior to the gamma version, the test script in Example 1 will not\nfunction properly.  You need to change the \"use lib\" line to read:\n\nuse lib './blib';\n\n•   In versions of 5.002 prior to version 5.002b1h, the test.pl file was not automatically\ncreated by h2xs.  This means that you cannot say \"make test\" to run the test script.  You\nwill need to add the following line before the \"use extension\" statement:\n\nuse lib './blib';\n\n•   In versions 5.000 and 5.001, instead of using the above line, you will need to use the\nfollowing line:\n\nBEGIN { unshift(@INC, \"./blib\") }\n\n•   This document assumes that the executable named \"perl\" is Perl version 5.  Some systems\nmay have installed Perl version 5 as \"perl5\".\n"
                    },
                    {
                        "name": "See also",
                        "content": "For more information, consult perlguts, perlapi, perlxs, perlmod, perlapio, and perlpod\n"
                    }
                ]
            },
            "Author": {
                "content": "Jeff Okamoto <okamoto@corp.hp.com>\n\nReviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig, and Tim Bunce.\n\nPerlIO material contributed by Lupe Christoph, with some clarification by Nick Ing-Simmons.\n\nChanges for h2xs as of Perl 5.8.x by Renee Baecker\n\nThis document is now maintained as part of Perl itself.\n",
                "subsections": [
                    {
                        "name": "Last Changed",
                        "content": "2020-10-05\n\n\n\nperl v5.34.0                                 2026-06-23                                 PERLXSTUT(1)"
                    }
                ]
            }
        }
    }
}