This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Lose the loose. Fix documentation typo.
[perl5.git] / dist / ExtUtils-ParseXS / lib / perlxstut.pod
CommitLineData
4633a7c4
LW
1=head1 NAME
2
adc5c68a 3perlxstut - Tutorial for writing XSUBs
4633a7c4
LW
4
5=head1 DESCRIPTION
6
7This tutorial will educate the reader on the steps involved in creating
171891c7
GS
8a Perl extension. The reader is assumed to have access to L<perlguts>,
9L<perlapi> and L<perlxs>.
4633a7c4
LW
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
360e660c
GS
13completely explained until later in the tutorial in order to slowly ease
14the reader into building extensions.
4633a7c4 15
360e660c
GS
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
360e660c 20=head1 SPECIAL NOTES
c07a80fd 21
360e660c 22=head2 make
c07a80fd 23
360e660c
GS
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
5a3e7812 27configured to use. Running B<perl -V:make> should tell you what it is.
c07a80fd 28
360e660c 29=head2 Version caveat
c07a80fd 30
beb31b0b
GS
31When writing a Perl extension for general consumption, one should expect that
32the extension will be used with versions of Perl different from the
33version available on your machine. Since you are reading this document,
34the version of Perl on your machine is probably 5.005 or later, but the users
35of your extension may have more ancient versions.
36
37To understand what kinds of incompatibilities one may expect, and in the rare
38case that the version of Perl on your machine is older than this document,
39see the section on "Troubleshooting these Examples" for more information.
40
41If your extension uses some features of Perl which are not available on older
42releases of Perl, your users would appreciate an early meaningful warning.
43You would probably put this information into the F<README> file, but nowadays
44installation of extensions may be performed automatically, guided by F<CPAN.pm>
45module or other tools.
46
47In MakeMaker-based installations, F<Makefile.PL> provides the earliest
48opportunity to perform version checks. One can put something like this
49in F<Makefile.PL> for this purpose:
50
51 eval { require 5.007 }
52 or die <<EOD;
53 ############
54 ### This module uses frobnication framework which is not available before
55 ### version 5.007 of Perl. Upgrade your Perl before installing Kara::Mba.
56 ############
57 EOD
c07a80fd 58
360e660c 59=head2 Dynamic Loading versus Static Loading
c07a80fd
PP
60
61It is commonly thought that if a system does not have the capability to
360e660c
GS
62dynamically load a library, you cannot build XSUBs. This is incorrect.
63You I<can> build them, but you must link the XSUBs subroutines with the
c07a80fd
PP
64rest of Perl, creating a new executable. This situation is similar to
65Perl 4.
66
67This tutorial can still be used on such a system. The XSUB build mechanism
68will check the system and build a dynamically-loadable library if possible,
69or else a static library and then, optionally, a new statically-linked
70executable with that static library linked in.
71
72Should you wish to build a statically-linked executable on a system which
73can dynamically load libraries, you may, in all the following examples,
360e660c
GS
74where the command "C<make>" with no arguments is executed, run the command
75"C<make perl>" instead.
c07a80fd
PP
76
77If you have generated such a statically-linked executable by choice, then
360e660c
GS
78instead of saying "C<make test>", you should say "C<make test_static>".
79On systems that cannot build dynamically-loadable libraries at all, simply
80saying "C<make test>" is sufficient.
81
82=head1 TUTORIAL
83
84Now let's go on with the show!
c07a80fd
PP
85
86=head2 EXAMPLE 1
4633a7c4
LW
87
88Our first extension will be very simple. When we call the routine in the
c07a80fd 89extension, it will print out a well-known message and return.
4633a7c4 90
360e660c
GS
91Run "C<h2xs -A -n Mytest>". This creates a directory named Mytest,
92possibly under ext/ if that directory exists in the current working
21afb104
YST
93directory. Several files will be created under the Mytest dir, including
94MANIFEST, Makefile.PL, lib/Mytest.pm, Mytest.xs, t/Mytest.t, and Changes.
4633a7c4 95
360e660c
GS
96The MANIFEST file contains the names of all the files just created in the
97Mytest directory.
4633a7c4
LW
98
99The file Makefile.PL should look something like this:
100
eb3fb7ac
RB
101 use ExtUtils::MakeMaker;
102 # See lib/ExtUtils/MakeMaker.pm for details of how to influence
103 # the contents of the Makefile that is written.
104 WriteMakefile(
105 NAME => 'Mytest',
106 VERSION_FROM => 'Mytest.pm', # finds $VERSION
107 LIBS => [''], # e.g., '-lm'
108 DEFINE => '', # e.g., '-DHAVE_SOMETHING'
109 INC => '', # e.g., '-I/usr/include/other'
110 );
4633a7c4 111
791fa977 112The file Mytest.pm should start with something like this:
c07a80fd 113
eb3fb7ac 114 package Mytest;
4633a7c4 115
eb3fb7ac
RB
116 use 5.008008;
117 use strict;
118 use warnings;
360e660c 119
eb3fb7ac 120 require Exporter;
c07a80fd 121
eb3fb7ac
RB
122 our @ISA = qw(Exporter);
123 our %EXPORT_TAGS = ( 'all' => [ qw(
c07a80fd 124
eb3fb7ac
RB
125 ) ] );
126
127 our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
c07a80fd 128
eb3fb7ac 129 our @EXPORT = qw(
c07a80fd 130
eb3fb7ac 131 );
c07a80fd 132
eb3fb7ac 133 our $VERSION = '0.01';
c07a80fd 134
eb3fb7ac
RB
135 require XSLoader;
136 XSLoader::load('Mytest', $VERSION);
137
138 # Preloaded methods go here.
139
140 1;
141 __END__
142 # Below is the stub of documentation for your module. You better edit it!
4633a7c4 143
360e660c
GS
144The rest of the .pm file contains sample code for providing documentation for
145the extension.
146
147Finally, the Mytest.xs file should look something like this:
4633a7c4 148
eb3fb7ac
RB
149 #include "EXTERN.h"
150 #include "perl.h"
151 #include "XSUB.h"
791fa977 152
eb3fb7ac
RB
153 #include "ppport.h"
154
155 MODULE = Mytest PACKAGE = Mytest
4633a7c4
LW
156
157Let's edit the .xs file by adding this to the end of the file:
158
eb3fb7ac
RB
159 void
160 hello()
161 CODE:
162 printf("Hello, world!\n");
4633a7c4 163
360e660c
GS
164It is okay for the lines starting at the "CODE:" line to not be indented.
165However, for readability purposes, it is suggested that you indent CODE:
166one level and the lines following one more level.
167
168Now we'll run "C<perl Makefile.PL>". This will create a real Makefile,
d9d2a7fb 169which make needs. Its output looks something like:
4633a7c4 170
eb3fb7ac
RB
171 % perl Makefile.PL
172 Checking if your kit is complete...
173 Looks good
174 Writing Makefile for Mytest
175 %
4633a7c4 176
360e660c
GS
177Now, running make will produce output that looks something like this (some
178long lines have been shortened for clarity and some extraneous lines have
179been deleted):
4633a7c4 180
eb3fb7ac
RB
181 % make
182 cp lib/Mytest.pm blib/lib/Mytest.pm
183 perl xsubpp -typemap typemap Mytest.xs > Mytest.xsc && mv Mytest.xsc Mytest.c
184 Please specify prototyping behavior for Mytest.xs (see perlxs manual)
185 cc -c Mytest.c
186 Running Mkbootstrap for Mytest ()
187 chmod 644 Mytest.bs
188 rm -f blib/arch/auto/Mytest/Mytest.so
189 cc -shared -L/usr/local/lib Mytest.o -o blib/arch/auto/Mytest/Mytest.so \
190 \
191
192 chmod 755 blib/arch/auto/Mytest/Mytest.so
193 cp Mytest.bs blib/arch/auto/Mytest/Mytest.bs
194 chmod 644 blib/arch/auto/Mytest/Mytest.bs
195 Manifying blib/man3/Mytest.3pm
196 %
360e660c 197
171891c7 198You can safely ignore the line about "prototyping behavior" - it is
5a7d1118 199explained in L<perlxs/"The PROTOTYPES: Keyword">.
360e660c 200
360e660c
GS
201Perl has its own special way of easily writing test scripts, but for this
202example only, we'll create our own test script. Create a file called hello
c07a80fd
PP
203that looks like this:
204
eb3fb7ac 205 #! /opt/perl5/bin/perl
c47ff5f1 206
eb3fb7ac 207 use ExtUtils::testlib;
c47ff5f1 208
eb3fb7ac 209 use Mytest;
c47ff5f1 210
eb3fb7ac 211 Mytest::hello();
4633a7c4 212
f4987be3 213Now we make the script executable (C<chmod +x hello>), run the script
360e660c 214and we should see the following output:
4633a7c4 215
eb3fb7ac
RB
216 % ./hello
217 Hello, world!
218 %
4633a7c4 219
c07a80fd 220=head2 EXAMPLE 2
4633a7c4 221
360e660c 222Now let's add to our extension a subroutine that will take a single numeric
010f0c4b 223argument as input and return 1 if the number is even or 0 if the number
360e660c 224is odd.
4633a7c4 225
791fa977 226Add the following to the end of Mytest.xs:
4633a7c4 227
eb3fb7ac
RB
228 int
229 is_even(input)
230 int input
231 CODE:
232 RETVAL = (input % 2 == 0);
233 OUTPUT:
234 RETVAL
4633a7c4 235
6b0ac556 236There does not need to be whitespace at the start of the "C<int input>"
360e660c 237line, but it is useful for improving readability. Placing a semi-colon at
6b0ac556 238the end of that line is also optional. Any amount and kind of whitespace
360e660c 239may be placed between the "C<int>" and "C<input>".
4633a7c4 240
360e660c 241Now re-run make to rebuild our new shared library.
4633a7c4 242
c07a80fd
PP
243Now perform the same steps as before, generating a Makefile from the
244Makefile.PL file, and running make.
4633a7c4 245
360e660c 246In order to test that our extension works, we now need to look at the
eb3fb7ac 247file Mytest.t. This file is set up to imitate the same kind of testing
c07a80fd
PP
248structure that Perl itself has. Within the test script, you perform a
249number of tests to confirm the behavior of the extension, printing "ok"
eb3fb7ac
RB
250when the test is correct, "not ok" when it is not.
251
252 use Test::More tests => 4;
253 BEGIN { use_ok('Mytest') };
254
255 #########################
c07a80fd 256
eb3fb7ac
RB
257 # Insert your test code below, the Test::More module is use()ed here so read
258 # its man page ( perldoc Test::More ) for help writing this test script.
259
260 is(&Mytest::is_even(0), 1);
261 is(&Mytest::is_even(1), 0);
262 is(&Mytest::is_even(2), 1);
c07a80fd 263
360e660c 264We will be calling the test script through the command "C<make test>". You
c07a80fd
PP
265should see output that looks something like this:
266
eb3fb7ac
RB
267 %make test
268 PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
269 t/Mytest....ok
270 All tests successful.
271 Files=1, Tests=4, 0 wallclock secs ( 0.03 cusr + 0.00 csys = 0.03 CPU)
272 %
4633a7c4 273
360e660c 274=head2 What has gone on?
4633a7c4
LW
275
276The program h2xs is the starting point for creating extensions. In later
c07a80fd 277examples we'll see how we can use h2xs to read header files and generate
4633a7c4
LW
278templates to connect to C routines.
279
280h2xs creates a number of files in the extension directory. The file
281Makefile.PL is a perl script which will generate a true Makefile to build
282the extension. We'll take a closer look at it later.
283
360e660c
GS
284The .pm and .xs files contain the meat of the extension. The .xs file holds
285the C routines that make up the extension. The .pm file contains routines
286that tell Perl how to load your extension.
287
288Generating the Makefile and running C<make> created a directory called blib
289(which stands for "build library") in the current working directory. This
290directory will contain the shared library that we will build. Once we have
291tested it, we can install it into its final location.
292
293Invoking the test script via "C<make test>" did something very important.
294It invoked perl with all those C<-I> arguments so that it could find the
295various files that are part of the extension. It is I<very> important that
296while you are still testing extensions that you use "C<make test>". If you
297try to run the test script all by itself, you will get a fatal error.
298Another reason it is important to use "C<make test>" to run your test
299script is that if you are testing an upgrade to an already-existing version,
6985a70b 300using "C<make test>" ensures that you will test your new extension, not the
360e660c 301already-existing version.
4633a7c4 302
c07a80fd 303When Perl sees a C<use extension;>, it searches for a file with the same name
360e660c 304as the C<use>'d extension that has a .pm suffix. If that file cannot be found,
c07a80fd 305Perl dies with a fatal error. The default search path is contained in the
360e660c 306C<@INC> array.
4633a7c4 307
791fa977 308In our case, Mytest.pm tells perl that it will need the Exporter and Dynamic
360e660c
GS
309Loader extensions. It then sets the C<@ISA> and C<@EXPORT> arrays and the
310C<$VERSION> scalar; finally it tells perl to bootstrap the module. Perl
311will call its dynamic loader routine (if there is one) and load the shared
312library.
4633a7c4 313
360e660c 314The two arrays C<@ISA> and C<@EXPORT> are very important. The C<@ISA>
c07a80fd 315array contains a list of other packages in which to search for methods (or
360e660c
GS
316subroutines) that do not exist in the current package. This is usually
317only important for object-oriented extensions (which we will talk about
318much later), and so usually doesn't need to be modified.
4633a7c4 319
360e660c
GS
320The C<@EXPORT> array tells Perl which of the extension's variables and
321subroutines should be placed into the calling package's namespace. Because
322you don't know if the user has already used your variable and subroutine
323names, it's vitally important to carefully select what to export. Do I<not>
324export method or variable names I<by default> without a good reason.
4633a7c4 325
c07a80fd 326As a general rule, if the module is trying to be object-oriented then don't
360e660c
GS
327export anything. If it's just a collection of functions and variables, then
328you can export them via another array, called C<@EXPORT_OK>. This array
329does not automatically place its subroutine and variable names into the
330namespace unless the user specifically requests that this be done.
4633a7c4 331
c07a80fd 332See L<perlmod> for more information.
4633a7c4 333
360e660c 334The C<$VERSION> variable is used to ensure that the .pm file and the shared
791fa977
PP
335library are "in sync" with each other. Any time you make changes to
336the .pm or .xs files, you should increment the value of this variable.
337
360e660c 338=head2 Writing good test scripts
791fa977 339
353c6505 340The importance of writing good test scripts cannot be over-emphasized. You
791fa977
PP
341should closely follow the "ok/not ok" style that Perl itself uses, so that
342it is very easy and unambiguous to determine the outcome of each test case.
343When you find and fix a bug, make sure you add a test case for it.
344
eb3fb7ac
RB
345By running "C<make test>", you ensure that your Mytest.t script runs and uses
346the correct version of your extension. If you have many test cases,
347save your test files in the "t" directory and use the suffix ".t".
348When you run "C<make test>", all of these test files will be executed.
4633a7c4 349
c07a80fd 350=head2 EXAMPLE 3
4633a7c4
LW
351
352Our third extension will take one argument as its input, round off that
c07a80fd 353value, and set the I<argument> to the rounded value.
4633a7c4 354
791fa977 355Add the following to the end of Mytest.xs:
4633a7c4
LW
356
357 void
358 round(arg)
359 double arg
360e660c 360 CODE:
4633a7c4
LW
361 if (arg > 0.0) {
362 arg = floor(arg + 0.5);
363 } else if (arg < 0.0) {
364 arg = ceil(arg - 0.5);
365 } else {
366 arg = 0.0;
367 }
360e660c 368 OUTPUT:
4633a7c4
LW
369 arg
370
c07a80fd 371Edit the Makefile.PL file so that the corresponding line looks like this:
4633a7c4
LW
372
373 'LIBS' => ['-lm'], # e.g., '-lm'
374
eb3fb7ac
RB
375Generate the Makefile and run make. Change the test number in Mytest.t to
376"9" and add the following tests:
4633a7c4 377
eb3fb7ac
RB
378 $i = -1.5; &Mytest::round($i); is( $i, -2.0 );
379 $i = -1.1; &Mytest::round($i); is( $i, -1.0 );
380 $i = 0.0; &Mytest::round($i); is( $i, 0.0 );
381 $i = 0.5; &Mytest::round($i); is( $i, 1.0 );
382 $i = 1.2; &Mytest::round($i); is( $i, 1.0 );
c07a80fd 383
360e660c 384Running "C<make test>" should now print out that all nine tests are okay.
4633a7c4 385
360e660c
GS
386Notice that in these new test cases, the argument passed to round was a
387scalar variable. You might be wondering if you can round a constant or
eb3fb7ac 388literal. To see what happens, temporarily add the following line to Mytest.t:
4633a7c4 389
791fa977 390 &Mytest::round(3);
4633a7c4 391
360e660c
GS
392Run "C<make test>" and notice that Perl dies with a fatal error. Perl won't
393let you change the value of constants!
4633a7c4 394
360e660c 395=head2 What's new here?
4633a7c4 396
360e660c 397=over 4
4633a7c4 398
360e660c 399=item *
4633a7c4 400
360e660c
GS
401We've made some changes to Makefile.PL. In this case, we've specified an
402extra library to be linked into the extension's shared library, the math
403library libm in this case. We'll talk later about how to write XSUBs that
404can call every routine in a library.
4633a7c4 405
360e660c
GS
406=item *
407
408The value of the function is not being passed back as the function's return
409value, but by changing the value of the variable that was passed into the
410function. You might have guessed that when you saw that the return value
411of round is of type "void".
412
413=back
414
415=head2 Input and Output Parameters
4633a7c4 416
360e660c
GS
417You specify the parameters that will be passed into the XSUB on the line(s)
418after you declare the function's return value and name. Each input parameter
6b0ac556 419line starts with optional whitespace, and may have an optional terminating
360e660c 420semicolon.
4633a7c4 421
360e660c 422The list of output parameters occurs at the very end of the function, just
5a7d1118 423after the OUTPUT: directive. The use of RETVAL tells Perl that you
360e660c
GS
424wish to send this value back as the return value of the XSUB function. In
425Example 3, we wanted the "return value" placed in the original variable
426which we passed in, so we listed it (and not RETVAL) in the OUTPUT: section.
4633a7c4 427
360e660c
GS
428=head2 The XSUBPP Program
429
beb31b0b 430The B<xsubpp> program takes the XS code in the .xs file and translates it into
4633a7c4
LW
431C code, placing it in a file whose suffix is .c. The C code created makes
432heavy use of the C functions within Perl.
433
360e660c 434=head2 The TYPEMAP file
4633a7c4 435
beb31b0b 436The B<xsubpp> program uses rules to convert from Perl's data types (scalar,
360e660c 437array, etc.) to C's data types (int, char, etc.). These rules are stored
78a4b226
SM
438in the typemap file ($PERLLIB/ExtUtils/typemap). There's a brief discussion
439below, but all the nitty-gritty details can be found in L<perlxstypemap>.
440If you have a new-enough version of perl (5.16 and up) or an upgraded
441XS compiler (C<ExtUtils::ParseXS> 3.13_01 or better), then you can inline
442typemaps in your XS instead of writing separate files.
443Either way, this typemap thing is split into three parts:
4633a7c4 444
360e660c
GS
445The first section maps various C data types to a name, which corresponds
446somewhat with the various Perl types. The second section contains C code
beb31b0b
GS
447which B<xsubpp> uses to handle input parameters. The third section contains
448C code which B<xsubpp> uses to handle output parameters.
4633a7c4 449
360e660c
GS
450Let's take a look at a portion of the .c file created for our extension.
451The file name is Mytest.c:
4633a7c4 452
791fa977 453 XS(XS_Mytest_round)
4633a7c4
LW
454 {
455 dXSARGS;
c07a80fd 456 if (items != 1)
eb3fb7ac 457 Perl_croak(aTHX_ "Usage: Mytest::round(arg)");
eaa72df2 458 PERL_UNUSED_VAR(cv); /* -W */
4633a7c4 459 {
c07a80fd 460 double arg = (double)SvNV(ST(0)); /* XXXXX */
4633a7c4
LW
461 if (arg > 0.0) {
462 arg = floor(arg + 0.5);
463 } else if (arg < 0.0) {
464 arg = ceil(arg - 0.5);
c07a80fd
PP
465 } else {
466 arg = 0.0;
4633a7c4 467 }
360e660c 468 sv_setnv(ST(0), (double)arg); /* XXXXX */
eaa72df2 469 SvSETMAGIC(ST(0));
4633a7c4 470 }
eb3fb7ac 471 XSRETURN_EMPTY;
4633a7c4 472 }
4633a7c4 473
78a4b226
SM
474Notice the two lines commented with "XXXXX". If you check the first part
475of the typemap file (or section), you'll see that doubles are of type
476T_DOUBLE. In the INPUT part of the typemap, an argument that is T_DOUBLE
477is assigned to the variable arg by calling the routine SvNV on something,
478then casting it to double, then assigned to the variable arg. Similarly,
479in the OUTPUT section, once arg has its final value, it is passed to the
480sv_setnv function to be passed back to the calling subroutine. These two
481functions are explained in L<perlguts>; we'll talk more later about what
482that "ST(0)" means in the section on the argument stack.
4633a7c4 483
360e660c 484=head2 Warning about Output Arguments
4633a7c4 485
c07a80fd 486In general, it's not a good idea to write extensions that modify their input
360e660c
GS
487parameters, as in Example 3. Instead, you should probably return multiple
488values in an array and let the caller handle them (we'll do this in a later
a2293a43 489example). However, in order to better accommodate calling pre-existing C
360e660c
GS
490routines, which often do modify their input parameters, this behavior is
491tolerated.
791fa977
PP
492
493=head2 EXAMPLE 4
494
68dc0745 495In this example, we'll now begin to write XSUBs that will interact with
360e660c 496pre-defined C libraries. To begin with, we will build a small library of
791fa977
PP
497our own, then let h2xs write our .pm and .xs files for us.
498
499Create a new directory called Mytest2 at the same level as the directory
500Mytest. In the Mytest2 directory, create another directory called mylib,
501and cd into that directory.
502
503Here we'll create some files that will generate a test library. These will
504include a C source file and a header file. We'll also create a Makefile.PL
505in this directory. Then we'll make sure that running make at the Mytest2
506level will automatically run this Makefile.PL file and the resulting Makefile.
507
9693b09d 508In the mylib directory, create a file mylib.h that looks like this:
791fa977
PP
509
510 #define TESTVAL 4
511
512 extern double foo(int, long, const char*);
513
514Also create a file mylib.c that looks like this:
515
516 #include <stdlib.h>
517 #include "./mylib.h"
c47ff5f1 518
791fa977 519 double
360e660c 520 foo(int a, long b, const char *c)
791fa977
PP
521 {
522 return (a + b + atof(c) + TESTVAL);
523 }
524
525And finally create a file Makefile.PL that looks like this:
526
527 use ExtUtils::MakeMaker;
528 $Verbose = 1;
529 WriteMakefile(
360e660c
GS
530 NAME => 'Mytest2::mylib',
531 SKIP => [qw(all static static_lib dynamic dynamic_lib)],
49733319 532 clean => {'FILES' => 'libmylib$(LIB_EXT)'},
791fa977
PP
533 );
534
535
8227f81c 536 sub MY::top_targets {
791fa977
PP
537 '
538 all :: static
539
360e660c
GS
540 pure_all :: static
541
791fa977
PP
542 static :: libmylib$(LIB_EXT)
543
544 libmylib$(LIB_EXT): $(O_FILES)
545 $(AR) cr libmylib$(LIB_EXT) $(O_FILES)
546 $(RANLIB) libmylib$(LIB_EXT)
547
548 ';
549 }
550
360e660c
GS
551Make sure you use a tab and not spaces on the lines beginning with "$(AR)"
552and "$(RANLIB)". Make will not function properly if you use spaces.
553It has also been reported that the "cr" argument to $(AR) is unnecessary
554on Win32 systems.
555
791fa977
PP
556We will now create the main top-level Mytest2 files. Change to the directory
557above Mytest2 and run the following command:
558
d9d2a7fb 559 % h2xs -O -n Mytest2 ./Mytest2/mylib/mylib.h
791fa977
PP
560
561This will print out a warning about overwriting Mytest2, but that's okay.
562Our files are stored in Mytest2/mylib, and will be untouched.
563
564The normal Makefile.PL that h2xs generates doesn't know about the mylib
565directory. We need to tell it that there is a subdirectory and that we
360e660c
GS
566will be generating a library in it. Let's add the argument MYEXTLIB to
567the WriteMakefile call so that it looks like this:
4633a7c4 568
360e660c
GS
569 WriteMakefile(
570 'NAME' => 'Mytest2',
571 'VERSION_FROM' => 'Mytest2.pm', # finds $VERSION
572 'LIBS' => [''], # e.g., '-lm'
573 'DEFINE' => '', # e.g., '-DHAVE_SOMETHING'
574 'INC' => '', # e.g., '-I/usr/include/other'
575 'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)',
576 );
791fa977 577
360e660c
GS
578and then at the end add a subroutine (which will override the pre-existing
579subroutine). Remember to use a tab character to indent the line beginning
580with "cd"!
791fa977
PP
581
582 sub MY::postamble {
583 '
584 $(MYEXTLIB): mylib/Makefile
360e660c 585 cd mylib && $(MAKE) $(PASSTHRU)
791fa977
PP
586 ';
587 }
588
791fa977
PP
589Let's also fix the MANIFEST file so that it accurately reflects the contents
590of our extension. The single line that says "mylib" should be replaced by
591the following three lines:
592
593 mylib/Makefile.PL
594 mylib/mylib.c
595 mylib/mylib.h
596
597To keep our namespace nice and unpolluted, edit the .pm file and change
77ca0c92 598the variable C<@EXPORT> to C<@EXPORT_OK>. Finally, in the
d9d2a7fb 599.xs file, edit the #include line to read:
791fa977
PP
600
601 #include "mylib/mylib.h"
602
603And also add the following function definition to the end of the .xs file:
604
605 double
606 foo(a,b,c)
607 int a
608 long b
609 const char * c
360e660c 610 OUTPUT:
791fa977
PP
611 RETVAL
612
78a4b226
SM
613Now we also need to create a typemap because the default Perl doesn't
614currently support the C<const char *> type. Include a new TYPEMAP
615section in your XS code before the above function:
791fa977 616
78a4b226 617 TYPEMAP: <<END;
791fa977 618 const char * T_PV
78a4b226 619 END
791fa977
PP
620
621Now run perl on the top-level Makefile.PL. Notice that it also created a
360e660c 622Makefile in the mylib directory. Run make and watch that it does cd into
791fa977
PP
623the mylib directory and run make in there as well.
624
eb3fb7ac 625Now edit the Mytest2.t script and change the number of tests to "4",
791fa977
PP
626and add the following lines to the end of the script:
627
eb3fb7ac
RB
628 is( &Mytest2::foo(1, 2, "Hello, world!"), 7 );
629 is( &Mytest2::foo(1, 2, "0.0"), 7 );
630 ok( abs(&Mytest2::foo(0, 0, "-3.4") - 0.6) <= 0.01 );
791fa977 631
360e660c
GS
632(When dealing with floating-point comparisons, it is best to not check for
633equality, but rather that the difference between the expected and actual
634result is below a certain amount (called epsilon) which is 0.01 in this case)
791fa977 635
eb3fb7ac
RB
636Run "C<make test>" and all should be well. There are some warnings on missing tests
637for the Mytest2::mylib extension, but you can ignore them.
791fa977 638
360e660c 639=head2 What has happened here?
791fa977
PP
640
641Unlike previous examples, we've now run h2xs on a real include file. This
642has caused some extra goodies to appear in both the .pm and .xs files.
643
84dc3c4d
PP
644=over 4
645
791fa977
PP
646=item *
647
360e660c
GS
648In the .xs file, there's now a #include directive with the absolute path to
649the mylib.h header file. We changed this to a relative path so that we
650could move the extension directory if we wanted to.
791fa977
PP
651
652=item *
653
654There's now some new C code that's been added to the .xs file. The purpose
655of the C<constant> routine is to make the values that are #define'd in the
360e660c
GS
656header file accessible by the Perl script (by calling either C<TESTVAL> or
657C<&Mytest2::TESTVAL>). There's also some XS code to allow calls to the
791fa977
PP
658C<constant> routine.
659
660=item *
661
360e660c
GS
662The .pm file originally exported the name C<TESTVAL> in the C<@EXPORT> array.
663This could lead to name clashes. A good rule of thumb is that if the #define
664is only going to be used by the C routines themselves, and not by the user,
665they should be removed from the C<@EXPORT> array. Alternately, if you don't
666mind using the "fully qualified name" of a variable, you could move most
667or all of the items from the C<@EXPORT> array into the C<@EXPORT_OK> array.
791fa977 668
d9d2a7fb
PP
669=item *
670
360e660c
GS
671If our include file had contained #include directives, these would not have
672been processed by h2xs. There is no good solution to this right now.
d9d2a7fb 673
360e660c 674=item *
791fa977
PP
675
676We've also told Perl about the library that we built in the mylib
360e660c 677subdirectory. That required only the addition of the C<MYEXTLIB> variable
791fa977
PP
678to the WriteMakefile call and the replacement of the postamble subroutine
679to cd into the subdirectory and run make. The Makefile.PL for the
680library is a bit more complicated, but not excessively so. Again we
681replaced the postamble subroutine to insert our own code. This code
360e660c
GS
682simply specified that the library to be created here was a static archive
683library (as opposed to a dynamically loadable library) and provided the
791fa977 684commands to build it.
4633a7c4 685
360e660c
GS
686=back
687
beb31b0b
GS
688=head2 Anatomy of .xs file
689
690The .xs file of L<"EXAMPLE 4"> contained some new elements. To understand
691the meaning of these elements, pay attention to the line which reads
692
eb3fb7ac 693 MODULE = Mytest2 PACKAGE = Mytest2
beb31b0b
GS
694
695Anything before this line is plain C code which describes which headers
696to include, and defines some convenience functions. No translations are
7817ba4d
NC
697performed on this part, apart from having embedded POD documentation
698skipped over (see L<perlpod>) it goes into the generated output C file as is.
beb31b0b
GS
699
700Anything after this line is the description of XSUB functions.
701These descriptions are translated by B<xsubpp> into C code which
702implements these functions using Perl calling conventions, and which
703makes these functions visible from Perl interpreter.
704
705Pay a special attention to the function C<constant>. This name appears
706twice in the generated .xs file: once in the first part, as a static C
f4987be3 707function, then another time in the second part, when an XSUB interface to
beb31b0b
GS
708this static C function is defined.
709
710This is quite typical for .xs files: usually the .xs file provides
711an interface to an existing C function. Then this C function is defined
712somewhere (either in an external library, or in the first part of .xs file),
713and a Perl interface to this function (i.e. "Perl glue") is described in the
714second part of .xs file. The situation in L<"EXAMPLE 1">, L<"EXAMPLE 2">,
715and L<"EXAMPLE 3">, when all the work is done inside the "Perl glue", is
716somewhat of an exception rather than the rule.
717
718=head2 Getting the fat out of XSUBs
719
720In L<"EXAMPLE 4"> the second part of .xs file contained the following
721description of an XSUB:
722
723 double
724 foo(a,b,c)
725 int a
726 long b
727 const char * c
728 OUTPUT:
729 RETVAL
730
731Note that in contrast with L<"EXAMPLE 1">, L<"EXAMPLE 2"> and L<"EXAMPLE 3">,
732this description does not contain the actual I<code> for what is done
313ce23f 733during a call to Perl function foo(). To understand what is going
beb31b0b
GS
734on here, one can add a CODE section to this XSUB:
735
736 double
737 foo(a,b,c)
738 int a
739 long b
740 const char * c
741 CODE:
742 RETVAL = foo(a,b,c);
743 OUTPUT:
744 RETVAL
745
746However, these two XSUBs provide almost identical generated C code: B<xsubpp>
747compiler is smart enough to figure out the C<CODE:> section from the first
748two lines of the description of XSUB. What about C<OUTPUT:> section? In
749fact, that is absolutely the same! The C<OUTPUT:> section can be removed
750as well, I<as far as C<CODE:> section or C<PPCODE:> section> is not
751specified: B<xsubpp> can see that it needs to generate a function call
752section, and will autogenerate the OUTPUT section too. Thus one can
753shortcut the XSUB to become:
754
755 double
756 foo(a,b,c)
757 int a
758 long b
759 const char * c
760
761Can we do the same with an XSUB
762
763 int
764 is_even(input)
765 int input
766 CODE:
767 RETVAL = (input % 2 == 0);
768 OUTPUT:
769 RETVAL
770
771of L<"EXAMPLE 2">? To do this, one needs to define a C function C<int
772is_even(int input)>. As we saw in L<Anatomy of .xs file>, a proper place
773for this definition is in the first part of .xs file. In fact a C function
774
775 int
776 is_even(int arg)
777 {
778 return (arg % 2 == 0);
779 }
780
781is probably overkill for this. Something as simple as a C<#define> will
782do too:
783
784 #define is_even(arg) ((arg) % 2 == 0)
785
786After having this in the first part of .xs file, the "Perl glue" part becomes
787as simple as
788
789 int
790 is_even(input)
791 int input
792
793This technique of separation of the glue part from the workhorse part has
794obvious tradeoffs: if you want to change a Perl interface, you need to
795change two places in your code. However, it removes a lot of clutter,
796and makes the workhorse part independent from idiosyncrasies of Perl calling
797convention. (In fact, there is nothing Perl-specific in the above description,
798a different version of B<xsubpp> might have translated this to TCL glue or
799Python glue as well.)
800
801=head2 More about XSUB arguments
4633a7c4 802
791fa977 803With the completion of Example 4, we now have an easy way to simulate some
c07a80fd
PP
804real-life libraries whose interfaces may not be the cleanest in the world.
805We shall now continue with a discussion of the arguments passed to the
beb31b0b 806B<xsubpp> compiler.
4633a7c4 807
360e660c
GS
808When you specify arguments to routines in the .xs file, you are really
809passing three pieces of information for each argument listed. The first
810piece is the order of that argument relative to the others (first, second,
811etc). The second is the type of argument, and consists of the type
812declaration of the argument (e.g., int, char*, etc). The third piece is
8dcb5783 813the calling convention for the argument in the call to the library function.
beb31b0b
GS
814
815While Perl passes arguments to functions by reference,
816C passes arguments by value; to implement a C function which modifies data
817of one of the "arguments", the actual argument of this C function would be
818a pointer to the data. Thus two C functions with declarations
819
820 int string_length(char *s);
821 int upper_case_char(char *cp);
822
823may have completely different semantics: the first one may inspect an array
824of chars pointed by s, and the second one may immediately dereference C<cp>
825and manipulate C<*cp> only (using the return value as, say, a success
826indicator). From Perl one would use these functions in
827a completely different manner.
828
829One conveys this info to B<xsubpp> by replacing C<*> before the
830argument by C<&>. C<&> means that the argument should be passed to a library
831function by its address. The above two function may be XSUB-ified as
832
833 int
834 string_length(s)
835 char * s
836
837 int
838 upper_case_char(cp)
839 char &cp
4633a7c4 840
beb31b0b 841For example, consider:
4633a7c4 842
4633a7c4 843 int
c07a80fd
PP
844 foo(a,b)
845 char &a
846 char * b
4633a7c4 847
beb31b0b 848The first Perl argument to this function would be treated as a char and assigned
c07a80fd 849to the variable a, and its address would be passed into the function foo.
beb31b0b 850The second Perl argument would be treated as a string pointer and assigned to the
c07a80fd 851variable b. The I<value> of b would be passed into the function foo. The
beb31b0b 852actual call to the function foo that B<xsubpp> generates would look like this:
4633a7c4 853
c07a80fd 854 foo(&a, b);
4633a7c4 855
beb31b0b 856B<xsubpp> will parse the following function argument lists identically:
791fa977
PP
857
858 char &a
859 char&a
860 char & a
861
862However, to help ease understanding, it is suggested that you place a "&"
863next to the variable name and away from the variable type), and place a
864"*" near the variable type, but away from the variable name (as in the
360e660c 865call to foo above). By doing so, it is easy to understand exactly what
ac036724 866will be passed to the C function; it will be whatever is in the "last
360e660c 867column".
4633a7c4 868
c07a80fd
PP
869You should take great pains to try to pass the function the type of variable
870it wants, when possible. It will save you a lot of trouble in the long run.
4633a7c4 871
360e660c 872=head2 The Argument Stack
4633a7c4 873
c07a80fd
PP
874If we look at any of the C code generated by any of the examples except
875example 1, you will notice a number of references to ST(n), where n is
360e660c
GS
876usually 0. "ST" is actually a macro that points to the n'th argument
877on the argument stack. ST(0) is thus the first argument on the stack and
878therefore the first argument passed to the XSUB, ST(1) is the second
879argument, and so on.
4633a7c4 880
beb31b0b 881When you list the arguments to the XSUB in the .xs file, that tells B<xsubpp>
c07a80fd
PP
882which argument corresponds to which of the argument stack (i.e., the first
883one listed is the first argument, and so on). You invite disaster if you
884do not list them in the same order as the function expects them.
4633a7c4 885
360e660c
GS
886The actual values on the argument stack are pointers to the values passed
887in. When an argument is listed as being an OUTPUT value, its corresponding
888value on the stack (i.e., ST(0) if it was the first argument) is changed.
889You can verify this by looking at the C code generated for Example 3.
890The code for the round() XSUB routine contains lines that look like this:
891
892 double arg = (double)SvNV(ST(0));
893 /* Round the contents of the variable arg */
894 sv_setnv(ST(0), (double)arg);
895
896The arg variable is initially set by taking the value from ST(0), then is
897stored back into ST(0) at the end of the routine.
898
beb31b0b
GS
899XSUBs are also allowed to return lists, not just scalars. This must be
900done by manipulating stack values ST(0), ST(1), etc, in a subtly
901different way. See L<perlxs> for details.
902
903XSUBs are also allowed to avoid automatic conversion of Perl function arguments
904to C function arguments. See L<perlxs> for details. Some people prefer
905manual conversion by inspecting C<ST(i)> even in the cases when automatic
906conversion will do, arguing that this makes the logic of an XSUB call clearer.
907Compare with L<"Getting the fat out of XSUBs"> for a similar tradeoff of
908a complete separation of "Perl glue" and "workhorse" parts of an XSUB.
909
910While experts may argue about these idioms, a novice to Perl guts may
911prefer a way which is as little Perl-guts-specific as possible, meaning
912automatic conversion and automatic call generation, as in
913L<"Getting the fat out of XSUBs">. This approach has the additional
914benefit of protecting the XSUB writer from future changes to the Perl API.
915
360e660c 916=head2 Extending your Extension
4633a7c4 917
c07a80fd
PP
918Sometimes you might want to provide some extra methods or subroutines
919to assist in making the interface between Perl and your extension simpler
920or easier to understand. These routines should live in the .pm file.
921Whether they are automatically loaded when the extension itself is loaded
360e660c 922or only loaded when called depends on where in the .pm file the subroutine
4a4eefd0 923definition is placed. You can also consult L<AutoLoader> for an alternate
360e660c 924way to store and load your extra subroutines.
4633a7c4 925
360e660c 926=head2 Documenting your Extension
4633a7c4 927
c07a80fd
PP
928There is absolutely no excuse for not documenting your extension.
929Documentation belongs in the .pm file. This file will be fed to pod2man,
3958b146
JH
930and the embedded documentation will be converted to the manpage format,
931then placed in the blib directory. It will be copied to Perl's
932manpage directory when the extension is installed.
4633a7c4 933
c07a80fd
PP
934You may intersperse documentation and Perl code within the .pm file.
935In fact, if you want to use method autoloading, you must do this,
936as the comment inside the .pm file explains.
4633a7c4 937
c07a80fd 938See L<perlpod> for more information about the pod format.
4633a7c4 939
360e660c 940=head2 Installing your Extension
4633a7c4 941
c07a80fd 942Once your extension is complete and passes all its tests, installing it
8dcb5783 943is quite simple: you simply run "make install". You will either need
c07a80fd
PP
944to have write permission into the directories where Perl is installed,
945or ask your system administrator to run the make for you.
4633a7c4 946
360e660c
GS
947Alternately, you can specify the exact directory to place the extension's
948files by placing a "PREFIX=/destination/directory" after the make install.
949(or in between the make and install if you have a brain-dead version of make).
950This can be very useful if you are building an extension that will eventually
951be distributed to multiple systems. You can then just archive the files in
952the destination directory and distribute them to your destination systems.
953
954=head2 EXAMPLE 5
955
956In this example, we'll do some more work with the argument stack. The
957previous examples have all returned only a single value. We'll now
958create an extension that returns an array.
959
960This extension is very Unix-oriented (struct statfs and the statfs system
961call). If you are not running on a Unix system, you can substitute for
962statfs any other function that returns multiple values, you can hard-code
963values to be returned to the caller (although this will be a bit harder
964to test the error case), or you can simply not do this example. If you
965change the XSUB, be sure to fix the test cases to match the changes.
966
967Return to the Mytest directory and add the following code to the end of
968Mytest.xs:
969
970 void
971 statfs(path)
972 char * path
beb31b0b 973 INIT:
360e660c
GS
974 int i;
975 struct statfs buf;
976
977 PPCODE:
978 i = statfs(path, &buf);
979 if (i == 0) {
980 XPUSHs(sv_2mortal(newSVnv(buf.f_bavail)));
981 XPUSHs(sv_2mortal(newSVnv(buf.f_bfree)));
982 XPUSHs(sv_2mortal(newSVnv(buf.f_blocks)));
983 XPUSHs(sv_2mortal(newSVnv(buf.f_bsize)));
984 XPUSHs(sv_2mortal(newSVnv(buf.f_ffree)));
985 XPUSHs(sv_2mortal(newSVnv(buf.f_files)));
986 XPUSHs(sv_2mortal(newSVnv(buf.f_type)));
360e660c
GS
987 } else {
988 XPUSHs(sv_2mortal(newSVnv(errno)));
989 }
990
991You'll also need to add the following code to the top of the .xs file, just
992after the include of "XSUB.h":
993
994 #include <sys/vfs.h>
995
eb3fb7ac
RB
996Also add the following code segment to Mytest.t while incrementing the "9"
997tests to "11":
360e660c
GS
998
999 @a = &Mytest::statfs("/blech");
eb3fb7ac 1000 ok( scalar(@a) == 1 && $a[0] == 2 );
360e660c 1001 @a = &Mytest::statfs("/");
eb3fb7ac 1002 is( scalar(@a), 7 );
360e660c
GS
1003
1004=head2 New Things in this Example
1005
1006This example added quite a few new concepts. We'll take them one at a time.
1007
1008=over 4
1009
1010=item *
1011
beb31b0b
GS
1012The INIT: directive contains code that will be placed immediately after
1013the argument stack is decoded. C does not allow variable declarations at
1014arbitrary locations inside a function,
360e660c 1015so this is usually the best way to declare local variables needed by the XSUB.
beb31b0b
GS
1016(Alternatively, one could put the whole C<PPCODE:> section into braces, and
1017put these declarations on top.)
360e660c
GS
1018
1019=item *
1020
1021This routine also returns a different number of arguments depending on the
1022success or failure of the call to statfs. If there is an error, the error
1023number is returned as a single-element array. If the call is successful,
256771e2
HQ
1024then a 7-element array is returned. Since only one argument is passed into
1025this function, we need room on the stack to hold the 7 values which may be
360e660c
GS
1026returned.
1027
1028We do this by using the PPCODE: directive, rather than the CODE: directive.
beb31b0b 1029This tells B<xsubpp> that we will be managing the return values that will be
360e660c
GS
1030put on the argument stack by ourselves.
1031
1032=item *
1033
1034When we want to place values to be returned to the caller onto the stack,
1035we use the series of macros that begin with "XPUSH". There are five
1036different versions, for placing integers, unsigned integers, doubles,
1037strings, and Perl scalars on the stack. In our example, we placed a
beb31b0b
GS
1038Perl scalar onto the stack. (In fact this is the only macro which
1039can be used to return multiple values.)
360e660c
GS
1040
1041The XPUSH* macros will automatically extend the return stack to prevent
1042it from being overrun. You push values onto the stack in the order you
1043want them seen by the calling program.
1044
1045=item *
1046
1047The values pushed onto the return stack of the XSUB are actually mortal SV's.
1048They are made mortal so that once the values are copied by the calling
1049program, the SV's that held the returned values can be deallocated.
1050If they were not mortal, then they would continue to exist after the XSUB
1051routine returned, but would not be accessible. This is a memory leak.
1052
beb31b0b
GS
1053=item *
1054
1055If we were interested in performance, not in code compactness, in the success
1056branch we would not use C<XPUSHs> macros, but C<PUSHs> macros, and would
1057pre-extend the stack before pushing the return values:
1058
eb3fb7ac 1059 EXTEND(SP, 7);
beb31b0b
GS
1060
1061The tradeoff is that one needs to calculate the number of return values
1062in advance (though overextending the stack will not typically hurt
1063anything but memory consumption).
1064
1065Similarly, in the failure branch we could use C<PUSHs> I<without> extending
1066the stack: the Perl function reference comes to an XSUB on the stack, thus
1067the stack is I<always> large enough to take one return value.
1068
360e660c
GS
1069=back
1070
171891c7 1071=head2 EXAMPLE 6
360e660c 1072
171891c7
GS
1073In this example, we will accept a reference to an array as an input
1074parameter, and return a reference to an array of hashes. This will
1075demonstrate manipulation of complex Perl data types from an XSUB.
1076
1077This extension is somewhat contrived. It is based on the code in
1078the previous example. It calls the statfs function multiple times,
1079accepting a reference to an array of filenames as input, and returning
1080a reference to an array of hashes containing the data for each of the
1081filesystems.
1082
1083Return to the Mytest directory and add the following code to the end of
1084Mytest.xs:
1085
eb3fb7ac
RB
1086 SV *
1087 multi_statfs(paths)
1088 SV * paths
1089 INIT:
1090 AV * results;
1091 I32 numpaths = 0;
1092 int i, n;
1093 struct statfs buf;
1094
216f0275 1095 SvGETMAGIC(paths);
eb3fb7ac
RB
1096 if ((!SvROK(paths))
1097 || (SvTYPE(SvRV(paths)) != SVt_PVAV)
1098 || ((numpaths = av_len((AV *)SvRV(paths))) < 0))
1099 {
1100 XSRETURN_UNDEF;
1101 }
1102 results = (AV *)sv_2mortal((SV *)newAV());
1103 CODE:
1104 for (n = 0; n <= numpaths; n++) {
1105 HV * rh;
1106 STRLEN l;
1107 char * fn = SvPV(*av_fetch((AV *)SvRV(paths), n, 0), l);
1108
1109 i = statfs(fn, &buf);
1110 if (i != 0) {
1111 av_push(results, newSVnv(errno));
1112 continue;
1113 }
171891c7 1114
eb3fb7ac
RB
1115 rh = (HV *)sv_2mortal((SV *)newHV());
1116
1117 hv_store(rh, "f_bavail", 8, newSVnv(buf.f_bavail), 0);
1118 hv_store(rh, "f_bfree", 7, newSVnv(buf.f_bfree), 0);
1119 hv_store(rh, "f_blocks", 8, newSVnv(buf.f_blocks), 0);
1120 hv_store(rh, "f_bsize", 7, newSVnv(buf.f_bsize), 0);
1121 hv_store(rh, "f_ffree", 7, newSVnv(buf.f_ffree), 0);
1122 hv_store(rh, "f_files", 7, newSVnv(buf.f_files), 0);
1123 hv_store(rh, "f_type", 6, newSVnv(buf.f_type), 0);
1124
1125 av_push(results, newRV((SV *)rh));
1126 }
1127 RETVAL = newRV((SV *)results);
1128 OUTPUT:
1129 RETVAL
1130
1131And add the following code to Mytest.t, while incrementing the "11"
1132tests to "13":
171891c7
GS
1133
1134 $results = Mytest::multi_statfs([ '/', '/blech' ]);
256771e2 1135 ok( ref $results->[0] );
eb3fb7ac 1136 ok( ! ref $results->[1] );
171891c7
GS
1137
1138=head2 New Things in this Example
1139
1140There are a number of new concepts introduced here, described below:
1141
1142=over 4
1143
1144=item *
1145
1146This function does not use a typemap. Instead, we declare it as accepting
1147one SV* (scalar) parameter, and returning an SV* value, and we take care of
1148populating these scalars within the code. Because we are only returning
1149one value, we don't need a C<PPCODE:> directive - instead, we use C<CODE:>
1150and C<OUTPUT:> directives.
1151
1152=item *
1153
1154When dealing with references, it is important to handle them with caution.
216f0275
FC
1155The C<INIT:> block first calls SvGETMAGIC(paths), in case
1156paths is a tied variable. Then it checks that C<SvROK> returns
1157true, which indicates that paths is a valid reference. (Simply
1158checking C<SvROK> won't trigger FETCH on a tied variable.) It
171891c7
GS
1159then verifies that the object referenced by paths is an array, using C<SvRV>
1160to dereference paths, and C<SvTYPE> to discover its type. As an added test,
1161it checks that the array referenced by paths is non-empty, using the C<av_len>
1162function (which returns -1 if the array is empty). The XSRETURN_UNDEF macro
1163is used to abort the XSUB and return the undefined value whenever all three of
1164these conditions are not met.
1165
1166=item *
1167
1168We manipulate several arrays in this XSUB. Note that an array is represented
1169internally by an AV* pointer. The functions and macros for manipulating
1170arrays are similar to the functions in Perl: C<av_len> returns the highest
1171index in an AV*, much like $#array; C<av_fetch> fetches a single scalar value
1172from an array, given its index; C<av_push> pushes a scalar value onto the
1173end of the array, automatically extending the array as necessary.
1174
1175Specifically, we read pathnames one at a time from the input array, and
1176store the results in an output array (results) in the same order. If
1177statfs fails, the element pushed onto the return array is the value of
1178errno after the failure. If statfs succeeds, though, the value pushed
1179onto the return array is a reference to a hash containing some of the
1180information in the statfs structure.
1181
1182As with the return stack, it would be possible (and a small performance win)
1183to pre-extend the return array before pushing data into it, since we know
1184how many elements we will return:
1185
1186 av_extend(results, numpaths);
1187
1188=item *
1189
1190We are performing only one hash operation in this function, which is storing
1191a new scalar under a key using C<hv_store>. A hash is represented by an HV*
1192pointer. Like arrays, the functions for manipulating hashes from an XSUB
1193mirror the functionality available from Perl. See L<perlguts> and L<perlapi>
1194for details.
1195
1196=item *
1197
1198To create a reference, we use the C<newRV> function. Note that you can
1199cast an AV* or an HV* to type SV* in this case (and many others). This
1200allows you to take references to arrays, hashes and scalars with the same
1201function. Conversely, the C<SvRV> function always returns an SV*, which may
da75cd15 1202need to be cast to the appropriate type if it is something other than a
171891c7
GS
1203scalar (check with C<SvTYPE>).
1204
1205=item *
1206
1207At this point, xsubpp is doing very little work - the differences between
1208Mytest.xs and Mytest.c are minimal.
1209
1210=back
360e660c
GS
1211
1212=head2 EXAMPLE 7 (Coming Soon)
1213
1214XPUSH args AND set RETVAL AND assign return value to array
1215
1216=head2 EXAMPLE 8 (Coming Soon)
1217
1218Setting $!
1219
8dcb5783
NIS
1220=head2 EXAMPLE 9 Passing open files to XSes
1221
1222You would think passing files to an XS is difficult, with all the
1223typeglobs and stuff. Well, it isn't.
1224
1225Suppose that for some strange reason we need a wrapper around the
1226standard C library function C<fputs()>. This is all we need:
1227
1228 #define PERLIO_NOT_STDIO 0
1229 #include "EXTERN.h"
1230 #include "perl.h"
1231 #include "XSUB.h"
1232
1233 #include <stdio.h>
1234
1235 int
1236 fputs(s, stream)
1237 char * s
1238 FILE * stream
1239
1240The real work is done in the standard typemap.
1241
8f778886 1242B<But> you lose all the fine stuff done by the perlio layers. This
8dcb5783
NIS
1243calls the stdio function C<fputs()>, which knows nothing about them.
1244
e8a52a58
LC
1245The standard typemap offers three variants of PerlIO *:
1246C<InputStream> (T_IN), C<InOutStream> (T_INOUT) and C<OutputStream>
1247(T_OUT). A bare C<PerlIO *> is considered a T_INOUT. If it matters
1248in your code (see below for why it might) #define or typedef
1249one of the specific names and use that as the argument or result
1250type in your XS file.
1251
1252The standard typemap does not contain PerlIO * before perl 5.7,
1253but it has the three stream variants. Using a PerlIO * directly
1254is not backwards compatible unless you provide your own typemap.
22569500
NIS
1255
1256For streams coming I<from> perl the main difference is that
1257C<OutputStream> will get the output PerlIO * - which may make
e8a52a58 1258a difference on a socket. Like in our example...
22569500
NIS
1259
1260For streams being handed I<to> perl a new file handle is created
1261(i.e. a reference to a new glob) and associated with the PerlIO *
1262provided. If the read/write state of the PerlIO * is not correct then you
1263may get errors or warnings from when the file handle is used.
1264So if you opened the PerlIO * as "w" it should really be an
1265C<OutputStream> if open as "r" it should be an C<InputStream>.
1266
8dcb5783
NIS
1267Now, suppose you want to use perlio layers in your XS. We'll use the
1268perlio C<PerlIO_puts()> function as an example.
1269
22569500
NIS
1270In the C part of the XS file (above the first MODULE line) you
1271have
1272
1273 #define OutputStream PerlIO *
1274 or
1275 typedef PerlIO * OutputStream;
8dcb5783 1276
8dcb5783
NIS
1277
1278And this is the XS code:
1279
1280 int
1281 perlioputs(s, stream)
1282 char * s
22569500 1283 OutputStream stream
8dcb5783
NIS
1284 CODE:
1285 RETVAL = PerlIO_puts(stream, s);
1286 OUTPUT:
1287 RETVAL
1288
1289We have to use a C<CODE> section because C<PerlIO_puts()> has the arguments
1290reversed compared to C<fputs()>, and we want to keep the arguments the same.
1291
1292Wanting to explore this thoroughly, we want to use the stdio C<fputs()>
e8a52a58
LC
1293on a PerlIO *. This means we have to ask the perlio system for a stdio
1294C<FILE *>:
8dcb5783
NIS
1295
1296 int
1297 perliofputs(s, stream)
1298 char * s
e8a52a58 1299 OutputStream stream
8dcb5783
NIS
1300 PREINIT:
1301 FILE *fp = PerlIO_findFILE(stream);
1302 CODE:
1303 if (fp != (FILE*) 0) {
1304 RETVAL = fputs(s, fp);
1305 } else {
1306 RETVAL = -1;
1307 }
1308 OUTPUT:
1309 RETVAL
1310
1311Note: C<PerlIO_findFILE()> will search the layers for a stdio
1312layer. If it can't find one, it will call C<PerlIO_exportFILE()> to
1313generate a new stdio C<FILE>. Please only call C<PerlIO_exportFILE()> if
1314you want a I<new> C<FILE>. It will generate one on each call and push a
1315new stdio layer. So don't call it repeatedly on the same
256771e2 1316file. C<PerlIO_findFILE()> will retrieve the stdio layer once it has been
8dcb5783
NIS
1317generated by C<PerlIO_exportFILE()>.
1318
1319This applies to the perlio system only. For versions before 5.7,
1320C<PerlIO_exportFILE()> is equivalent to C<PerlIO_findFILE()>.
1321
360e660c
GS
1322=head2 Troubleshooting these Examples
1323
1324As mentioned at the top of this document, if you are having problems with
1325these example extensions, you might see if any of these help you.
1326
1327=over 4
1328
1329=item *
1330
1331In versions of 5.002 prior to the gamma version, the test script in Example
13321 will not function properly. You need to change the "use lib" line to
1333read:
1334
1335 use lib './blib';
1336
1337=item *
1338
1339In versions of 5.002 prior to version 5.002b1h, the test.pl file was not
1340automatically created by h2xs. This means that you cannot say "make test"
1341to run the test script. You will need to add the following line before the
1342"use extension" statement:
1343
1344 use lib './blib';
1345
1346=item *
1347
1348In versions 5.000 and 5.001, instead of using the above line, you will need
1349to use the following line:
1350
1351 BEGIN { unshift(@INC, "./blib") }
1352
1353=item *
1354
8dcb5783 1355This document assumes that the executable named "perl" is Perl version 5.
360e660c
GS
1356Some systems may have installed Perl version 5 as "perl5".
1357
1358=back
1359
1360=head1 See also
4633a7c4 1361
171891c7 1362For more information, consult L<perlguts>, L<perlapi>, L<perlxs>, L<perlmod>,
c07a80fd 1363and L<perlpod>.
4633a7c4 1364
360e660c 1365=head1 Author
4633a7c4 1366
9607fc9c 1367Jeff Okamoto <F<okamoto@corp.hp.com>>
4633a7c4 1368
c07a80fd
PP
1369Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig,
1370and Tim Bunce.
4633a7c4 1371
22569500
NIS
1372PerlIO material contributed by Lupe Christoph, with some clarification
1373by Nick Ing-Simmons.
8dcb5783 1374
eb3fb7ac
RB
1375Changes for h2xs as of Perl 5.8.x by Renee Baecker
1376
c07a80fd 1377=head2 Last Changed
4633a7c4 1378
78a4b226 13792012-01-20