Debian Codegraph @

upstream/debian-unstable/man1/perlxstut.1

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