Debian Codegraph @

upstream/opensuse-tumbleweed/man1/perlxstut.1

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