home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 2 / AACD 2.iso / AACD / Programming / perlman / man / perlxstut.txt < prev   
Encoding:
Text File  |  1999-09-09  |  30.4 KB  |  792 lines

  1. NAME
  2.        perlXStut - Tutorial for XSUB's
  3.  
  4. DESCRIPTION
  5.        This tutorial will educate the reader on the steps
  6.        involved in creating a Perl extension.  The reader is
  7.        assumed to have access to the perlguts manpage and the
  8.        perlxs manpage.
  9.  
  10.        This tutorial starts with very simple examples and becomes
  11.        more complex, with each new example adding new features.
  12.        Certain concepts may not be completely explained until
  13.        later in the tutorial in order to slowly ease the reader
  14.        into building extensions.
  15.  
  16.        VERSION CAVEAT
  17.  
  18.        This tutorial tries hard to keep up with the latest
  19.        development versions of Perl.  This often means that it is
  20.        sometimes in advance of the latest released version of
  21.        Perl, and that certain features described here might not
  22.        work on earlier versions.  This section will keep track of
  23.        when various features were added to Perl 5.
  24.  
  25.        o   In versions of 5.002 prior to version beta 3, then the
  26.            line in the .xs file about "PROTOTYPES: DISABLE" will
  27.            cause a compiler error.  Simply remove that line from
  28.            the file.
  29.  
  30.        o   In versions of 5.002 prior to version 5.002b1h, the
  31.            test.pl file was not automatically created by h2xs.
  32.            This means that you cannot say "make test" to run the
  33.            test script.  You will need to add the following line
  34.            before the "use extension" statement:
  35.  
  36.                    use lib './blib';
  37.  
  38.        o   In versions 5.000 and 5.001, instead of using the
  39.            above line, you will need to use the following line:
  40.  
  41.                    BEGIN { unshift(@INC, "./blib") }
  42.  
  43.        o   This document assumes that the executable named "perl"
  44.            is Perl version 5.  Some systems may have installed
  45.            Perl version 5 as "perl5".
  46.  
  47.        DYNAMIC VERSUS STATIC
  48.  
  49.        It is commonly thought that if a system does not have the
  50.        capability to dynamically load a library, you cannot build
  51.        XSUB's.  This is incorrect.  You can build them, but you
  52.        must link the XSUB's subroutines with the rest of Perl,
  53.        creating a new executable.  This situation is similar to
  54.        Perl 4.
  55.  
  56.        This tutorial can still be used on such a system.  The
  57.        XSUB build mechanism will check the system and build a
  58.        dynamically-loadable library if possible, or else a static
  59.        library and then, optionally, a new statically-linked
  60.        executable with that static library linked in.
  61.  
  62.        Should you wish to build a statically-linked executable on
  63.        a system which can dynamically load libraries, you may, in
  64.        all the following examples, where the command "make" with
  65.        no arguments is executed, run the command "make perl"
  66.        instead.
  67.  
  68.        If you have generated such a statically-linked executable
  69.        by choice, then instead of saying "make test", you should
  70.        say "make test_static".  On systems that cannot build
  71.        dynamically-loadable libraries at all, simply saying "make
  72.        test" is sufficient.
  73.  
  74.        EXAMPLE 1
  75.  
  76.        Our first extension will be very simple.  When we call the
  77.        routine in the extension, it will print out a well-known
  78.        message and return.
  79.  
  80.        Run "h2xs -A -n Mytest".  This creates a directory named
  81.        Mytest, possibly under ext/ if that directory exists in
  82.        the current working directory.  Several files will be
  83.        created in the Mytest dir, including MANIFEST,
  84.        Makefile.PL, Mytest.pm, Mytest.xs, test.pl, and Changes.
  85.  
  86.        The MANIFEST file contains the names of all the files
  87.        created.
  88.  
  89.        The file Makefile.PL should look something like this:
  90.  
  91.                use ExtUtils::MakeMaker;
  92.                # See lib/ExtUtils/MakeMaker.pm for details of how to influence
  93.                # the contents of the Makefile that is written.
  94.                WriteMakefile(
  95.                    'NAME'      => 'Mytest',
  96.                    'VERSION_FROM' => 'Mytest.pm', # finds $VERSION
  97.                    'LIBS'      => [''],   # e.g., '-lm'
  98.                    'DEFINE'    => '',     # e.g., '-DHAVE_SOMETHING'
  99.                    'INC'       => '',     # e.g., '-I/usr/include/other'
  100.                );
  101.  
  102.        The file Mytest.pm should start with something like this:
  103.  
  104.                package Mytest;
  105.  
  106.                require Exporter;
  107.                require DynaLoader;
  108.  
  109.                @ISA = qw(Exporter DynaLoader);
  110.                # Items to export into callers namespace by default. Note: do not export
  111.                # names by default without a very good reason. Use EXPORT_OK instead.
  112.                # Do not simply export all your public functions/methods/constants.
  113.                @EXPORT = qw(
  114.  
  115.                );
  116.                $VERSION = '0.01';
  117.  
  118.                bootstrap Mytest $VERSION;
  119.  
  120.                # Preloaded methods go here.
  121.  
  122.                # Autoload methods go after __END__, and are processed by the autosplit program.
  123.  
  124.                1;
  125.                __END__
  126.                # Below is the stub of documentation for your module. You better edit it!
  127.  
  128.        And the Mytest.xs file should look something like this:
  129.  
  130.                #ifdef __cplusplus
  131.                extern "C" {
  132.                #endif
  133.                #include "EXTERN.h"
  134.                #include "perl.h"
  135.                #include "XSUB.h"
  136.                #ifdef __cplusplus
  137.                }
  138.                #endif
  139.  
  140.                PROTOTYPES: DISABLE
  141.  
  142.                MODULE = Mytest         PACKAGE = Mytest
  143.  
  144.        Let's edit the .xs file by adding this to the end of the
  145.        file:
  146.  
  147.                void
  148.                hello()
  149.                        CODE:
  150.                        printf("Hello, world!\n");
  151.  
  152.        Now we'll run "perl Makefile.PL".  This will create a real
  153.        Makefile, which make needs.  It's output looks something
  154.        like:
  155.  
  156.                % perl Makefile.PL
  157.                Checking if your kit is complete...
  158.                Looks good
  159.                Writing Makefile for Mytest
  160.                %
  161.  
  162.        Now, running make will produce output that looks something
  163.        like this (some long lines shortened for clarity):
  164.  
  165.                % make
  166.                umask 0 && cp Mytest.pm ./blib/Mytest.pm
  167.                perl xsubpp -typemap typemap Mytest.xs >Mytest.tc && mv Mytest.tc Mytest.c
  168.                cc -c Mytest.c
  169.                Running Mkbootstrap for Mytest ()
  170.                chmod 644 Mytest.bs
  171.                LD_RUN_PATH="" ld -o ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl -b Mytest.o
  172.                chmod 755 ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl
  173.                cp Mytest.bs ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
  174.                chmod 644 ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
  175.  
  176.        Now, although there is already a test.pl template ready
  177.        for us, for this example only, we'll create a special test
  178.        script.  Create a file called hello that looks like this:
  179.  
  180.                #! /opt/perl5/bin/perl
  181.  
  182.                use lib './blib';
  183.  
  184.                use Mytest;
  185.  
  186.                Mytest::hello();
  187.  
  188.        Now we run the script and we should see the following
  189.        output:
  190.  
  191.                % perl hello
  192.                Hello, world!
  193.                %
  194.  
  195.        EXAMPLE 2
  196.  
  197.        Now let's add to our extension a subroutine that will take
  198.        a single argument and return 0 if the argument is even, 1
  199.        if the argument is odd.
  200.  
  201.        Add the following to the end of Mytest.xs:
  202.  
  203.                int
  204.                is_even(input)
  205.                        int     input
  206.                        CODE:
  207.                        RETVAL = (input % 2 == 0);
  208.                        OUTPUT:
  209.                        RETVAL
  210.  
  211.        There does not need to be white space at the start of the
  212.        "int input" line, but it is useful for improving
  213.        readability.  The semi-colon at the end of that line is
  214.        also optional.
  215.  
  216.        Any white space may be between the "int" and "input".  It
  217.        is also okay for the four lines starting at the "CODE:"
  218.        line to not be indented.  However, for readability
  219.        purposes, it is suggested that you indent them 8 spaces
  220.        (or one normal tab stop).
  221.  
  222.        Now re-run make to rebuild our new shared library.
  223.  
  224.        Now perform the same steps as before, generating a
  225.        Makefile from the Makefile.PL file, and running make.
  226.  
  227.        In order to test that our extension works, we now need to
  228.        look at the file test.pl.  This file is set up to imitate
  229.        the same kind of testing structure that Perl itself has.
  230.        Within the test script, you perform a number of tests to
  231.        confirm the behavior of the extension, printing "ok" when
  232.        the test is correct, "not ok" when it is not.
  233.  
  234.        Remove the line that starts with "use lib", change the
  235.        print statement in the BEGIN block to print "1..4", and
  236.        add the following code to the end of the file:
  237.  
  238.                print &Mytest::is_even(0) == 1 ? "ok 2" : "not ok 2", "\n";
  239.                print &Mytest::is_even(1) == 0 ? "ok 3" : "not ok 3", "\n";
  240.                print &Mytest::is_even(2) == 1 ? "ok 4" : "not ok 4", "\n";
  241.  
  242.        We will be calling the test script through the command
  243.        "make test".  You should see output that looks something
  244.        like this:
  245.  
  246.                % make test
  247.                PERL_DL_NONLAZY=1 /opt/perl5.002b2/bin/perl (lots of -I arguments) test.pl
  248.                1..4
  249.                ok 1
  250.                ok 2
  251.                ok 3
  252.                ok 4
  253.                %
  254.  
  255.        WHAT HAS GONE ON?
  256.  
  257.        The program h2xs is the starting point for creating
  258.        extensions.  In later examples we'll see how we can use
  259.        h2xs to read header files and generate templates to
  260.        connect to C routines.
  261.  
  262.        h2xs creates a number of files in the extension directory.
  263.        The file Makefile.PL is a perl script which will generate
  264.        a true Makefile to build the extension.  We'll take a
  265.        closer look at it later.
  266.  
  267.        The files <extension>.pm and <extension>.xs contain the
  268.        meat of the extension.  The .xs file holds the C routines
  269.        that make up the extension.  The .pm file contains
  270.        routines that tell Perl how to load your extension.
  271.  
  272.        Generating and invoking the Makefile created a directory
  273.        blib (which stands for "build library") in the current
  274.        working directory.  This directory will contain the shared
  275.        library that we will build.  Once we have tested it, we
  276.        can install it into its final location.
  277.  
  278.        Invoking the test script via "make test" did something
  279.        very important.  It invoked perl with all those -I
  280.        arguments so that it could find the various files that are
  281.        part of the extension.
  282.  
  283.        It is very important that while you are still testing
  284.        extensions that you use "make test".  If you try to run
  285.        the test script all by itself, you will get a fatal error.
  286.  
  287.        Another reason it is important to use "make test" to run
  288.        your test script is that if you are testing an upgrade to
  289.        an already-existing version, using "make test" insures
  290.        that you use your new extension, not the already-existing
  291.        version.
  292.  
  293.        When Perl sees a use extension;, it searches for a file
  294.        with the same name as the use'd extension that has a .pm
  295.        suffix.  If that file cannot be found, Perl dies with a
  296.        fatal error.  The default search path is contained in the
  297.        @INC array.
  298.  
  299.        In our case, Mytest.pm tells perl that it will need the
  300.        Exporter and Dynamic Loader extensions.  It then sets the
  301.        @ISA and @EXPORT arrays and the $VERSION scalar; finally
  302.        it tells perl to bootstrap the module.  Perl will call its
  303.        dynamic loader routine (if there is one) and load the
  304.        shared library.
  305.  
  306.        The two arrays that are set in the .pm file are very
  307.        important.  The @ISA array contains a list of other
  308.        packages in which to search for methods (or subroutines)
  309.        that do not exist in the current package.  The @EXPORT
  310.        array tells Perl which of the extension's routines should
  311.        be placed into the calling package's namespace.
  312.  
  313.        It's important to select what to export carefully.  Do NOT
  314.        export method names and do NOT export anything else by
  315.        default without a good reason.
  316.  
  317.        As a general rule, if the module is trying to be object-
  318.        oriented then don't export anything.  If it's just a
  319.        collection of functions then you can export any of the
  320.        functions via another array, called @EXPORT_OK.
  321.  
  322.        See the perlmod manpage for more information.
  323.  
  324.        The $VERSION variable is used to ensure that the .pm file
  325.        and the shared library are "in sync" with each other.  Any
  326.        time you make changes to the .pm or .xs files, you should
  327.        increment the value of this variable.
  328.  
  329.        WRITING GOOD TEST SCRIPTS
  330.  
  331.        The importance of writing good test scripts cannot be
  332.        overemphasized.  You should closely follow the "ok/not ok"
  333.        style that Perl itself uses, so that it is very easy and
  334.        unambiguous to determine the outcome of each test case.
  335.        When you find and fix a bug, make sure you add a test case
  336.        for it.
  337.  
  338.        By running "make test", you ensure that your test.pl
  339.        script runs and uses the correct version of your
  340.        extension.  If you have many test cases, you might want to
  341.        copy Perl's test style.  Create a directory named "t", and
  342.        ensure all your test files end with the suffix ".t".  The
  343.        Makefile will properly run all these test files.
  344.  
  345.        EXAMPLE 3
  346.  
  347.        Our third extension will take one argument as its input,
  348.        round off that value, and set the argument to the rounded
  349.        value.
  350.  
  351.        Add the following to the end of Mytest.xs:
  352.  
  353.                void
  354.                round(arg)
  355.                        double  arg
  356.                        CODE:
  357.                        if (arg > 0.0) {
  358.                                arg = floor(arg + 0.5);
  359.                        } else if (arg < 0.0) {
  360.                                arg = ceil(arg - 0.5);
  361.                        } else {
  362.                                arg = 0.0;
  363.                        }
  364.                        OUTPUT:
  365.                        arg
  366.  
  367.        Edit the Makefile.PL file so that the corresponding line
  368.        looks like this:
  369.  
  370.                'LIBS'      => ['-lm'],   # e.g., '-lm'
  371.  
  372.        Generate the Makefile and run make.  Change the BEGIN
  373.        block to print out "1..9" and add the following to
  374.        test.pl:
  375.  
  376.                $i = -1.5; &Mytest::round($i); print $i == -2.0 ? "ok 5" : "not ok 5", "\n";
  377.                $i = -1.1; &Mytest::round($i); print $i == -1.0 ? "ok 6" : "not ok 6", "\n";
  378.                $i = 0.0; &Mytest::round($i); print $i == 0.0 ? "ok 7" : "not ok 7", "\n";
  379.                $i = 0.5; &Mytest::round($i); print $i == 1.0 ? "ok 8" : "not ok 8", "\n";
  380.                $i = 1.2; &Mytest::round($i); print $i == 1.0 ? "ok 9" : "not ok 9", "\n";
  381.  
  382.        Running "make test" should now print out that all nine
  383.        tests are okay.
  384.  
  385.        You might be wondering if you can round a constant.  To
  386.        see what happens, add the following line to test.pl
  387.        temporarily:
  388.  
  389.                &Mytest::round(3);
  390.  
  391.        Run "make test" and notice that Perl dies with a fatal
  392.        error.  Perl won't let you change the value of constants!
  393.  
  394.        WHAT'S NEW HERE?
  395.  
  396.        Two things are new here.  First, we've made some changes
  397.        to Makefile.PL.  In this case, we've specified an extra
  398.        library to link in, in this case the math library, libm.
  399.        We'll talk later about how to write XSUBs that can call
  400.        every routine in a library.
  401.  
  402.        Second, the value of the function is being passed back not
  403.        as the function's return value, but through the same
  404.        variable that was passed into the function.
  405.  
  406.        INPUT AND OUTPUT PARAMETERS
  407.  
  408.        You specify the parameters that will be passed into the
  409.        XSUB just after you declare the function return value and
  410.        name.  Each parameter line starts with optional white
  411.        space, and may have an optional terminating semicolon.
  412.  
  413.        The list of output parameters occurs after the OUTPUT:
  414.        directive.  The use of RETVAL tells Perl that you wish to
  415.        send this value back as the return value of the XSUB
  416.        function.  In Example 3, the value we wanted returned was
  417.        contained in the same variable we passed in, so we listed
  418.        it (and not RETVAL) in the OUTPUT: section.
  419.  
  420.        THE XSUBPP COMPILER
  421.  
  422.        The compiler xsubpp takes the XS code in the .xs file and
  423.        converts it into C code, placing it in a file whose suffix
  424.        is .c.  The C code created makes heavy use of the C
  425.        functions within Perl.
  426.  
  427.        THE TYPEMAP FILE
  428.  
  429.        The xsubpp compiler uses rules to convert from Perl's data
  430.        types (scalar, array, etc.) to C's data types (int, char
  431.        *, etc.).  These rules are stored in the typemap file
  432.        ($PERLLIB/ExtUtils/typemap).  This file is split into
  433.        three parts.
  434.  
  435.        The first part attempts to map various C data types to a
  436.        coded flag, which has some correspondence with the various
  437.        Perl types.  The second part contains C code which xsubpp
  438.        uses for input parameters.  The third part contains C code
  439.        which xsubpp uses for output parameters.  We'll talk more
  440.        about the C code later.
  441.  
  442.        Let's now take a look at a portion of the .c file created
  443.        for our extension.
  444.  
  445.                XS(XS_Mytest_round)
  446.                {
  447.                    dXSARGS;
  448.                    if (items != 1)
  449.                        croak("Usage: Mytest::round(arg)");
  450.                    {
  451.                        double  arg = (double)SvNV(ST(0));      /* XXXXX */
  452.                        if (arg > 0.0) {
  453.                                arg = floor(arg + 0.5);
  454.                        } else if (arg < 0.0) {
  455.                                arg = ceil(arg - 0.5);
  456.                        } else {
  457.                                arg = 0.0;
  458.                        }
  459.                        sv_setnv(ST(0), (double)arg);   /* XXXXX */
  460.                    }
  461.                    XSRETURN(1);
  462.                }
  463.  
  464.        Notice the two lines marked with "XXXXX".  If you check
  465.        the first section of the typemap file, you'll see that
  466.        doubles are of type T_DOUBLE.  In the INPUT section, an
  467.        argument that is T_DOUBLE is assigned to the variable arg
  468.        by calling the routine SvNV on something, then casting it
  469.        to double, then assigned to the variable arg.  Similarly,
  470.        in the OUTPUT section, once arg has its final value, it is
  471.        passed to the sv_setnv function to be passed back to the
  472.        calling subroutine.  These two functions are explained in
  473.        the perlguts manpage; we'll talk more later about what
  474.        that "ST(0)" means in the section on the argument stack.
  475.  
  476.        WARNING
  477.  
  478.        In general, it's not a good idea to write extensions that
  479.        modify their input parameters, as in Example 3.  However,
  480.        in order to better accomodate calling pre-existing C
  481.        routines, which often do modify their input parameters,
  482.        this behavior is tolerated.
  483.  
  484.        EXAMPLE 4
  485.  
  486.        In this example, we'll now begin to write XSUB's that will
  487.        interact with pre-defined C libraries.  To begin with, we
  488.        will build a small library of our own, then let h2xs write
  489.        our .pm and .xs files for us.
  490.  
  491.        Create a new directory called Mytest2 at the same level as
  492.        the directory Mytest.  In the Mytest2 directory, create
  493.        another directory called mylib, and cd into that
  494.        directory.
  495.  
  496.        Here we'll create some files that will generate a test
  497.        library.  These will include a C source file and a header
  498.        file.  We'll also create a Makefile.PL in this directory.
  499.        Then we'll make sure that running make at the Mytest2
  500.        level will automatically run this Makefile.PL file and the
  501.        resulting Makefile.
  502.  
  503.        In the testlib directory, create a file mylib.h that looks
  504.        like this:
  505.  
  506.                #define TESTVAL 4
  507.  
  508.                extern double   foo(int, long, const char*);
  509.  
  510.        Also create a file mylib.c that looks like this:
  511.  
  512.                #include <stdlib.h>
  513.                #include "./mylib.h"
  514.  
  515.                double
  516.                foo(a, b, c)
  517.                int             a;
  518.                long            b;
  519.                const char *    c;
  520.                {
  521.                        return (a + b + atof(c) + TESTVAL);
  522.                }
  523.  
  524.        And finally create a file Makefile.PL that looks like
  525.        this:
  526.  
  527.                use ExtUtils::MakeMaker;
  528.                $Verbose = 1;
  529.                WriteMakefile(
  530.                    'NAME' => 'Mytest2::mylib',
  531.                    'clean'     => {'FILES' => 'libmylib.a'},
  532.                );
  533.  
  534.                sub MY::postamble {
  535.                        '
  536.                all :: static
  537.  
  538.                static ::       libmylib$(LIB_EXT)
  539.  
  540.                libmylib$(LIB_EXT): $(O_FILES)
  541.                        $(AR) cr libmylib$(LIB_EXT) $(O_FILES)
  542.                        $(RANLIB) libmylib$(LIB_EXT)
  543.  
  544.                ';
  545.                }
  546.  
  547.        We will now create the main top-level Mytest2 files.
  548.        Change to the directory above Mytest2 and run the
  549.        following command:
  550.  
  551.                % h2xs -O -n Mytest2 < ./Mytest2/mylib/mylib.h
  552.  
  553.        This will print out a warning about overwriting Mytest2,
  554.        but that's okay.  Our files are stored in Mytest2/mylib,
  555.        and will be untouched.
  556.  
  557.        The normal Makefile.PL that h2xs generates doesn't know
  558.        about the mylib directory.  We need to tell it that there
  559.        is a subdirectory and that we will be generating a library
  560.        in it.  Let's add the following key-value pair to the
  561.        WriteMakefile call:
  562.  
  563.                'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)',
  564.  
  565.        and a new replacement subroutine too:
  566.  
  567.                sub MY::postamble {
  568.                '
  569.                $(MYEXTLIB): mylib/Makefile
  570.                        cd mylib && $(MAKE)
  571.                ';
  572.                }
  573.  
  574.        (Note: Most makes will require that there be a tab
  575.        character that indents the line "cd mylib && $(MAKE)".)
  576.  
  577.        Let's also fix the MANIFEST file so that it accurately
  578.        reflects the contents of our extension.  The single line
  579.        that says "mylib" should be replaced by the following
  580.        three lines:
  581.  
  582.                mylib/Makefile.PL
  583.                mylib/mylib.c
  584.                mylib/mylib.h
  585.  
  586.        To keep our namespace nice and unpolluted, edit the .pm
  587.        file and change the line setting @EXPORT to @EXPORT_OK.
  588.        And finally, in the .xs file, edit the #include line to
  589.        read:
  590.  
  591.                #include "mylib/mylib.h"
  592.  
  593.        And also add the following function definition to the end
  594.        of the .xs file:
  595.  
  596.                double
  597.                foo(a,b,c)
  598.                        int             a
  599.                        long            b
  600.                        const char *    c
  601.                        OUTPUT:
  602.                        RETVAL
  603.  
  604.        Now we also need to create a typemap file because the
  605.        default Perl doesn't currently support the const char *
  606.        type.  Create a file called typemap and place the
  607.        following in it:
  608.  
  609.                const char *    T_PV
  610.  
  611.        Now run perl on the top-level Makefile.PL.  Notice that it
  612.        also created a Makefile in the mylib directory.  Run make
  613.        and see that it does cd into the mylib directory and run
  614.        make in there as well.
  615.  
  616.        Now edit the test.pl script and change the BEGIN block to
  617.        print "1..4", and add the following lines to the end of
  618.        the script:
  619.  
  620.                print &Mytest2::foo(1, 2, "Hello, world!") == 7 ? "ok 2\n" : "not ok 2\n";
  621.                print &Mytest2::foo(1, 2, "0.0") == 7 ? "ok 3\n" : "not ok 3\n";
  622.                print abs(&Mytest2::foo(0, 0, "-3.4") - 0.6) <= 0.01 ? "ok 4\n" : "not ok 4\n";
  623.  
  624.        (When dealing with floating-point comparisons, it is often
  625.        useful to not check for equality, but rather the
  626.        difference being below a certain epsilon factor, 0.01 in
  627.        this case)
  628.  
  629.        Run "make test" and all should be well.  Unlike previous
  630.        examples, we've now run h2xs on a real include file.  This
  631.        has caused some extra goodies to appear in both the .pm
  632.        and .xs files.
  633.  
  634.        o
  635.        In the .xs file, there's now a #include declaration with
  636.        the full path to the mylib.h header file.
  637.  
  638.        o
  639.        There's now some new C code that's been added to the .xs
  640.        file.  The purpose of the constant routine is to make the
  641.        values that are #define'd in the header file available to
  642.        the Perl script (in this case, by calling &main::TESTVAL).
  643.        There's also some XS code to allow calls to the constant
  644.        routine.
  645.  
  646.        o
  647.        The .pm file has exported the name TESTVAL in the @EXPORT
  648.        array.  This could lead to name clashes.  A good rule of
  649.        thumb is that if the #define is only going to be used by
  650.        the C routines themselves, and not by the user, they
  651.        should be removed from the @EXPORT array.  Alternately, if
  652.        you don't mind using the "fully qualified name" of a
  653.        variable, you could remove most or all of the items in the
  654.        @EXPORT array.
  655.  
  656.        We've also told Perl about the library that we built in
  657.        the mylib subdirectory.  That required only the addition
  658.        of the MYEXTLIB variable to the WriteMakefile call and the
  659.        replacement of the postamble subroutine to cd into the
  660.        subdirectory and run make.  The Makefile.PL for the
  661.        library is a bit more complicated, but not excessively so.
  662.        Again we replaced the postamble subroutine to insert our
  663.        own code.  This code simply specified that the library to
  664.        be created here was a static archive (as opposed to a
  665.        dynamically loadable library) and provided the commands to
  666.        build it.
  667.  
  668.        SPECIFYING ARGUMENTS TO XSUBPP
  669.  
  670.        With the completion of Example 4, we now have an easy way
  671.        to simulate some real-life libraries whose interfaces may
  672.        not be the cleanest in the world.  We shall now continue
  673.        with a discussion of the arguments passed to the xsubpp
  674.        compiler.
  675.  
  676.        When you specify arguments in the .xs file, you are really
  677.        passing three pieces of information for each one listed.
  678.        The first piece is the order of that argument relative to
  679.        the others (first, second, etc).  The second is the type
  680.        of argument, and consists of the type declaration of the
  681.        argument (e.g., int, char*, etc).  The third piece is the
  682.        exact way in which the argument should be used in the call
  683.        to the library function from this XSUB.  This would mean
  684.        whether or not to place a "&" before the argument or not,
  685.        meaning the argument expects to be passed the address of
  686.        the specified data type.
  687.  
  688.        There is a difference between the two arguments in this
  689.        hypothetical function:
  690.  
  691.                int
  692.                foo(a,b)
  693.                        char    &a
  694.                        char *  b
  695.  
  696.        The first argument to this function would be treated as a
  697.        char and assigned to the variable a, and its address would
  698.        be passed into the function foo.  The second argument
  699.        would be treated as a string pointer and assigned to the
  700.        variable b.  The value of b would be passed into the
  701.        function foo.  The actual call to the function foo that
  702.        xsubpp generates would look like this:
  703.  
  704.                foo(&a, b);
  705.  
  706.        Xsubpp will identically parse the following function
  707.        argument lists:
  708.  
  709.                char    &a
  710.                char&a
  711.                char    & a
  712.  
  713.        However, to help ease understanding, it is suggested that
  714.        you place a "&" next to the variable name and away from
  715.        the variable type), and place a "*" near the variable
  716.        type, but away from the variable name (as in the complete
  717.        example above).  By doing so, it is easy to understand
  718.        exactly what will be passed to the C function -- it will
  719.        be whatever is in the "last column".
  720.  
  721.        You should take great pains to try to pass the function
  722.        the type of variable it wants, when possible.  It will
  723.        save you a lot of trouble in the long run.
  724.  
  725.        THE ARGUMENT STACK
  726.  
  727.        If we look at any of the C code generated by any of the
  728.        examples except example 1, you will notice a number of
  729.        references to ST(n), where n is usually 0.  The "ST" is
  730.        actually a macro that points to the n'th argument on the
  731.        argument stack.  ST(0) is thus the first argument passed
  732.        to the XSUB, ST(1) is the second argument, and so on.
  733.  
  734.        When you list the arguments to the XSUB in the .xs file,
  735.        that tell xsubpp which argument corresponds to which of
  736.        the argument stack (i.e., the first one listed is the
  737.        first argument, and so on).  You invite disaster if you do
  738.        not list them in the same order as the function expects
  739.        them.
  740.  
  741.        EXTENDING YOUR EXTENSION
  742.  
  743.        Sometimes you might want to provide some extra methods or
  744.        subroutines to assist in making the interface between Perl
  745.        and your extension simpler or easier to understand.  These
  746.        routines should live in the .pm file.  Whether they are
  747.        automatically loaded when the extension itself is loaded
  748.        or only loaded when called depends on where in the .pm
  749.        file the subroutine definition is placed.
  750.  
  751.        DOCUMENTING YOUR EXTENSION
  752.  
  753.        There is absolutely no excuse for not documenting your
  754.        extension.  Documentation belongs in the .pm file.  This
  755.        file will be fed to pod2man, and the embedded
  756.        documentation will be converted to the man page format,
  757.        then placed in the blib directory.  It will be copied to
  758.        Perl's man page directory when the extension is installed.
  759.  
  760.        You may intersperse documentation and Perl code within the
  761.        .pm file.  In fact, if you want to use method autoloading,
  762.        you must do this, as the comment inside the .pm file
  763.        explains.
  764.  
  765.        See the perlpod manpage for more information about the pod
  766.        format.
  767.  
  768.        INSTALLING YOUR EXTENSION
  769.  
  770.        Once your extension is complete and passes all its tests,
  771.        installing it is quite simple: you simply run "make
  772.        install".  You will either need to have write permission
  773.        into the directories where Perl is installed, or ask your
  774.        system administrator to run the make for you.
  775.  
  776.        SEE ALSO
  777.  
  778.        For more information, consult the perlguts manpage, the
  779.        perlxs manpage, the perlmod manpage, and the perlpod
  780.        manpage.
  781.  
  782.        Author
  783.  
  784.        Jeff Okamoto <okamoto@corp.hp.com>
  785.  
  786.        Reviewed and assisted by Dean Roehrich, Ilya Zakharevich,
  787.        Andreas Koenig, and Tim Bunce.
  788.  
  789.        Last Changed
  790.  
  791.        1996/2/9
  792.