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