3 perlXStut - Tutorial for writing XSUBs
7 This tutorial will educate the reader on the steps involved in creating
8 a Perl extension. The reader is assumed to have access to L<perlguts> and
11 This tutorial starts with very simple examples and becomes more complex,
12 with each new example adding new features. Certain concepts may not be
13 completely explained until later in the tutorial in order to slowly ease
14 the reader into building extensions.
16 This tutorial was written from a Unix point of view. Where I know them
17 to be otherwise different for other platforms (e.g. Win32), I will list
18 them. If you find something that was missed, please let me know.
24 This tutorial assumes that the make program that Perl is configured to
25 use is called C<make>. Instead of running "make" in the examples that
26 follow, you may have to substitute whatever make program Perl has been
27 configured to use. Running "perl -V:make" should tell you what it is.
31 When writing a Perl extension for general consumption, one should expect that
32 the extension will be used with versions of Perl different from the
33 version available on your machine. Since you are reading this document,
34 the version of Perl on your machine is probably 5.005 or later, but the users
35 of your extension may have more ancient versions.
37 To understand what kinds of incompatibilities one may expect, and in the rare
38 case that the version of Perl on your machine is older than this document,
39 see the section on "Troubleshooting these Examples" for more information.
41 If your extension uses some features of Perl which are not available on older
42 releases of Perl, your users would appreciate an early meaningful warning.
43 You would probably put this information into the F<README> file, but nowadays
44 installation of extensions may be performed automatically, guided by F<CPAN.pm>
45 module or other tools.
47 In MakeMaker-based installations, F<Makefile.PL> provides the earliest
48 opportunity to perform version checks. One can put something like this
49 in F<Makefile.PL> for this purpose:
51 eval { require 5.007 }
54 ### This module uses frobnication framework which is not available before
55 ### version 5.007 of Perl. Upgrade your Perl before installing Kara::Mba.
59 =head2 Dynamic Loading versus Static Loading
61 It is commonly thought that if a system does not have the capability to
62 dynamically load a library, you cannot build XSUBs. This is incorrect.
63 You I<can> build them, but you must link the XSUBs subroutines with the
64 rest of Perl, creating a new executable. This situation is similar to
67 This tutorial can still be used on such a system. The XSUB build mechanism
68 will check the system and build a dynamically-loadable library if possible,
69 or else a static library and then, optionally, a new statically-linked
70 executable with that static library linked in.
72 Should you wish to build a statically-linked executable on a system which
73 can dynamically load libraries, you may, in all the following examples,
74 where the command "C<make>" with no arguments is executed, run the command
75 "C<make perl>" instead.
77 If you have generated such a statically-linked executable by choice, then
78 instead of saying "C<make test>", you should say "C<make test_static>".
79 On systems that cannot build dynamically-loadable libraries at all, simply
80 saying "C<make test>" is sufficient.
84 Now let's go on with the show!
88 Our first extension will be very simple. When we call the routine in the
89 extension, it will print out a well-known message and return.
91 Run "C<h2xs -A -n Mytest>". This creates a directory named Mytest,
92 possibly under ext/ if that directory exists in the current working
93 directory. Several files will be created in the Mytest dir, including
94 MANIFEST, Makefile.PL, Mytest.pm, Mytest.xs, test.pl, and Changes.
96 The MANIFEST file contains the names of all the files just created in the
99 The file Makefile.PL should look something like this:
101 use ExtUtils::MakeMaker;
102 # See lib/ExtUtils/MakeMaker.pm for details of how to influence
103 # the contents of the Makefile that is written.
106 VERSION_FROM => 'Mytest.pm', # finds $VERSION
107 LIBS => [''], # e.g., '-lm'
108 DEFINE => '', # e.g., '-DHAVE_SOMETHING'
109 INC => '', # e.g., '-I/usr/include/other'
112 The file Mytest.pm should start with something like this:
121 our @ISA = qw(Exporter DynaLoader);
122 # Items to export into callers namespace by default. Note: do not export
123 # names by default without a very good reason. Use EXPORT_OK instead.
124 # Do not simply export all your public functions/methods/constants.
128 our $VERSION = '0.01';
130 bootstrap Mytest $VERSION;
132 # Preloaded methods go here.
134 # Autoload methods go after __END__, and are processed by the autosplit program.
138 # Below is the stub of documentation for your module. You better edit it!
140 The rest of the .pm file contains sample code for providing documentation for
143 Finally, the Mytest.xs file should look something like this:
149 MODULE = Mytest PACKAGE = Mytest
151 Let's edit the .xs file by adding this to the end of the file:
156 printf("Hello, world!\n");
158 It is okay for the lines starting at the "CODE:" line to not be indented.
159 However, for readability purposes, it is suggested that you indent CODE:
160 one level and the lines following one more level.
162 Now we'll run "C<perl Makefile.PL>". This will create a real Makefile,
163 which make needs. Its output looks something like:
166 Checking if your kit is complete...
168 Writing Makefile for Mytest
171 Now, running make will produce output that looks something like this (some
172 long lines have been shortened for clarity and some extraneous lines have
176 umask 0 && cp Mytest.pm ./blib/Mytest.pm
177 perl xsubpp -typemap typemap Mytest.xs >Mytest.tc && mv Mytest.tc Mytest.c
178 Please specify prototyping behavior for Mytest.xs (see perlxs manual)
180 Running Mkbootstrap for Mytest ()
182 LD_RUN_PATH="" ld -o ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl -b Mytest.o
183 chmod 755 ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl
184 cp Mytest.bs ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
185 chmod 644 ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
186 Manifying ./blib/man3/Mytest.3
189 You can safely ignore the line about "prototyping behavior".
191 If you are on a Win32 system, and the build process fails with linker
192 errors for functions in the C library, check if your Perl is configured
193 to use PerlCRT (running "perl -V:libc" should show you if this is the
194 case). If Perl is configured to use PerlCRT, you have to make sure
195 PerlCRT.lib is copied to the same location that msvcrt.lib lives in,
196 so that the compiler can find it on its own. msvcrt.lib is usually
197 found in the Visual C compiler's lib directory (e.g. C:/DevStudio/VC/lib).
199 Perl has its own special way of easily writing test scripts, but for this
200 example only, we'll create our own test script. Create a file called hello
201 that looks like this:
203 #! /opt/perl5/bin/perl
205 use ExtUtils::testlib;
211 Now we make the script executable (C<chmod -x hello>), run the script
212 and we should see the following output:
220 Now let's add to our extension a subroutine that will take a single numeric
221 argument as input and return 0 if the number is even or 1 if the number
224 Add the following to the end of Mytest.xs:
230 RETVAL = (input % 2 == 0);
234 There does not need to be white space at the start of the "C<int input>"
235 line, but it is useful for improving readability. Placing a semi-colon at
236 the end of that line is also optional. Any amount and kind of white space
237 may be placed between the "C<int>" and "C<input>".
239 Now re-run make to rebuild our new shared library.
241 Now perform the same steps as before, generating a Makefile from the
242 Makefile.PL file, and running make.
244 In order to test that our extension works, we now need to look at the
245 file test.pl. This file is set up to imitate the same kind of testing
246 structure that Perl itself has. Within the test script, you perform a
247 number of tests to confirm the behavior of the extension, printing "ok"
248 when the test is correct, "not ok" when it is not. Change the print
249 statement in the BEGIN block to print "1..4", and add the following code
250 to the end of the file:
252 print &Mytest::is_even(0) == 1 ? "ok 2" : "not ok 2", "\n";
253 print &Mytest::is_even(1) == 0 ? "ok 3" : "not ok 3", "\n";
254 print &Mytest::is_even(2) == 1 ? "ok 4" : "not ok 4", "\n";
256 We will be calling the test script through the command "C<make test>". You
257 should see output that looks something like this:
260 PERL_DL_NONLAZY=1 /opt/perl5.004/bin/perl (lots of -I arguments) test.pl
268 =head2 What has gone on?
270 The program h2xs is the starting point for creating extensions. In later
271 examples we'll see how we can use h2xs to read header files and generate
272 templates to connect to C routines.
274 h2xs creates a number of files in the extension directory. The file
275 Makefile.PL is a perl script which will generate a true Makefile to build
276 the extension. We'll take a closer look at it later.
278 The .pm and .xs files contain the meat of the extension. The .xs file holds
279 the C routines that make up the extension. The .pm file contains routines
280 that tell Perl how to load your extension.
282 Generating the Makefile and running C<make> created a directory called blib
283 (which stands for "build library") in the current working directory. This
284 directory will contain the shared library that we will build. Once we have
285 tested it, we can install it into its final location.
287 Invoking the test script via "C<make test>" did something very important.
288 It invoked perl with all those C<-I> arguments so that it could find the
289 various files that are part of the extension. It is I<very> important that
290 while you are still testing extensions that you use "C<make test>". If you
291 try to run the test script all by itself, you will get a fatal error.
292 Another reason it is important to use "C<make test>" to run your test
293 script is that if you are testing an upgrade to an already-existing version,
294 using "C<make test>" insures that you will test your new extension, not the
295 already-existing version.
297 When Perl sees a C<use extension;>, it searches for a file with the same name
298 as the C<use>'d extension that has a .pm suffix. If that file cannot be found,
299 Perl dies with a fatal error. The default search path is contained in the
302 In our case, Mytest.pm tells perl that it will need the Exporter and Dynamic
303 Loader extensions. It then sets the C<@ISA> and C<@EXPORT> arrays and the
304 C<$VERSION> scalar; finally it tells perl to bootstrap the module. Perl
305 will call its dynamic loader routine (if there is one) and load the shared
308 The two arrays C<@ISA> and C<@EXPORT> are very important. The C<@ISA>
309 array contains a list of other packages in which to search for methods (or
310 subroutines) that do not exist in the current package. This is usually
311 only important for object-oriented extensions (which we will talk about
312 much later), and so usually doesn't need to be modified.
314 The C<@EXPORT> array tells Perl which of the extension's variables and
315 subroutines should be placed into the calling package's namespace. Because
316 you don't know if the user has already used your variable and subroutine
317 names, it's vitally important to carefully select what to export. Do I<not>
318 export method or variable names I<by default> without a good reason.
320 As a general rule, if the module is trying to be object-oriented then don't
321 export anything. If it's just a collection of functions and variables, then
322 you can export them via another array, called C<@EXPORT_OK>. This array
323 does not automatically place its subroutine and variable names into the
324 namespace unless the user specifically requests that this be done.
326 See L<perlmod> for more information.
328 The C<$VERSION> variable is used to ensure that the .pm file and the shared
329 library are "in sync" with each other. Any time you make changes to
330 the .pm or .xs files, you should increment the value of this variable.
332 =head2 Writing good test scripts
334 The importance of writing good test scripts cannot be overemphasized. You
335 should closely follow the "ok/not ok" style that Perl itself uses, so that
336 it is very easy and unambiguous to determine the outcome of each test case.
337 When you find and fix a bug, make sure you add a test case for it.
339 By running "C<make test>", you ensure that your test.pl script runs and uses
340 the correct version of your extension. If you have many test cases, you
341 might want to copy Perl's test style. Create a directory named "t" in the
342 extension's directory and append the suffix ".t" to the names of your test
343 files. When you run "C<make test>", all of these test files will be executed.
347 Our third extension will take one argument as its input, round off that
348 value, and set the I<argument> to the rounded value.
350 Add the following to the end of Mytest.xs:
357 arg = floor(arg + 0.5);
358 } else if (arg < 0.0) {
359 arg = ceil(arg - 0.5);
366 Edit the Makefile.PL file so that the corresponding line looks like this:
368 'LIBS' => ['-lm'], # e.g., '-lm'
370 Generate the Makefile and run make. Change the BEGIN block to print
371 "1..9" and add the following to test.pl:
373 $i = -1.5; &Mytest::round($i); print $i == -2.0 ? "ok 5" : "not ok 5", "\n";
374 $i = -1.1; &Mytest::round($i); print $i == -1.0 ? "ok 6" : "not ok 6", "\n";
375 $i = 0.0; &Mytest::round($i); print $i == 0.0 ? "ok 7" : "not ok 7", "\n";
376 $i = 0.5; &Mytest::round($i); print $i == 1.0 ? "ok 8" : "not ok 8", "\n";
377 $i = 1.2; &Mytest::round($i); print $i == 1.0 ? "ok 9" : "not ok 9", "\n";
379 Running "C<make test>" should now print out that all nine tests are okay.
381 Notice that in these new test cases, the argument passed to round was a
382 scalar variable. You might be wondering if you can round a constant or
383 literal. To see what happens, temporarily add the following line to test.pl:
387 Run "C<make test>" and notice that Perl dies with a fatal error. Perl won't
388 let you change the value of constants!
390 =head2 What's new here?
396 We've made some changes to Makefile.PL. In this case, we've specified an
397 extra library to be linked into the extension's shared library, the math
398 library libm in this case. We'll talk later about how to write XSUBs that
399 can call every routine in a library.
403 The value of the function is not being passed back as the function's return
404 value, but by changing the value of the variable that was passed into the
405 function. You might have guessed that when you saw that the return value
406 of round is of type "void".
410 =head2 Input and Output Parameters
412 You specify the parameters that will be passed into the XSUB on the line(s)
413 after you declare the function's return value and name. Each input parameter
414 line starts with optional white space, and may have an optional terminating
417 The list of output parameters occurs at the very end of the function, just
418 before after the OUTPUT: directive. The use of RETVAL tells Perl that you
419 wish to send this value back as the return value of the XSUB function. In
420 Example 3, we wanted the "return value" placed in the original variable
421 which we passed in, so we listed it (and not RETVAL) in the OUTPUT: section.
423 =head2 The XSUBPP Program
425 The B<xsubpp> program takes the XS code in the .xs file and translates it into
426 C code, placing it in a file whose suffix is .c. The C code created makes
427 heavy use of the C functions within Perl.
429 =head2 The TYPEMAP file
431 The B<xsubpp> program uses rules to convert from Perl's data types (scalar,
432 array, etc.) to C's data types (int, char, etc.). These rules are stored
433 in the typemap file ($PERLLIB/ExtUtils/typemap). This file is split into
436 The first section maps various C data types to a name, which corresponds
437 somewhat with the various Perl types. The second section contains C code
438 which B<xsubpp> uses to handle input parameters. The third section contains
439 C code which B<xsubpp> uses to handle output parameters.
441 Let's take a look at a portion of the .c file created for our extension.
442 The file name is Mytest.c:
448 croak("Usage: Mytest::round(arg)");
450 double arg = (double)SvNV(ST(0)); /* XXXXX */
452 arg = floor(arg + 0.5);
453 } else if (arg < 0.0) {
454 arg = ceil(arg - 0.5);
458 sv_setnv(ST(0), (double)arg); /* XXXXX */
463 Notice the two lines commented with "XXXXX". If you check the first section
464 of the typemap file, you'll see that doubles are of type T_DOUBLE. In the
465 INPUT section, an argument that is T_DOUBLE is assigned to the variable
466 arg by calling the routine SvNV on something, then casting it to double,
467 then assigned to the variable arg. Similarly, in the OUTPUT section,
468 once arg has its final value, it is passed to the sv_setnv function to
469 be passed back to the calling subroutine. These two functions are explained
470 in L<perlguts>; we'll talk more later about what that "ST(0)" means in the
471 section on the argument stack.
473 =head2 Warning about Output Arguments
475 In general, it's not a good idea to write extensions that modify their input
476 parameters, as in Example 3. Instead, you should probably return multiple
477 values in an array and let the caller handle them (we'll do this in a later
478 example). However, in order to better accomodate calling pre-existing C
479 routines, which often do modify their input parameters, this behavior is
484 In this example, we'll now begin to write XSUBs that will interact with
485 pre-defined C libraries. To begin with, we will build a small library of
486 our own, then let h2xs write our .pm and .xs files for us.
488 Create a new directory called Mytest2 at the same level as the directory
489 Mytest. In the Mytest2 directory, create another directory called mylib,
490 and cd into that directory.
492 Here we'll create some files that will generate a test library. These will
493 include a C source file and a header file. We'll also create a Makefile.PL
494 in this directory. Then we'll make sure that running make at the Mytest2
495 level will automatically run this Makefile.PL file and the resulting Makefile.
497 In the mylib directory, create a file mylib.h that looks like this:
501 extern double foo(int, long, const char*);
503 Also create a file mylib.c that looks like this:
509 foo(int a, long b, const char *c)
511 return (a + b + atof(c) + TESTVAL);
514 And finally create a file Makefile.PL that looks like this:
516 use ExtUtils::MakeMaker;
519 NAME => 'Mytest2::mylib',
520 SKIP => [qw(all static static_lib dynamic dynamic_lib)],
521 clean => {'FILES' => 'libmylib$(LIBEEXT)'},
525 sub MY::top_targets {
531 static :: libmylib$(LIB_EXT)
533 libmylib$(LIB_EXT): $(O_FILES)
534 $(AR) cr libmylib$(LIB_EXT) $(O_FILES)
535 $(RANLIB) libmylib$(LIB_EXT)
540 Make sure you use a tab and not spaces on the lines beginning with "$(AR)"
541 and "$(RANLIB)". Make will not function properly if you use spaces.
542 It has also been reported that the "cr" argument to $(AR) is unnecessary
545 We will now create the main top-level Mytest2 files. Change to the directory
546 above Mytest2 and run the following command:
548 % h2xs -O -n Mytest2 ./Mytest2/mylib/mylib.h
550 This will print out a warning about overwriting Mytest2, but that's okay.
551 Our files are stored in Mytest2/mylib, and will be untouched.
553 The normal Makefile.PL that h2xs generates doesn't know about the mylib
554 directory. We need to tell it that there is a subdirectory and that we
555 will be generating a library in it. Let's add the argument MYEXTLIB to
556 the WriteMakefile call so that it looks like this:
560 'VERSION_FROM' => 'Mytest2.pm', # finds $VERSION
561 'LIBS' => [''], # e.g., '-lm'
562 'DEFINE' => '', # e.g., '-DHAVE_SOMETHING'
563 'INC' => '', # e.g., '-I/usr/include/other'
564 'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)',
567 and then at the end add a subroutine (which will override the pre-existing
568 subroutine). Remember to use a tab character to indent the line beginning
573 $(MYEXTLIB): mylib/Makefile
574 cd mylib && $(MAKE) $(PASSTHRU)
578 Let's also fix the MANIFEST file so that it accurately reflects the contents
579 of our extension. The single line that says "mylib" should be replaced by
580 the following three lines:
586 To keep our namespace nice and unpolluted, edit the .pm file and change
587 the variable C<@EXPORT> to C<@EXPORT_OK>. Finally, in the
588 .xs file, edit the #include line to read:
590 #include "mylib/mylib.h"
592 And also add the following function definition to the end of the .xs file:
602 Now we also need to create a typemap file because the default Perl doesn't
603 currently support the const char * type. Create a file called typemap in
604 the Mytest2 directory and place the following in it:
608 Now run perl on the top-level Makefile.PL. Notice that it also created a
609 Makefile in the mylib directory. Run make and watch that it does cd into
610 the mylib directory and run make in there as well.
612 Now edit the test.pl script and change the BEGIN block to print "1..4",
613 and add the following lines to the end of the script:
615 print &Mytest2::foo(1, 2, "Hello, world!") == 7 ? "ok 2\n" : "not ok 2\n";
616 print &Mytest2::foo(1, 2, "0.0") == 7 ? "ok 3\n" : "not ok 3\n";
617 print abs(&Mytest2::foo(0, 0, "-3.4") - 0.6) <= 0.01 ? "ok 4\n" : "not ok 4\n";
619 (When dealing with floating-point comparisons, it is best to not check for
620 equality, but rather that the difference between the expected and actual
621 result is below a certain amount (called epsilon) which is 0.01 in this case)
623 Run "C<make test>" and all should be well.
625 =head2 What has happened here?
627 Unlike previous examples, we've now run h2xs on a real include file. This
628 has caused some extra goodies to appear in both the .pm and .xs files.
634 In the .xs file, there's now a #include directive with the absolute path to
635 the mylib.h header file. We changed this to a relative path so that we
636 could move the extension directory if we wanted to.
640 There's now some new C code that's been added to the .xs file. The purpose
641 of the C<constant> routine is to make the values that are #define'd in the
642 header file accessible by the Perl script (by calling either C<TESTVAL> or
643 C<&Mytest2::TESTVAL>). There's also some XS code to allow calls to the
648 The .pm file originally exported the name C<TESTVAL> in the C<@EXPORT> array.
649 This could lead to name clashes. A good rule of thumb is that if the #define
650 is only going to be used by the C routines themselves, and not by the user,
651 they should be removed from the C<@EXPORT> array. Alternately, if you don't
652 mind using the "fully qualified name" of a variable, you could move most
653 or all of the items from the C<@EXPORT> array into the C<@EXPORT_OK> array.
657 If our include file had contained #include directives, these would not have
658 been processed by h2xs. There is no good solution to this right now.
662 We've also told Perl about the library that we built in the mylib
663 subdirectory. That required only the addition of the C<MYEXTLIB> variable
664 to the WriteMakefile call and the replacement of the postamble subroutine
665 to cd into the subdirectory and run make. The Makefile.PL for the
666 library is a bit more complicated, but not excessively so. Again we
667 replaced the postamble subroutine to insert our own code. This code
668 simply specified that the library to be created here was a static archive
669 library (as opposed to a dynamically loadable library) and provided the
670 commands to build it.
674 =head2 Anatomy of .xs file
676 The .xs file of L<"EXAMPLE 4"> contained some new elements. To understand
677 the meaning of these elements, pay attention to the line which reads
679 MODULE = Mytest2 PACKAGE = Mytest2
681 Anything before this line is plain C code which describes which headers
682 to include, and defines some convenience functions. No translations are
683 performed on this part, it goes into the generated output C file as is.
685 Anything after this line is the description of XSUB functions.
686 These descriptions are translated by B<xsubpp> into C code which
687 implements these functions using Perl calling conventions, and which
688 makes these functions visible from Perl interpreter.
690 Pay a special attention to the function C<constant>. This name appears
691 twice in the generated .xs file: once in the first part, as a static C
692 function, the another time in the second part, when an XSUB interface to
693 this static C function is defined.
695 This is quite typical for .xs files: usually the .xs file provides
696 an interface to an existing C function. Then this C function is defined
697 somewhere (either in an external library, or in the first part of .xs file),
698 and a Perl interface to this function (i.e. "Perl glue") is described in the
699 second part of .xs file. The situation in L<"EXAMPLE 1">, L<"EXAMPLE 2">,
700 and L<"EXAMPLE 3">, when all the work is done inside the "Perl glue", is
701 somewhat of an exception rather than the rule.
703 =head2 Getting the fat out of XSUBs
705 In L<"EXAMPLE 4"> the second part of .xs file contained the following
706 description of an XSUB:
716 Note that in contrast with L<"EXAMPLE 1">, L<"EXAMPLE 2"> and L<"EXAMPLE 3">,
717 this description does not contain the actual I<code> for what is done
718 is done during a call to Perl function foo(). To understand what is going
719 on here, one can add a CODE section to this XSUB:
731 However, these two XSUBs provide almost identical generated C code: B<xsubpp>
732 compiler is smart enough to figure out the C<CODE:> section from the first
733 two lines of the description of XSUB. What about C<OUTPUT:> section? In
734 fact, that is absolutely the same! The C<OUTPUT:> section can be removed
735 as well, I<as far as C<CODE:> section or C<PPCODE:> section> is not
736 specified: B<xsubpp> can see that it needs to generate a function call
737 section, and will autogenerate the OUTPUT section too. Thus one can
738 shortcut the XSUB to become:
746 Can we do the same with an XSUB
752 RETVAL = (input % 2 == 0);
756 of L<"EXAMPLE 2">? To do this, one needs to define a C function C<int
757 is_even(int input)>. As we saw in L<Anatomy of .xs file>, a proper place
758 for this definition is in the first part of .xs file. In fact a C function
763 return (arg % 2 == 0);
766 is probably overkill for this. Something as simple as a C<#define> will
769 #define is_even(arg) ((arg) % 2 == 0)
771 After having this in the first part of .xs file, the "Perl glue" part becomes
778 This technique of separation of the glue part from the workhorse part has
779 obvious tradeoffs: if you want to change a Perl interface, you need to
780 change two places in your code. However, it removes a lot of clutter,
781 and makes the workhorse part independent from idiosyncrasies of Perl calling
782 convention. (In fact, there is nothing Perl-specific in the above description,
783 a different version of B<xsubpp> might have translated this to TCL glue or
784 Python glue as well.)
786 =head2 More about XSUB arguments
788 With the completion of Example 4, we now have an easy way to simulate some
789 real-life libraries whose interfaces may not be the cleanest in the world.
790 We shall now continue with a discussion of the arguments passed to the
793 When you specify arguments to routines in the .xs file, you are really
794 passing three pieces of information for each argument listed. The first
795 piece is the order of that argument relative to the others (first, second,
796 etc). The second is the type of argument, and consists of the type
797 declaration of the argument (e.g., int, char*, etc). The third piece is
798 the calling convention for the argument in the call to the library function.
800 While Perl passes arguments to functions by reference,
801 C passes arguments by value; to implement a C function which modifies data
802 of one of the "arguments", the actual argument of this C function would be
803 a pointer to the data. Thus two C functions with declarations
805 int string_length(char *s);
806 int upper_case_char(char *cp);
808 may have completely different semantics: the first one may inspect an array
809 of chars pointed by s, and the second one may immediately dereference C<cp>
810 and manipulate C<*cp> only (using the return value as, say, a success
811 indicator). From Perl one would use these functions in
812 a completely different manner.
814 One conveys this info to B<xsubpp> by replacing C<*> before the
815 argument by C<&>. C<&> means that the argument should be passed to a library
816 function by its address. The above two function may be XSUB-ified as
826 For example, consider:
833 The first Perl argument to this function would be treated as a char and assigned
834 to the variable a, and its address would be passed into the function foo.
835 The second Perl argument would be treated as a string pointer and assigned to the
836 variable b. The I<value> of b would be passed into the function foo. The
837 actual call to the function foo that B<xsubpp> generates would look like this:
841 B<xsubpp> will parse the following function argument lists identically:
847 However, to help ease understanding, it is suggested that you place a "&"
848 next to the variable name and away from the variable type), and place a
849 "*" near the variable type, but away from the variable name (as in the
850 call to foo above). By doing so, it is easy to understand exactly what
851 will be passed to the C function -- it will be whatever is in the "last
854 You should take great pains to try to pass the function the type of variable
855 it wants, when possible. It will save you a lot of trouble in the long run.
857 =head2 The Argument Stack
859 If we look at any of the C code generated by any of the examples except
860 example 1, you will notice a number of references to ST(n), where n is
861 usually 0. "ST" is actually a macro that points to the n'th argument
862 on the argument stack. ST(0) is thus the first argument on the stack and
863 therefore the first argument passed to the XSUB, ST(1) is the second
866 When you list the arguments to the XSUB in the .xs file, that tells B<xsubpp>
867 which argument corresponds to which of the argument stack (i.e., the first
868 one listed is the first argument, and so on). You invite disaster if you
869 do not list them in the same order as the function expects them.
871 The actual values on the argument stack are pointers to the values passed
872 in. When an argument is listed as being an OUTPUT value, its corresponding
873 value on the stack (i.e., ST(0) if it was the first argument) is changed.
874 You can verify this by looking at the C code generated for Example 3.
875 The code for the round() XSUB routine contains lines that look like this:
877 double arg = (double)SvNV(ST(0));
878 /* Round the contents of the variable arg */
879 sv_setnv(ST(0), (double)arg);
881 The arg variable is initially set by taking the value from ST(0), then is
882 stored back into ST(0) at the end of the routine.
884 XSUBs are also allowed to return lists, not just scalars. This must be
885 done by manipulating stack values ST(0), ST(1), etc, in a subtly
886 different way. See L<perlxs> for details.
888 XSUBs are also allowed to avoid automatic conversion of Perl function arguments
889 to C function arguments. See L<perlxs> for details. Some people prefer
890 manual conversion by inspecting C<ST(i)> even in the cases when automatic
891 conversion will do, arguing that this makes the logic of an XSUB call clearer.
892 Compare with L<"Getting the fat out of XSUBs"> for a similar tradeoff of
893 a complete separation of "Perl glue" and "workhorse" parts of an XSUB.
895 While experts may argue about these idioms, a novice to Perl guts may
896 prefer a way which is as little Perl-guts-specific as possible, meaning
897 automatic conversion and automatic call generation, as in
898 L<"Getting the fat out of XSUBs">. This approach has the additional
899 benefit of protecting the XSUB writer from future changes to the Perl API.
901 =head2 Extending your Extension
903 Sometimes you might want to provide some extra methods or subroutines
904 to assist in making the interface between Perl and your extension simpler
905 or easier to understand. These routines should live in the .pm file.
906 Whether they are automatically loaded when the extension itself is loaded
907 or only loaded when called depends on where in the .pm file the subroutine
908 definition is placed. You can also consult L<Autoloader> for an alternate
909 way to store and load your extra subroutines.
911 =head2 Documenting your Extension
913 There is absolutely no excuse for not documenting your extension.
914 Documentation belongs in the .pm file. This file will be fed to pod2man,
915 and the embedded documentation will be converted to the man page format,
916 then placed in the blib directory. It will be copied to Perl's man
917 page directory when the extension is installed.
919 You may intersperse documentation and Perl code within the .pm file.
920 In fact, if you want to use method autoloading, you must do this,
921 as the comment inside the .pm file explains.
923 See L<perlpod> for more information about the pod format.
925 =head2 Installing your Extension
927 Once your extension is complete and passes all its tests, installing it
928 is quite simple: you simply run "make install". You will either need
929 to have write permission into the directories where Perl is installed,
930 or ask your system administrator to run the make for you.
932 Alternately, you can specify the exact directory to place the extension's
933 files by placing a "PREFIX=/destination/directory" after the make install.
934 (or in between the make and install if you have a brain-dead version of make).
935 This can be very useful if you are building an extension that will eventually
936 be distributed to multiple systems. You can then just archive the files in
937 the destination directory and distribute them to your destination systems.
941 In this example, we'll do some more work with the argument stack. The
942 previous examples have all returned only a single value. We'll now
943 create an extension that returns an array.
945 This extension is very Unix-oriented (struct statfs and the statfs system
946 call). If you are not running on a Unix system, you can substitute for
947 statfs any other function that returns multiple values, you can hard-code
948 values to be returned to the caller (although this will be a bit harder
949 to test the error case), or you can simply not do this example. If you
950 change the XSUB, be sure to fix the test cases to match the changes.
952 Return to the Mytest directory and add the following code to the end of
963 i = statfs(path, &buf);
965 XPUSHs(sv_2mortal(newSVnv(buf.f_bavail)));
966 XPUSHs(sv_2mortal(newSVnv(buf.f_bfree)));
967 XPUSHs(sv_2mortal(newSVnv(buf.f_blocks)));
968 XPUSHs(sv_2mortal(newSVnv(buf.f_bsize)));
969 XPUSHs(sv_2mortal(newSVnv(buf.f_ffree)));
970 XPUSHs(sv_2mortal(newSVnv(buf.f_files)));
971 XPUSHs(sv_2mortal(newSVnv(buf.f_type)));
972 XPUSHs(sv_2mortal(newSVnv(buf.f_fsid[0])));
973 XPUSHs(sv_2mortal(newSVnv(buf.f_fsid[1])));
975 XPUSHs(sv_2mortal(newSVnv(errno)));
978 You'll also need to add the following code to the top of the .xs file, just
979 after the include of "XSUB.h":
983 Also add the following code segment to test.pl while incrementing the "1..9"
984 string in the BEGIN block to "1..11":
986 @a = &Mytest::statfs("/blech");
987 print ((scalar(@a) == 1 && $a[0] == 2) ? "ok 10\n" : "not ok 10\n");
988 @a = &Mytest::statfs("/");
989 print scalar(@a) == 9 ? "ok 11\n" : "not ok 11\n";
991 =head2 New Things in this Example
993 This example added quite a few new concepts. We'll take them one at a time.
999 The INIT: directive contains code that will be placed immediately after
1000 the argument stack is decoded. C does not allow variable declarations at
1001 arbitrary locations inside a function,
1002 so this is usually the best way to declare local variables needed by the XSUB.
1003 (Alternatively, one could put the whole C<PPCODE:> section into braces, and
1004 put these declarations on top.)
1008 This routine also returns a different number of arguments depending on the
1009 success or failure of the call to statfs. If there is an error, the error
1010 number is returned as a single-element array. If the call is successful,
1011 then a 9-element array is returned. Since only one argument is passed into
1012 this function, we need room on the stack to hold the 9 values which may be
1015 We do this by using the PPCODE: directive, rather than the CODE: directive.
1016 This tells B<xsubpp> that we will be managing the return values that will be
1017 put on the argument stack by ourselves.
1021 When we want to place values to be returned to the caller onto the stack,
1022 we use the series of macros that begin with "XPUSH". There are five
1023 different versions, for placing integers, unsigned integers, doubles,
1024 strings, and Perl scalars on the stack. In our example, we placed a
1025 Perl scalar onto the stack. (In fact this is the only macro which
1026 can be used to return multiple values.)
1028 The XPUSH* macros will automatically extend the return stack to prevent
1029 it from being overrun. You push values onto the stack in the order you
1030 want them seen by the calling program.
1034 The values pushed onto the return stack of the XSUB are actually mortal SV's.
1035 They are made mortal so that once the values are copied by the calling
1036 program, the SV's that held the returned values can be deallocated.
1037 If they were not mortal, then they would continue to exist after the XSUB
1038 routine returned, but would not be accessible. This is a memory leak.
1042 If we were interested in performance, not in code compactness, in the success
1043 branch we would not use C<XPUSHs> macros, but C<PUSHs> macros, and would
1044 pre-extend the stack before pushing the return values:
1048 The tradeoff is that one needs to calculate the number of return values
1049 in advance (though overextending the stack will not typically hurt
1050 anything but memory consumption).
1052 Similarly, in the failure branch we could use C<PUSHs> I<without> extending
1053 the stack: the Perl function reference comes to an XSUB on the stack, thus
1054 the stack is I<always> large enough to take one return value.
1058 =head2 EXAMPLE 6 (Coming Soon)
1060 Passing in and returning references to arrays and/or hashes
1062 =head2 EXAMPLE 7 (Coming Soon)
1064 XPUSH args AND set RETVAL AND assign return value to array
1066 =head2 EXAMPLE 8 (Coming Soon)
1070 =head2 EXAMPLE 9 (Coming Soon)
1072 Getting fd's from filehandles
1074 =head2 Troubleshooting these Examples
1076 As mentioned at the top of this document, if you are having problems with
1077 these example extensions, you might see if any of these help you.
1083 In versions of 5.002 prior to the gamma version, the test script in Example
1084 1 will not function properly. You need to change the "use lib" line to
1091 In versions of 5.002 prior to version 5.002b1h, the test.pl file was not
1092 automatically created by h2xs. This means that you cannot say "make test"
1093 to run the test script. You will need to add the following line before the
1094 "use extension" statement:
1100 In versions 5.000 and 5.001, instead of using the above line, you will need
1101 to use the following line:
1103 BEGIN { unshift(@INC, "./blib") }
1107 This document assumes that the executable named "perl" is Perl version 5.
1108 Some systems may have installed Perl version 5 as "perl5".
1114 For more information, consult L<perlguts>, L<perlxs>, L<perlmod>,
1119 Jeff Okamoto <F<okamoto@corp.hp.com>>
1121 Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig,