notes on PERL_IMPLICIT_CONTEXT (from a version by Nathan Torkington
[p5sagit/p5-mst-13.2.git] / pod / perlxstut.pod
1 =head1 NAME
2
3 perlXStut - Tutorial for writing XSUBs
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 This tutorial was written from a Unix point of view.  Where I know them
17 to be otherwise different for other platforms (e.g. Win32), I will list
18 them.  If you find something that was missed, please let me know.
19
20 =head1 SPECIAL NOTES
21
22 =head2 make
23
24 This tutorial assumes that the make program that Perl is configured to
25 use is called C<make>.  Instead of running "make" in the examples that
26 follow, you may have to substitute whatever make program Perl has been
27 configured to use.  Running "perl -V:make" should tell you what it is.
28
29 =head2 Version caveat
30
31 This tutorial tries hard to keep up with the latest development versions
32 of Perl.  This often means that it is sometimes in advance of the latest
33 released version of Perl, and that certain features described here might
34 not work on earlier versions.  See the section on "Troubleshooting
35 these Examples" for more information.
36
37 =head2 Dynamic Loading versus Static Loading
38
39 It is commonly thought that if a system does not have the capability to
40 dynamically load a library, you cannot build XSUBs.  This is incorrect.
41 You I<can> build them, but you must link the XSUBs subroutines with the
42 rest of Perl, creating a new executable.  This situation is similar to
43 Perl 4.
44
45 This tutorial can still be used on such a system.  The XSUB build mechanism
46 will check the system and build a dynamically-loadable library if possible,
47 or else a static library and then, optionally, a new statically-linked
48 executable with that static library linked in.
49
50 Should you wish to build a statically-linked executable on a system which
51 can dynamically load libraries, you may, in all the following examples,
52 where the command "C<make>" with no arguments is executed, run the command
53 "C<make perl>" instead.
54
55 If you have generated such a statically-linked executable by choice, then
56 instead of saying "C<make test>", you should say "C<make test_static>".
57 On systems that cannot build dynamically-loadable libraries at all, simply
58 saying "C<make test>" is sufficient.
59
60 =head1 TUTORIAL
61
62 Now let's go on with the show!
63
64 =head2 EXAMPLE 1
65
66 Our first extension will be very simple.  When we call the routine in the
67 extension, it will print out a well-known message and return.
68
69 Run "C<h2xs -A -n Mytest>".  This creates a directory named Mytest,
70 possibly under ext/ if that directory exists in the current working
71 directory.  Several files will be created in the Mytest dir, including
72 MANIFEST, Makefile.PL, Mytest.pm, Mytest.xs, test.pl, and Changes.
73
74 The MANIFEST file contains the names of all the files just created in the
75 Mytest directory.
76
77 The file Makefile.PL should look something like this:
78
79         use ExtUtils::MakeMaker;
80         # See lib/ExtUtils/MakeMaker.pm for details of how to influence
81         # the contents of the Makefile that is written.
82         WriteMakefile(
83             NAME         => 'Mytest',
84             VERSION_FROM => 'Mytest.pm', # finds $VERSION
85             LIBS         => [''],   # e.g., '-lm'
86             DEFINE       => '',     # e.g., '-DHAVE_SOMETHING'
87             INC          => '',     # e.g., '-I/usr/include/other'
88         );
89
90 The file Mytest.pm should start with something like this:
91
92         package Mytest;
93
94         use strict;
95         use vars qw($VERSION @ISA @EXPORT);
96
97         require Exporter;
98         require DynaLoader;
99
100         @ISA = qw(Exporter DynaLoader);
101         # Items to export into callers namespace by default. Note: do not export
102         # names by default without a very good reason. Use EXPORT_OK instead.
103         # Do not simply export all your public functions/methods/constants.
104         @EXPORT = qw(
105
106         );
107         $VERSION = '0.01';
108
109         bootstrap Mytest $VERSION;
110
111         # Preloaded methods go here.
112
113         # Autoload methods go after __END__, and are processed by the autosplit program.
114
115         1;
116         __END__
117         # Below is the stub of documentation for your module. You better edit it!
118
119 The rest of the .pm file contains sample code for providing documentation for
120 the extension.
121
122 Finally, the Mytest.xs file should look something like this:
123
124         #include "EXTERN.h"
125         #include "perl.h"
126         #include "XSUB.h"
127
128         MODULE = Mytest         PACKAGE = Mytest
129
130 Let's edit the .xs file by adding this to the end of the file:
131
132         void
133         hello()
134             CODE:
135                 printf("Hello, world!\n");
136
137 It is okay for the lines starting at the "CODE:" line to not be indented.
138 However, for readability purposes, it is suggested that you indent CODE:
139 one level and the lines following one more level.
140
141 Now we'll run "C<perl Makefile.PL>".  This will create a real Makefile,
142 which make needs.  Its output looks something like:
143
144         % perl Makefile.PL
145         Checking if your kit is complete...
146         Looks good
147         Writing Makefile for Mytest
148         %
149
150 Now, running make will produce output that looks something like this (some
151 long lines have been shortened for clarity and some extraneous lines have
152 been deleted):
153
154         % make
155         umask 0 && cp Mytest.pm ./blib/Mytest.pm
156         perl xsubpp -typemap typemap Mytest.xs >Mytest.tc && mv Mytest.tc Mytest.c
157         Please specify prototyping behavior for Mytest.xs (see perlxs manual)
158         cc -c Mytest.c
159         Running Mkbootstrap for Mytest ()
160         chmod 644 Mytest.bs
161         LD_RUN_PATH="" ld -o ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl -b Mytest.o
162         chmod 755 ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl
163         cp Mytest.bs ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
164         chmod 644 ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
165         Manifying ./blib/man3/Mytest.3
166         %
167
168 You can safely ignore the line about "prototyping behavior".
169
170 If you are on a Win32 system, and the build process fails with linker
171 errors for functions in the C library, check if your Perl is configured
172 to use PerlCRT (running "perl -V:libc" should show you if this is the
173 case).  If Perl is configured to use PerlCRT, you have to make sure
174 PerlCRT.lib is copied to the same location that msvcrt.lib lives in,
175 so that the compiler can find it on its own.  msvcrt.lib is usually
176 found in the Visual C compiler's lib directory (e.g. C:/DevStudio/VC/lib).
177
178 Perl has its own special way of easily writing test scripts, but for this
179 example only, we'll create our own test script.  Create a file called hello
180 that looks like this:
181
182         #! /opt/perl5/bin/perl
183         
184         use ExtUtils::testlib;
185         
186         use Mytest;
187         
188         Mytest::hello();
189
190 Now we make the script executable (C<chmod -x hello>), run the script
191 and we should see the following output:
192
193         % ./hello
194         Hello, world!
195         %
196
197 =head2 EXAMPLE 2
198
199 Now let's add to our extension a subroutine that will take a single numeric
200 argument as input and return 0 if the number is even or 1 if the number
201 is odd.
202
203 Add the following to the end of Mytest.xs:
204
205         int
206         is_even(input)
207                 int     input
208             CODE:
209                 RETVAL = (input % 2 == 0);
210             OUTPUT:
211                 RETVAL
212
213 There does not need to be white space at the start of the "C<int input>"
214 line, but it is useful for improving readability.  Placing a semi-colon at
215 the end of that line is also optional.  Any amount and kind of white space
216 may be placed between the "C<int>" and "C<input>".
217
218 Now re-run make to rebuild our new shared library.
219
220 Now perform the same steps as before, generating a Makefile from the
221 Makefile.PL file, and running make.
222
223 In order to test that our extension works, we now need to look at the
224 file test.pl.  This file is set up to imitate the same kind of testing
225 structure that Perl itself has.  Within the test script, you perform a
226 number of tests to confirm the behavior of the extension, printing "ok"
227 when the test is correct, "not ok" when it is not.  Change the print
228 statement in the BEGIN block to print "1..4", and add the following code
229 to the end of the file:
230
231         print &Mytest::is_even(0) == 1 ? "ok 2" : "not ok 2", "\n";
232         print &Mytest::is_even(1) == 0 ? "ok 3" : "not ok 3", "\n";
233         print &Mytest::is_even(2) == 1 ? "ok 4" : "not ok 4", "\n";
234
235 We will be calling the test script through the command "C<make test>".  You
236 should see output that looks something like this:
237
238         % make test
239         PERL_DL_NONLAZY=1 /opt/perl5.004/bin/perl (lots of -I arguments) test.pl
240         1..4
241         ok 1
242         ok 2
243         ok 3
244         ok 4
245         %
246
247 =head2 What has gone on?
248
249 The program h2xs is the starting point for creating extensions.  In later
250 examples we'll see how we can use h2xs to read header files and generate
251 templates to connect to C routines.
252
253 h2xs creates a number of files in the extension directory.  The file
254 Makefile.PL is a perl script which will generate a true Makefile to build
255 the extension.  We'll take a closer look at it later.
256
257 The .pm and .xs files contain the meat of the extension.  The .xs file holds
258 the C routines that make up the extension.  The .pm file contains routines
259 that tell Perl how to load your extension.
260
261 Generating the Makefile and running C<make> created a directory called blib
262 (which stands for "build library") in the current working directory.  This
263 directory will contain the shared library that we will build.  Once we have
264 tested it, we can install it into its final location.
265
266 Invoking the test script via "C<make test>" did something very important.
267 It invoked perl with all those C<-I> arguments so that it could find the
268 various files that are part of the extension.  It is I<very> important that
269 while you are still testing extensions that you use "C<make test>".  If you
270 try to run the test script all by itself, you will get a fatal error.
271 Another reason it is important to use "C<make test>" to run your test
272 script is that if you are testing an upgrade to an already-existing version,
273 using "C<make test>" insures that you will test your new extension, not the
274 already-existing version.
275
276 When Perl sees a C<use extension;>, it searches for a file with the same name
277 as the C<use>'d extension that has a .pm suffix.  If that file cannot be found,
278 Perl dies with a fatal error.  The default search path is contained in the
279 C<@INC> array.
280
281 In our case, Mytest.pm tells perl that it will need the Exporter and Dynamic
282 Loader extensions.  It then sets the C<@ISA> and C<@EXPORT> arrays and the
283 C<$VERSION> scalar; finally it tells perl to bootstrap the module.  Perl
284 will call its dynamic loader routine (if there is one) and load the shared
285 library.
286
287 The two arrays C<@ISA> and C<@EXPORT> are very important.  The C<@ISA>
288 array contains a list of other packages in which to search for methods (or
289 subroutines) that do not exist in the current package.  This is usually
290 only important for object-oriented extensions (which we will talk about
291 much later), and so usually doesn't need to be modified.
292
293 The C<@EXPORT> array tells Perl which of the extension's variables and
294 subroutines should be placed into the calling package's namespace.  Because
295 you don't know if the user has already used your variable and subroutine
296 names, it's vitally important to carefully select what to export.  Do I<not>
297 export method or variable names I<by default> without a good reason.
298
299 As a general rule, if the module is trying to be object-oriented then don't
300 export anything.  If it's just a collection of functions and variables, then
301 you can export them via another array, called C<@EXPORT_OK>.  This array
302 does not automatically place its subroutine and variable names into the
303 namespace unless the user specifically requests that this be done.
304
305 See L<perlmod> for more information.
306
307 The C<$VERSION> variable is used to ensure that the .pm file and the shared
308 library are "in sync" with each other.  Any time you make changes to
309 the .pm or .xs files, you should increment the value of this variable.
310
311 =head2 Writing good test scripts
312
313 The importance of writing good test scripts cannot be overemphasized.  You
314 should closely follow the "ok/not ok" style that Perl itself uses, so that
315 it is very easy and unambiguous to determine the outcome of each test case.
316 When you find and fix a bug, make sure you add a test case for it.
317
318 By running "C<make test>", you ensure that your test.pl script runs and uses
319 the correct version of your extension.  If you have many test cases, you
320 might want to copy Perl's test style.  Create a directory named "t" in the
321 extension's directory and append the suffix ".t" to the names of your test
322 files.  When you run "C<make test>", all of these test files will be executed.
323
324 =head2 EXAMPLE 3
325
326 Our third extension will take one argument as its input, round off that
327 value, and set the I<argument> to the rounded value.
328
329 Add the following to the end of Mytest.xs:
330
331         void
332         round(arg)
333                 double  arg
334             CODE:
335                 if (arg > 0.0) {
336                         arg = floor(arg + 0.5);
337                 } else if (arg < 0.0) {
338                         arg = ceil(arg - 0.5);
339                 } else {
340                         arg = 0.0;
341                 }
342             OUTPUT:
343                 arg
344
345 Edit the Makefile.PL file so that the corresponding line looks like this:
346
347         'LIBS'      => ['-lm'],   # e.g., '-lm'
348
349 Generate the Makefile and run make.  Change the BEGIN block to print
350 "1..9" and add the following to test.pl:
351
352         $i = -1.5; &Mytest::round($i); print $i == -2.0 ? "ok 5" : "not ok 5", "\n";
353         $i = -1.1; &Mytest::round($i); print $i == -1.0 ? "ok 6" : "not ok 6", "\n";
354         $i = 0.0; &Mytest::round($i); print $i == 0.0 ? "ok 7" : "not ok 7", "\n";
355         $i = 0.5; &Mytest::round($i); print $i == 1.0 ? "ok 8" : "not ok 8", "\n";
356         $i = 1.2; &Mytest::round($i); print $i == 1.0 ? "ok 9" : "not ok 9", "\n";
357
358 Running "C<make test>" should now print out that all nine tests are okay.
359
360 Notice that in these new test cases, the argument passed to round was a
361 scalar variable.  You might be wondering if you can round a constant or
362 literal.  To see what happens, temporarily add the following line to test.pl:
363
364         &Mytest::round(3);
365
366 Run "C<make test>" and notice that Perl dies with a fatal error.  Perl won't
367 let you change the value of constants!
368
369 =head2 What's new here?
370
371 =over 4
372
373 =item *
374
375 We've made some changes to Makefile.PL.  In this case, we've specified an
376 extra library to be linked into the extension's shared library, the math
377 library libm in this case.  We'll talk later about how to write XSUBs that
378 can call every routine in a library.
379
380 =item *
381
382 The value of the function is not being passed back as the function's return
383 value, but by changing the value of the variable that was passed into the
384 function.  You might have guessed that when you saw that the return value
385 of round is of type "void".
386
387 =back
388
389 =head2 Input and Output Parameters
390
391 You specify the parameters that will be passed into the XSUB on the line(s)
392 after you declare the function's return value and name.  Each input parameter
393 line starts with optional white space, and may have an optional terminating
394 semicolon.
395
396 The list of output parameters occurs at the very end of the function, just
397 before after the OUTPUT: directive.  The use of RETVAL tells Perl that you
398 wish to send this value back as the return value of the XSUB function.  In
399 Example 3, we wanted the "return value" placed in the original variable
400 which we passed in, so we listed it (and not RETVAL) in the OUTPUT: section.
401
402 =head2 The XSUBPP Program
403
404 The xsubpp program takes the XS code in the .xs file and translates it into
405 C code, placing it in a file whose suffix is .c.  The C code created makes
406 heavy use of the C functions within Perl.
407
408 =head2 The TYPEMAP file
409
410 The xsubpp program uses rules to convert from Perl's data types (scalar,
411 array, etc.) to C's data types (int, char, etc.).  These rules are stored
412 in the typemap file ($PERLLIB/ExtUtils/typemap).  This file is split into
413 three parts.
414
415 The first section maps various C data types to a name, which corresponds
416 somewhat with the various Perl types.  The second section contains C code
417 which xsubpp uses to handle input parameters.  The third section contains
418 C code which xsubpp uses to handle output parameters.
419
420 Let's take a look at a portion of the .c file created for our extension.
421 The file name is Mytest.c:
422
423         XS(XS_Mytest_round)
424         {
425             dXSARGS;
426             if (items != 1)
427                 croak("Usage: Mytest::round(arg)");
428             {
429                 double  arg = (double)SvNV(ST(0));      /* XXXXX */
430                 if (arg > 0.0) {
431                         arg = floor(arg + 0.5);
432                 } else if (arg < 0.0) {
433                         arg = ceil(arg - 0.5);
434                 } else {
435                         arg = 0.0;
436                 }
437                 sv_setnv(ST(0), (double)arg);   /* XXXXX */
438             }
439             XSRETURN(1);
440         }
441
442 Notice the two lines commented with "XXXXX".  If you check the first section
443 of the typemap file, you'll see that doubles are of type T_DOUBLE.  In the
444 INPUT section, an argument that is T_DOUBLE is assigned to the variable
445 arg by calling the routine SvNV on something, then casting it to double,
446 then assigned to the variable arg.  Similarly, in the OUTPUT section,
447 once arg has its final value, it is passed to the sv_setnv function to
448 be passed back to the calling subroutine.  These two functions are explained
449 in L<perlguts>; we'll talk more later about what that "ST(0)" means in the
450 section on the argument stack.
451
452 =head2 Warning about Output Arguments
453
454 In general, it's not a good idea to write extensions that modify their input
455 parameters, as in Example 3.  Instead, you should probably return multiple
456 values in an array and let the caller handle them (we'll do this in a later
457 example).  However, in order to better accomodate calling pre-existing C
458 routines, which often do modify their input parameters, this behavior is
459 tolerated.
460
461 =head2 EXAMPLE 4
462
463 In this example, we'll now begin to write XSUBs that will interact with
464 pre-defined C libraries.  To begin with, we will build a small library of
465 our own, then let h2xs write our .pm and .xs files for us.
466
467 Create a new directory called Mytest2 at the same level as the directory
468 Mytest.  In the Mytest2 directory, create another directory called mylib,
469 and cd into that directory.
470
471 Here we'll create some files that will generate a test library.  These will
472 include a C source file and a header file.  We'll also create a Makefile.PL
473 in this directory.  Then we'll make sure that running make at the Mytest2
474 level will automatically run this Makefile.PL file and the resulting Makefile.
475
476 In the mylib directory, create a file mylib.h that looks like this:
477
478         #define TESTVAL 4
479
480         extern double   foo(int, long, const char*);
481
482 Also create a file mylib.c that looks like this:
483
484         #include <stdlib.h>
485         #include "./mylib.h"
486         
487         double
488         foo(int a, long b, const char *c)
489         {
490                 return (a + b + atof(c) + TESTVAL);
491         }
492
493 And finally create a file Makefile.PL that looks like this:
494
495         use ExtUtils::MakeMaker;
496         $Verbose = 1;
497         WriteMakefile(
498             NAME   => 'Mytest2::mylib',
499             SKIP   => [qw(all static static_lib dynamic dynamic_lib)],
500             clean  => {'FILES' => 'libmylib$(LIBEEXT)'},
501         );
502
503
504         sub MY::top_targets {
505                 '
506         all :: static
507
508         pure_all :: static
509
510         static ::       libmylib$(LIB_EXT)
511
512         libmylib$(LIB_EXT): $(O_FILES)
513                 $(AR) cr libmylib$(LIB_EXT) $(O_FILES)
514                 $(RANLIB) libmylib$(LIB_EXT)
515
516         ';
517         }
518
519 Make sure you use a tab and not spaces on the lines beginning with "$(AR)"
520 and "$(RANLIB)".  Make will not function properly if you use spaces.
521 It has also been reported that the "cr" argument to $(AR) is unnecessary
522 on Win32 systems.
523
524 We will now create the main top-level Mytest2 files.  Change to the directory
525 above Mytest2 and run the following command:
526
527         % h2xs -O -n Mytest2 ./Mytest2/mylib/mylib.h
528
529 This will print out a warning about overwriting Mytest2, but that's okay.
530 Our files are stored in Mytest2/mylib, and will be untouched.
531
532 The normal Makefile.PL that h2xs generates doesn't know about the mylib
533 directory.  We need to tell it that there is a subdirectory and that we
534 will be generating a library in it.  Let's add the argument MYEXTLIB to
535 the WriteMakefile call so that it looks like this:
536
537         WriteMakefile(
538             'NAME'      => 'Mytest2',
539             'VERSION_FROM' => 'Mytest2.pm', # finds $VERSION
540             'LIBS'      => [''],   # e.g., '-lm'
541             'DEFINE'    => '',     # e.g., '-DHAVE_SOMETHING'
542             'INC'       => '',     # e.g., '-I/usr/include/other'
543             'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)',
544         );
545
546 and then at the end add a subroutine (which will override the pre-existing
547 subroutine).  Remember to use a tab character to indent the line beginning
548 with "cd"!
549
550         sub MY::postamble {
551         '
552         $(MYEXTLIB): mylib/Makefile
553                 cd mylib && $(MAKE) $(PASSTHRU)
554         ';
555         }
556
557 Let's also fix the MANIFEST file so that it accurately reflects the contents
558 of our extension.  The single line that says "mylib" should be replaced by
559 the following three lines:
560
561         mylib/Makefile.PL
562         mylib/mylib.c
563         mylib/mylib.h
564
565 To keep our namespace nice and unpolluted, edit the .pm file and change
566 the variable C<@EXPORT> to C<@EXPORT_OK> (there are two: one in the line
567 beginning "use vars" and one setting the array itself).  Finally, in the
568 .xs file, edit the #include line to read:
569
570         #include "mylib/mylib.h"
571
572 And also add the following function definition to the end of the .xs file:
573
574         double
575         foo(a,b,c)
576                 int             a
577                 long            b
578                 const char *    c
579             OUTPUT:
580                 RETVAL
581
582 Now we also need to create a typemap file because the default Perl doesn't
583 currently support the const char * type.  Create a file called typemap in
584 the Mytest2 directory and place the following in it:
585
586         const char *    T_PV
587
588 Now run perl on the top-level Makefile.PL.  Notice that it also created a
589 Makefile in the mylib directory.  Run make and watch that it does cd into
590 the mylib directory and run make in there as well.
591
592 Now edit the test.pl script and change the BEGIN block to print "1..4",
593 and add the following lines to the end of the script:
594
595         print &Mytest2::foo(1, 2, "Hello, world!") == 7 ? "ok 2\n" : "not ok 2\n";
596         print &Mytest2::foo(1, 2, "0.0") == 7 ? "ok 3\n" : "not ok 3\n";
597         print abs(&Mytest2::foo(0, 0, "-3.4") - 0.6) <= 0.01 ? "ok 4\n" : "not ok 4\n";
598
599 (When dealing with floating-point comparisons, it is best to not check for
600 equality, but rather that the difference between the expected and actual
601 result is below a certain amount (called epsilon) which is 0.01 in this case)
602
603 Run "C<make test>" and all should be well.
604
605 =head2 What has happened here?
606
607 Unlike previous examples, we've now run h2xs on a real include file.  This
608 has caused some extra goodies to appear in both the .pm and .xs files.
609
610 =over 4
611
612 =item *
613
614 In the .xs file, there's now a #include directive with the absolute path to
615 the mylib.h header file.  We changed this to a relative path so that we
616 could move the extension directory if we wanted to.
617
618 =item *
619
620 There's now some new C code that's been added to the .xs file.  The purpose
621 of the C<constant> routine is to make the values that are #define'd in the
622 header file accessible by the Perl script (by calling either C<TESTVAL> or
623 C<&Mytest2::TESTVAL>).  There's also some XS code to allow calls to the
624 C<constant> routine.
625
626 =item *
627
628 The .pm file originally exported the name C<TESTVAL> in the C<@EXPORT> array.
629 This could lead to name clashes.  A good rule of thumb is that if the #define
630 is only going to be used by the C routines themselves, and not by the user,
631 they should be removed from the C<@EXPORT> array.  Alternately, if you don't
632 mind using the "fully qualified name" of a variable, you could move most
633 or all of the items from the C<@EXPORT> array into the C<@EXPORT_OK> array.
634
635 =item *
636
637 If our include file had contained #include directives, these would not have
638 been processed by h2xs.  There is no good solution to this right now.
639
640 =item *
641
642 We've also told Perl about the library that we built in the mylib
643 subdirectory.  That required only the addition of the C<MYEXTLIB> variable
644 to the WriteMakefile call and the replacement of the postamble subroutine
645 to cd into the subdirectory and run make.  The Makefile.PL for the
646 library is a bit more complicated, but not excessively so.  Again we
647 replaced the postamble subroutine to insert our own code.  This code
648 simply specified that the library to be created here was a static archive
649 library (as opposed to a dynamically loadable library) and provided the
650 commands to build it.
651
652 =back
653
654 =head2 More about XSUBPP
655
656 With the completion of Example 4, we now have an easy way to simulate some
657 real-life libraries whose interfaces may not be the cleanest in the world.
658 We shall now continue with a discussion of the arguments passed to the
659 xsubpp compiler.
660
661 When you specify arguments to routines in the .xs file, you are really
662 passing three pieces of information for each argument listed.  The first
663 piece is the order of that argument relative to the others (first, second,
664 etc).  The second is the type of argument, and consists of the type
665 declaration of the argument (e.g., int, char*, etc).  The third piece is
666 the exact way in which the argument should be used in the call to the
667 library function from this XSUB.  This would mean whether or not to place
668 a "&" before the argument or not, meaning the argument expects to be
669 passed the address of the specified data type.
670
671 There is a difference between the two arguments in this hypothetical function:
672
673         int
674         foo(a,b)
675                 char    &a
676                 char *  b
677
678 The first argument to this function would be treated as a char and assigned
679 to the variable a, and its address would be passed into the function foo.
680 The second argument would be treated as a string pointer and assigned to the
681 variable b.  The I<value> of b would be passed into the function foo.  The
682 actual call to the function foo that xsubpp generates would look like this:
683
684         foo(&a, b);
685
686 Xsubpp will parse the following function argument lists identically:
687
688         char    &a
689         char&a
690         char    & a
691
692 However, to help ease understanding, it is suggested that you place a "&"
693 next to the variable name and away from the variable type), and place a
694 "*" near the variable type, but away from the variable name (as in the
695 call to foo above).  By doing so, it is easy to understand exactly what
696 will be passed to the C function -- it will be whatever is in the "last
697 column".
698
699 You should take great pains to try to pass the function the type of variable
700 it wants, when possible.  It will save you a lot of trouble in the long run.
701
702 =head2 The Argument Stack
703
704 If we look at any of the C code generated by any of the examples except
705 example 1, you will notice a number of references to ST(n), where n is
706 usually 0.  "ST" is actually a macro that points to the n'th argument
707 on the argument stack.  ST(0) is thus the first argument on the stack and
708 therefore the first argument passed to the XSUB, ST(1) is the second
709 argument, and so on.
710
711 When you list the arguments to the XSUB in the .xs file, that tells xsubpp
712 which argument corresponds to which of the argument stack (i.e., the first
713 one listed is the first argument, and so on).  You invite disaster if you
714 do not list them in the same order as the function expects them.
715
716 The actual values on the argument stack are pointers to the values passed
717 in.  When an argument is listed as being an OUTPUT value, its corresponding
718 value on the stack (i.e., ST(0) if it was the first argument) is changed.
719 You can verify this by looking at the C code generated for Example 3.
720 The code for the round() XSUB routine contains lines that look like this:
721
722         double  arg = (double)SvNV(ST(0));
723         /* Round the contents of the variable arg */
724         sv_setnv(ST(0), (double)arg);
725
726 The arg variable is initially set by taking the value from ST(0), then is
727 stored back into ST(0) at the end of the routine.
728
729 =head2 Extending your Extension
730
731 Sometimes you might want to provide some extra methods or subroutines
732 to assist in making the interface between Perl and your extension simpler
733 or easier to understand.  These routines should live in the .pm file.
734 Whether they are automatically loaded when the extension itself is loaded
735 or only loaded when called depends on where in the .pm file the subroutine
736 definition is placed.  You can also consult L<Autoloader> for an alternate
737 way to store and load your extra subroutines.
738
739 =head2 Documenting your Extension
740
741 There is absolutely no excuse for not documenting your extension.
742 Documentation belongs in the .pm file.  This file will be fed to pod2man,
743 and the embedded documentation will be converted to the man page format,
744 then placed in the blib directory.  It will be copied to Perl's man
745 page directory when the extension is installed.
746
747 You may intersperse documentation and Perl code within the .pm file.
748 In fact, if you want to use method autoloading, you must do this,
749 as the comment inside the .pm file explains.
750
751 See L<perlpod> for more information about the pod format.
752
753 =head2 Installing your Extension
754
755 Once your extension is complete and passes all its tests, installing it
756 is quite simple: you simply run "make install".  You will either need 
757 to have write permission into the directories where Perl is installed,
758 or ask your system administrator to run the make for you.
759
760 Alternately, you can specify the exact directory to place the extension's
761 files by placing a "PREFIX=/destination/directory" after the make install.
762 (or in between the make and install if you have a brain-dead version of make).
763 This can be very useful if you are building an extension that will eventually
764 be distributed to multiple systems.  You can then just archive the files in
765 the destination directory and distribute them to your destination systems.
766
767 =head2 EXAMPLE 5
768
769 In this example, we'll do some more work with the argument stack.  The
770 previous examples have all returned only a single value.  We'll now
771 create an extension that returns an array.
772
773 This extension is very Unix-oriented (struct statfs and the statfs system
774 call).  If you are not running on a Unix system, you can substitute for
775 statfs any other function that returns multiple values, you can hard-code
776 values to be returned to the caller (although this will be a bit harder
777 to test the error case), or you can simply not do this example.  If you
778 change the XSUB, be sure to fix the test cases to match the changes.
779
780 Return to the Mytest directory and add the following code to the end of
781 Mytest.xs:
782
783         void
784         statfs(path)
785                 char *  path
786             PREINIT:
787                 int i;
788                 struct statfs buf;
789
790             PPCODE:
791                 i = statfs(path, &buf);
792                 if (i == 0) {
793                         XPUSHs(sv_2mortal(newSVnv(buf.f_bavail)));
794                         XPUSHs(sv_2mortal(newSVnv(buf.f_bfree)));
795                         XPUSHs(sv_2mortal(newSVnv(buf.f_blocks)));
796                         XPUSHs(sv_2mortal(newSVnv(buf.f_bsize)));
797                         XPUSHs(sv_2mortal(newSVnv(buf.f_ffree)));
798                         XPUSHs(sv_2mortal(newSVnv(buf.f_files)));
799                         XPUSHs(sv_2mortal(newSVnv(buf.f_type)));
800                         XPUSHs(sv_2mortal(newSVnv(buf.f_fsid[0])));
801                         XPUSHs(sv_2mortal(newSVnv(buf.f_fsid[1])));
802                 } else {
803                         XPUSHs(sv_2mortal(newSVnv(errno)));
804                 }
805
806 You'll also need to add the following code to the top of the .xs file, just
807 after the include of "XSUB.h":
808
809         #include <sys/vfs.h>
810
811 Also add the following code segment to test.pl while incrementing the "1..9"
812 string in the BEGIN block to "1..11":
813
814         @a = &Mytest::statfs("/blech");
815         print ((scalar(@a) == 1 && $a[0] == 2) ? "ok 10\n" : "not ok 10\n");
816         @a = &Mytest::statfs("/");
817         print scalar(@a) == 9 ? "ok 11\n" : "not ok 11\n";
818
819 =head2 New Things in this Example
820
821 This example added quite a few new concepts.  We'll take them one at a time.
822
823 =over 4
824
825 =item *
826
827 The PREINIT: directive contains code that will be placed immediately after
828 variable declaration and before the argument stack is decoded.  Some compilers
829 cannot handle variable declarations at arbitrary locations inside a function,
830 so this is usually the best way to declare local variables needed by the XSUB.
831
832 =item *
833
834 This routine also returns a different number of arguments depending on the
835 success or failure of the call to statfs.  If there is an error, the error
836 number is returned as a single-element array.  If the call is successful,
837 then a 9-element array is returned.  Since only one argument is passed into
838 this function, we need room on the stack to hold the 9 values which may be
839 returned.
840
841 We do this by using the PPCODE: directive, rather than the CODE: directive.
842 This tells xsubpp that we will be managing the return values that will be
843 put on the argument stack by ourselves.
844
845 =item *
846
847 When we want to place values to be returned to the caller onto the stack,
848 we use the series of macros that begin with "XPUSH".  There are five
849 different versions, for placing integers, unsigned integers, doubles,
850 strings, and Perl scalars on the stack.  In our example, we placed a
851 Perl scalar onto the stack.
852
853 The XPUSH* macros will automatically extend the return stack to prevent
854 it from being overrun.  You push values onto the stack in the order you
855 want them seen by the calling program.
856
857 =item *
858
859 The values pushed onto the return stack of the XSUB are actually mortal SV's.
860 They are made mortal so that once the values are copied by the calling
861 program, the SV's that held the returned values can be deallocated.
862 If they were not mortal, then they would continue to exist after the XSUB
863 routine returned, but would not be accessible.  This is a memory leak.
864
865 =back
866
867 =head2 EXAMPLE 6 (Coming Soon)
868
869 Passing in and returning references to arrays and/or hashes
870
871 =head2 EXAMPLE 7 (Coming Soon)
872
873 XPUSH args AND set RETVAL AND assign return value to array
874
875 =head2 EXAMPLE 8 (Coming Soon)
876
877 Setting $!
878
879 =head2 EXAMPLE 9 (Coming Soon)
880
881 Getting fd's from filehandles
882
883 =head2 Troubleshooting these Examples
884
885 As mentioned at the top of this document, if you are having problems with
886 these example extensions, you might see if any of these help you.
887
888 =over 4
889
890 =item *
891
892 In versions of 5.002 prior to the gamma version, the test script in Example
893 1 will not function properly.  You need to change the "use lib" line to
894 read:
895
896         use lib './blib';
897
898 =item *
899
900 In versions of 5.002 prior to version 5.002b1h, the test.pl file was not
901 automatically created by h2xs.  This means that you cannot say "make test"
902 to run the test script.  You will need to add the following line before the
903 "use extension" statement:
904
905         use lib './blib';
906
907 =item *
908
909 In versions 5.000 and 5.001, instead of using the above line, you will need
910 to use the following line:
911
912         BEGIN { unshift(@INC, "./blib") }
913
914 =item *
915
916 This document assumes that the executable named "perl" is Perl version 5.  
917 Some systems may have installed Perl version 5 as "perl5".
918
919 =back
920
921 =head1 See also
922
923 For more information, consult L<perlguts>, L<perlxs>, L<perlmod>,
924 and L<perlpod>.
925
926 =head1 Author
927
928 Jeff Okamoto <F<okamoto@corp.hp.com>>
929
930 Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig,
931 and Tim Bunce.
932
933 =head2 Last Changed
934
935 1999/5/25