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