home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl502b.zip / pod / perlxstut.pod < prev    next >
Text File  |  1996-01-30  |  19KB  |  533 lines

  1. =head1 NAME
  2.  
  3. perlXStut - Tutorial for XSUB's
  4.  
  5. =head1 DESCRIPTION
  6.  
  7. This tutorial will educate the reader on the steps involved in creating
  8. a Perl extension.  The reader is assumed to have access to L<perlguts> and
  9. L<perlxs>.
  10.  
  11. This tutorial starts with very simple examples and becomes more complex,
  12. with each new example adding new features.  Certain concepts may not be
  13. completely explained until later in the tutorial in order to slowly ease
  14. the reader into building extensions.
  15.  
  16. =head2 VERSION CAVEAT
  17.  
  18. This tutorial tries hard to keep up with the latest development versions
  19. of Perl.  This often means that it is sometimes in advance of the latest
  20. released version of Perl, and that certain features described here might
  21. not work on earlier versions.  This section will keep track of when various
  22. features were added to Perl 5.
  23.  
  24. =over 4
  25.  
  26. =item *
  27.  
  28. In version 5.002 before version 5.002b1h, the test.pl file was not
  29. automatically created by xsubpp.  This means that you cannot say "make test"
  30. to run the test script.  You will need to add the following line before the
  31. "use extension" statement:
  32.  
  33.     use lib './blib';
  34.  
  35. =item *
  36.  
  37. In versions 5.000 and 5.001, instead of using the above line, you will need
  38. to use the following line:
  39.  
  40.     BEGIN { unshift(@INC, "./blib") }
  41.  
  42. =item *
  43.  
  44. This document assumes that the executable named "perl" is Perl version 5.  
  45. Some systems may have installed Perl version 5 as "perl5".
  46.  
  47. =back
  48.  
  49. =head2 DYNAMIC VERSUS STATIC
  50.  
  51. It is commonly thought that if a system does not have the capability to
  52. dynamically load a library, you cannot build XSUB's.  This is incorrect.
  53. You I<can> build them, but you must link the XSUB's subroutines with the
  54. rest of Perl, creating a new executable.  This situation is similar to
  55. Perl 4.
  56.  
  57. This tutorial can still be used on such a system.  The XSUB build mechanism
  58. will check the system and build a dynamically-loadable library if possible,
  59. or else a static 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 a system which
  63. can dynamically load libraries, you may, in all the following examples,
  64. where the command "make" with no arguments is executed, run the command
  65. "make perl" instead.
  66.  
  67. If you have generated such a statically-linked executable by choice, then
  68. instead of saying "make test", you should say "make test_static".  On systems
  69. that cannot build dynamically-loadable libraries at all, simply saying "make
  70. test" is sufficient.
  71.  
  72. =head2 EXAMPLE 1
  73.  
  74. Our first extension will be very simple.  When we call the routine in the
  75. extension, it will print out a well-known message and return.
  76.  
  77. Run "h2xs -A -n mytest".  This creates a directory named mytest, possibly under
  78. ext/ if that directory exists in the current working directory.  Several files
  79. will be created in the mytest dir, including MANIFEST, Makefile.PL, mytest.pm,
  80. mytest.xs, test.pl, and Changes.
  81.  
  82. The MANIFEST file contains the names of all the files created.
  83.  
  84. The file Makefile.PL should look something like this:
  85.  
  86.     use ExtUtils::MakeMaker;
  87.     # See lib/ExtUtils/MakeMaker.pm for details of how to influence
  88.     # the contents of the Makefile that is written.
  89.     WriteMakefile(
  90.         'NAME'      => 'mytest',
  91.         'VERSION_FROM' => 'mytest.pm', # finds $VERSION
  92.         'LIBS'      => [''],   # e.g., '-lm'
  93.         'DEFINE'    => '',     # e.g., '-DHAVE_SOMETHING'
  94.         'INC'       => '',     # e.g., '-I/usr/include/other'
  95.     );
  96.  
  97. The file mytest.pm should start with something like this:
  98.  
  99.     package mytest;
  100.  
  101.     require Exporter;
  102.     require DynaLoader;
  103.  
  104.     @ISA = qw(Exporter DynaLoader);
  105.     # Items to export into callers namespace by default. Note: do not export
  106.     # names by default without a very good reason. Use EXPORT_OK instead.
  107.     # Do not simply export all your public functions/methods/constants.
  108.     @EXPORT = qw(
  109.  
  110.     );
  111.     $VERSION = '0.01';
  112.  
  113.     bootstrap mytest $VERSION;
  114.  
  115.     # Preloaded methods go here.
  116.  
  117.     # Autoload methods go after __END__, and are processed by the autosplit program.
  118.  
  119.     1;
  120.     __END__
  121.     # Below is the stub of documentation for your module. You better edit it!
  122.  
  123. And the mytest.xs file should look something like this:
  124.  
  125.     #ifdef __cplusplus
  126.     extern "C" {
  127.     #endif
  128.     #include "EXTERN.h"
  129.     #include "perl.h"
  130.     #include "XSUB.h"
  131.     #ifdef __cplusplus
  132.     }
  133.     #endif
  134.     
  135.     MODULE = mytest        PACKAGE = mytest
  136.  
  137. Let's edit the .xs file by adding this to the end of the file:
  138.  
  139.     void
  140.     hello()
  141.         CODE:
  142.         printf("Hello, world!\n");
  143.  
  144. Now we'll run "perl Makefile.PL".  This will create a real Makefile,
  145. which make needs.  It's output looks something like:
  146.  
  147.     % perl Makefile.PL
  148.     Checking if your kit is complete...
  149.     Looks good
  150.     Writing Makefile for mytest
  151.     %
  152.  
  153. Now, running make will produce output that looks something like this
  154. (some long lines shortened for clarity):
  155.  
  156.     % make
  157.     umask 0 && cp mytest.pm ./blib/mytest.pm
  158.     perl xsubpp -typemap typemap mytest.xs >mytest.tc && mv mytest.tc mytest.c
  159.     cc -c mytest.c
  160.     Running Mkbootstrap for mytest ()
  161.     chmod 644 mytest.bs
  162.     LD_RUN_PATH="" ld -o ./blib/PA-RISC1.1/auto/mytest/mytest.sl -b mytest.o
  163.     chmod 755 ./blib/PA-RISC1.1/auto/mytest/mytest.sl
  164.     cp mytest.bs ./blib/PA-RISC1.1/auto/mytest/mytest.bs
  165.     chmod 644 ./blib/PA-RISC1.1/auto/mytest/mytest.bs
  166.  
  167. Now, although there is already a test.pl template ready for us, for this
  168. example only, we'll create a special test script.  Create a file called hello
  169. that looks like this:
  170.  
  171. Now we'll create a test script, test1.pl in the mytest directory.  It should
  172. look like this:
  173.  
  174.     #! /opt/perl5/bin/perl
  175.     
  176.     use lib './blib';
  177.     
  178.     use mytest;
  179.     
  180.     mytest::hello();
  181.  
  182. Now we run the script and we should see the following output:
  183.  
  184.     % perl hello
  185.     Hello, world!
  186.     %
  187.  
  188. =head2 EXAMPLE 2
  189.  
  190. Now let's add to our extension a subroutine that will take a single argument
  191. and return 0 if the argument is even, 1 if the argument is odd.
  192.  
  193. Add the following to the end of mytest.xs:
  194.  
  195.     int
  196.     is_even(input)
  197.         int    input
  198.         CODE:
  199.         RETVAL = (input % 2 == 0);
  200.         OUTPUT:
  201.         RETVAL
  202.  
  203. There must be some white space at the start of the "int input" line, and
  204. there must not be a semi-colon at the end of the line (as you'd expect in
  205. a C program).
  206.  
  207. Any white space may be between the "int" and "input".  It is also okay for
  208. the four lines starting at the "CODE:" line to not be indented.  However,
  209. for readability purposes, it is suggested that you indent them 8 spaces
  210. (or one normal tab stop).
  211.  
  212. Now re-run make to rebuild our new shared library.
  213.  
  214. Now perform the same steps as before, generating a Makefile from the
  215. Makefile.PL file, and running make.
  216.  
  217. In order to test that our extension works, we now need to look at the
  218. file test.pl.  This file is set up to imitate the same kind of testing
  219. structure that Perl itself has.  Within the test script, you perform a
  220. number of tests to confirm the behavior of the extension, printing "ok"
  221. when the test is correct, "not ok" when it is not.
  222.  
  223. Let's change the print statement in the BEGIN block to print "1..4" and
  224. add the following code to the end of the file:
  225.  
  226.     print &mytest::is_even(0) == 1 ? "ok 2" : "not ok 2", "\n";
  227.     print &mytest::is_even(1) == 0 ? "ok 3" : "not ok 3", "\n";
  228.     print &mytest::is_even(2) == 1 ? "ok 4" : "not ok 4", "\n";
  229.  
  230. We will be calling the test script through the command "make test".  You
  231. should see output that looks something like this:
  232.  
  233.     % make test
  234.     PERL_DL_NONLAZY=1 /opt/perl5.002b2/bin/perl (lots of -I arguments) test.pl
  235.     1..4
  236.     ok 1
  237.     ok 2
  238.     ok 3
  239.     ok 4
  240.     %
  241.  
  242. =head2 WHAT HAS GONE ON?
  243.  
  244. The program h2xs is the starting point for creating extensions.  In later
  245. examples we'll see how we can use h2xs to read header files and generate
  246. templates to connect to C routines.
  247.  
  248. h2xs creates a number of files in the extension directory.  The file
  249. Makefile.PL is a perl script which will generate a true Makefile to build
  250. the extension.  We'll take a closer look at it later.
  251.  
  252. The files <extension>.pm and <extension>.xs contain the meat of the extension.
  253. The .xs file holds the C routines that make up the extension.  The .pm file
  254. contains routines that tell Perl how to load your extension.
  255.  
  256. Generating and invoking the Makefile created a directory blib (which stands
  257. for "build library") in the current working directory.  This directory will
  258. contain the shared library that we will build.  Once we have tested it, we
  259. can install it into its final location.
  260.  
  261. Invoking the test script via "make test" did something very important.  It
  262. invoked perl with all those -I arguments so that it could find the various
  263. files that are part of the extension.
  264.  
  265. It is I<very> important that while you are still testing extensions that
  266. you use "make test".  If you try to run the test script all by itself, you
  267. will get a fatal error.
  268.  
  269. Another reason it is important to use "make test" to run your test script
  270. is that if you are testing an upgrade to an already-existing version, using
  271. "make test" insures that you use your new extension, not the already-existing
  272. version.
  273.  
  274. Finally, our test scripts do two important things.  First of all, they place
  275. the directory "blib" at the head of the @INC array.  Placing this inside a
  276. BEGIN block assures us that Perl will look in the blib directory hierarchy
  277. before looking in the system directories.  This could be important if you are
  278. upgrading an already-existing extension and do not want to disturb the system
  279. version until you are ready to install it.
  280.  
  281. When Perl sees a C<use extension;>, it searches for a file with the same name
  282. as the use'd extension that has a .pm suffix.  If that file cannot be found,
  283. Perl dies with a fatal error.  The default search path is contained in the
  284. @INC array.
  285.  
  286. In our case, mytest.pm tells perl that it will need the Exporter and Dynamic
  287. Loader extensions.  It then sets the @ISA and @EXPORT arrays and the $VERSION
  288. scalar; finally it tells perl to bootstrap the module.  Perl will call its
  289. dynamic loader routine (if there is one) and load the shared library.
  290.  
  291. The two arrays that are set in the .pm file are very important.  The @ISA
  292. array contains a list of other packages in which to search for methods (or
  293. subroutines) that do not exist in the current package.  The @EXPORT array
  294. tells Perl which of the extension's routines should be placed into the
  295. calling package's namespace.
  296.  
  297. It's important to select what to export carefully.  Do NOT export method names
  298. and do NOT export anything else I<by default> without a good reason.
  299.  
  300. As a general rule, if the module is trying to be object-oriented then don't
  301. export anything.  If it's just a collection of functions then you can export
  302. any of the functions via another array, called @EXPORT_OK.
  303.  
  304. See L<perlmod> for more information.
  305.  
  306. The $VERSION variable is used to ensure that the .pm file and the shared
  307. library are "in sync" with each other.  Any time you make changes to the
  308. .pm or .xs files, you should increment the value of this variable.
  309.  
  310. =head2 EXAMPLE 3
  311.  
  312. Our third extension will take one argument as its input, round off that
  313. value, and set the I<argument> to the rounded value.
  314.  
  315. Add the following to the end of mytest.xs:
  316.  
  317.     void
  318.     round(arg)
  319.         double  arg
  320.         CODE:
  321.         if (arg > 0.0) {
  322.             arg = floor(arg + 0.5);
  323.         } else if (arg < 0.0) {
  324.             arg = ceil(arg - 0.5);
  325.         } else {
  326.             arg = 0.0;
  327.         }
  328.         OUTPUT:
  329.         arg
  330.  
  331. Edit the Makefile.PL file so that the corresponding line looks like this:
  332.  
  333.     'LIBS'      => ['-lm'],   # e.g., '-lm'
  334.  
  335. Generate the Makefile and run make.  Change the BEGIN block to print out
  336. "1..9" and add the following to test.pl:
  337.  
  338.     $i = -1.5; &mytest::round($i); print $i == -2.0 ? "ok 5" : "not ok 5", "\n";
  339.     $i = -1.1; &mytest::round($i); print $i == -1.0 ? "ok 6" : "not ok 6", "\n";
  340.     $i = 0.0; &mytest::round($i); print $i == 0.0 ? "ok 7" : "not ok 7", "\n";
  341.     $i = 0.5; &mytest::round($i); print $i == 1.0 ? "ok 8" : "not ok 8", "\n";
  342.     $i = 1.2; &mytest::round($i); print $i == 1.0 ? "ok 9" : "not ok 9", "\n";
  343.  
  344. Running "make test" should now print out that all nine tests are okay.
  345.  
  346. You might be wondering if you can round a constant.  To see what happens, add
  347. the following line to test.pl temporarily:
  348.  
  349.     &mytest::round(3);
  350.  
  351. Run "make test" and notice that Perl dies with a fatal error.  Perl won't let
  352. you change the value of constants!
  353.  
  354. =head2 WHAT'S NEW HERE?
  355.  
  356. Two things are new here.  First, we've made some changes to Makefile.PL.
  357. In this case, we've specified an extra library to link in, in this case the
  358. math library, libm.  We'll talk later about how to write XSUBs that can call
  359. every routine in a library.
  360.  
  361. Second, the value of the function is being passed back not as the function's
  362. return value, but through the same variable that was passed into the function.
  363.  
  364. =head2 INPUT AND OUTPUT PARAMETERS
  365.  
  366. You specify the parameters that will be passed into the XSUB just after you
  367. declare the function return value and name.  The list of parameters looks
  368. very C-like, but the lines must be indented by a tab stop, and each line
  369. may not have an ending semi-colon.
  370.  
  371. The list of output parameters occurs after the OUTPUT: directive.  The use
  372. of RETVAL tells Perl that you wish to send this value back as the return
  373. value of the XSUB function.  In Example 3, the value we wanted returned was
  374. contained in the same variable we passed in, so we listed it (and not RETVAL)
  375. in the OUTPUT: section.
  376.  
  377. =head2 THE XSUBPP COMPILER
  378.  
  379. The compiler xsubpp takes the XS code in the .xs file and converts it into
  380. C code, placing it in a file whose suffix is .c.  The C code created makes
  381. heavy use of the C functions within Perl.
  382.  
  383. =head2 THE TYPEMAP FILE
  384.  
  385. The xsubpp compiler uses rules to convert from Perl's data types (scalar,
  386. array, etc.) to C's data types (int, char *, etc.).  These rules are stored
  387. in the typemap file ($PERLLIB/ExtUtils/typemap).  This file is split into
  388. three parts.
  389.  
  390. The first part attempts to map various C data types to a coded flag, which
  391. has some correspondence with the various Perl types.  The second part contains
  392. C code which xsubpp uses for input parameters.  The third part contains C
  393. code which xsubpp uses for output parameters.  We'll talk more about the
  394. C code later.
  395.  
  396. Let's now take a look at a portion of the .c file created for our extension.
  397.  
  398.     XS(XS_mytest_round)
  399.     {
  400.         dXSARGS;
  401.         if (items != 1)
  402.         croak("Usage: mytest::round(arg)");
  403.         {
  404.         double  arg = (double)SvNV(ST(0));    /* XXXXX */
  405.         if (arg > 0.0) {
  406.             arg = floor(arg + 0.5);
  407.         } else if (arg < 0.0) {
  408.             arg = ceil(arg - 0.5);
  409.         } else {
  410.             arg = 0.0;
  411.         }
  412.         sv_setnv(ST(0), (double)arg);    /* XXXXX */
  413.         }
  414.         XSRETURN(1);
  415.     }
  416.  
  417. Notice the two lines marked with "XXXXX".  If you check the first section of
  418. the typemap file, you'll see that doubles are of type T_DOUBLE.  In the
  419. INPUT section, an argument that is T_DOUBLE is assigned to the variable
  420. arg by calling the routine SvNV on something, then casting it to double,
  421. then assigned to the variable arg.  Similarly, in the OUTPUT section,
  422. once arg has its final value, it is passed to the sv_setnv function to
  423. be passed back to the calling subroutine.  These two functions are explained
  424. in L<perlguts>; we'll talk more later about what that "ST(0)" means in the
  425. section on the argument stack.
  426.  
  427. =head2 WARNING
  428.  
  429. In general, it's not a good idea to write extensions that modify their input
  430. parameters, as in Example 3.  However, in order to better accomodate calling
  431. pre-existing C routines, which often do modify their input parameters,
  432. this behavior is tolerated.  The next example will show how to do this.
  433.  
  434. [Examples 4 and 5 have not been re-worked yet and are not included.]
  435.  
  436. =head2 SPECIFYING ARGUMENTS TO XSUBPP
  437.  
  438. After completing Example 5, we now have an easy way to simulate some
  439. real-life libraries whose interfaces may not be the cleanest in the world.
  440. We shall now continue with a discussion of the arguments passed to the
  441. xsubpp compiler.
  442.  
  443. When you specify arguments in the .xs file, you are really passing three
  444. pieces of information for each one listed.  The first piece is the order
  445. of that argument relative to the others (first, second, etc).  The second
  446. is the type of argument, and consists of the type declaration of the
  447. argument (e.g., int, char*, etc).  The third piece is the exact way in
  448. which the argument should be used in the call to the library function
  449. from this XSUB.  This would mean whether or not to place a "&" before
  450. the argument or not, meaning the argument expects to be passed the address
  451. of the specified data type.
  452.  
  453. There is a difference between the two arguments in this hypothetical function:
  454.  
  455.     int
  456.     foo(a,b)
  457.         char    &a
  458.         char *    b
  459.  
  460. The first argument to this function would be treated as a char and assigned
  461. to the variable a, and its address would be passed into the function foo.
  462. The second argument would be treated as a string pointer and assigned to the
  463. variable b.  The I<value> of b would be passed into the function foo.  The
  464. actual call to the function foo that xsubpp generates would look like this:
  465.  
  466.     foo(&a, b);
  467.  
  468. In other words, whatever is in the last column (or the variable name) is
  469. what is passed into the C function.
  470.  
  471. You should take great pains to try to pass the function the type of variable
  472. it wants, when possible.  It will save you a lot of trouble in the long run.
  473.  
  474. =head2 THE ARGUMENT STACK
  475.  
  476. If we look at any of the C code generated by any of the examples except
  477. example 1, you will notice a number of references to ST(n), where n is
  478. usually 0.  The "ST" is actually a macro that points to the n'th argument
  479. on the argument stack.  ST(0) is thus the first argument passed to the
  480. XSUB, ST(1) is the second argument, and so on.
  481.  
  482. When you list the arguments to the XSUB in the .xs file, that tell xsubpp
  483. which argument corresponds to which of the argument stack (i.e., the first
  484. one listed is the first argument, and so on).  You invite disaster if you
  485. do not list them in the same order as the function expects them.
  486.  
  487. =head2 EXTENDING YOUR EXTENSION
  488.  
  489. Sometimes you might want to provide some extra methods or subroutines
  490. to assist in making the interface between Perl and your extension simpler
  491. or easier to understand.  These routines should live in the .pm file.
  492. Whether they are automatically loaded when the extension itself is loaded
  493. or only loaded when called depends on where in the .pm file the subroutine
  494. definition is placed.
  495.  
  496. =head2 DOCUMENTING YOUR EXTENSION
  497.  
  498. There is absolutely no excuse for not documenting your extension.
  499. Documentation belongs in the .pm file.  This file will be fed to pod2man,
  500. and the documentation embedded within it converted to man page format,
  501. then placed in the blib directory.  It will be copied to Perl's man
  502. page directory when the extension is installed.
  503.  
  504. You may intersperse documentation and Perl code within the .pm file.
  505. In fact, if you want to use method autoloading, you must do this,
  506. as the comment inside the .pm file explains.
  507.  
  508. See L<perlpod> for more information about the pod format.
  509.  
  510. =head2 INSTALLING YOUR EXTENSION
  511.  
  512. Once your extension is complete and passes all its tests, installing it
  513. is quite simple: you simply run "make install".  You will either need 
  514. to have write permission into the directories where Perl is installed,
  515. or ask your system administrator to run the make for you.
  516.  
  517. =head2 SEE ALSO
  518.  
  519. For more information, consult L<perlguts>, L<perlxs>, L<perlmod>,
  520. and L<perlpod>.
  521.  
  522. =head2 Author
  523.  
  524. Jeff Okamoto <okamoto@corp.hp.com>
  525.  
  526. Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig,
  527. and Tim Bunce.
  528.  
  529. =head2 Last Changed
  530.  
  531. 1996/1/19
  532.  
  533.