Cari di Perl 
    Perl Tutorial
Daftar Isi
(Sebelumnya) Tutorial on threads in PerlPerl Unicode Tutorial (Berikutnya)
Tutorials

Tutorial for writing XSUBs

Daftar Isi

NAME

perlxstut - Tutorial for writing XSUBs

DESCRIPTION

This tutorial will educate the reader on the steps involved in creatinga Perl extension. The reader is assumed to have access to perlguts,perlapi and perlxs.

This tutorial starts with very simple examples and becomes more complex,with each new example adding new features. Certain concepts may not becompletely explained until later in the tutorial in order to slowly easethe reader into building extensions.

This tutorial was written from a Unix point of view. Where I know themto be otherwise different for other platforms (e.g. Win32), I will listthem. If you find something that was missed, please let me know.

SPECIAL NOTES

make

This tutorial assumes that the make program that Perl is configured touse is called make. Instead of running "make" in the examples thatfollow, you may have to substitute whatever make program Perl has beenconfigured to use. Running perl -V:make should tell you what it is.

Version caveat

When writing a Perl extension for general consumption, one should expect thatthe extension will be used with versions of Perl different from theversion available on your machine. Since you are reading this document,the version of Perl on your machine is probably 5.005 or later, but the usersof your extension may have more ancient versions.

To understand what kinds of incompatibilities one may expect, and in the rarecase that the version of Perl on your machine is older than this document,see the section on "Troubleshooting these Examples" for more information.

If your extension uses some features of Perl which are not available on olderreleases of Perl, your users would appreciate an early meaningful warning.You would probably put this information into the README file, but nowadaysinstallation of extensions may be performed automatically, guided by CPAN.pmmodule or other tools.

In MakeMaker-based installations, Makefile.PL provides the earliestopportunity to perform version checks. One can put something like thisin Makefile.PL for this purpose:

  1. eval { require 5.007 }
  2. or die <<EOD;
  3. ############
  4. ### This module uses frobnication framework which is not available before
  5. ### version 5.007 of Perl. Upgrade your Perl before installing Kara::Mba.
  6. ############
  7. EOD

Dynamic Loading versus Static Loading

It is commonly thought that if a system does not have the capability todynamically load a library, you cannot build XSUBs. This is incorrect.You can build them, but you must link the XSUBs subroutines with therest of Perl, creating a new executable. This situation is similar toPerl 4.

This tutorial can still be used on such a system. The XSUB build mechanismwill check the system and build a dynamically-loadable library if possible,or else a static library and then, optionally, a new statically-linkedexecutable with that static library linked in.

Should you wish to build a statically-linked executable on a system whichcan dynamically load libraries, you may, in all the following examples,where the command "make" with no arguments is executed, run the command"make perl" instead.

If you have generated such a statically-linked executable by choice, theninstead of saying "make test", you should say "make test_static".On systems that cannot build dynamically-loadable libraries at all, simplysaying "make test" is sufficient.

TUTORIAL

Now let's go on with the show!

EXAMPLE 1

Our first extension will be very simple. When we call the routine in theextension, it will print out a well-known message and return.

Run "h2xs -A -n Mytest". This creates a directory named Mytest,possibly under ext/ if that directory exists in the current workingdirectory. Several files will be created under the Mytest dir, includingMANIFEST, Makefile.PL, lib/Mytest.pm, Mytest.xs, t/Mytest.t, and Changes.

The MANIFEST file contains the names of all the files just created in theMytest directory.

The file Makefile.PL should look something like this:

  1. use ExtUtils::MakeMaker;
  2. # See lib/ExtUtils/MakeMaker.pm for details of how to influence
  3. # the contents of the Makefile that is written.
  4. WriteMakefile(
  5. NAME => 'Mytest',
  6. VERSION_FROM => 'Mytest.pm', # finds $VERSION
  7. LIBS => [''], # e.g., '-lm'
  8. DEFINE => '', # e.g., '-DHAVE_SOMETHING'
  9. INC => '', # e.g., '-I/usr/include/other'
  10. );

The file Mytest.pm should start with something like this:

  1. package Mytest;
  2. use 5.008008;
  3. use strict;
  4. use warnings;
  5. require Exporter;
  6. our @ISA = qw(Exporter);
  7. our %EXPORT_TAGS = ( 'all' => [ qw(
  8. ) ] );
  9. our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
  10. our @EXPORT = qw(
  11. );
  12. our $VERSION = '0.01';
  13. require XSLoader;
  14. XSLoader::load('Mytest', $VERSION);
  15. # Preloaded methods go here.
  16. 1;
  17. __END__
  18. # Below is the stub of documentation for your module. You better edit it!

The rest of the .pm file contains sample code for providing documentation forthe extension.

Finally, the Mytest.xs file should look something like this:

  1. #include "EXTERN.h"
  2. #include "perl.h"
  3. #include "XSUB.h"
  4. #include "ppport.h"
  5. MODULE = MytestPACKAGE = Mytest

Let's edit the .xs file by adding this to the end of the file:

  1. void
  2. hello()
  3. CODE:
  4. printf("Hello, world!\n");

It is okay for the lines starting at the "CODE:" line to not be indented.However, for readability purposes, it is suggested that you indent CODE:one level and the lines following one more level.

Now we'll run "perl Makefile.PL". This will create a real Makefile,which make needs. Its output looks something like:

  1. % perl Makefile.PL
  2. Checking if your kit is complete...
  3. Looks good
  4. Writing Makefile for Mytest
  5. %

Now, running make will produce output that looks something like this (somelong lines have been shortened for clarity and some extraneous lines havebeen deleted):

  1. % make
  2. cp lib/Mytest.pm blib/lib/Mytest.pm
  3. perl xsubpp -typemap typemap Mytest.xs > Mytest.xsc && mv Mytest.xsc Mytest.c
  4. Please specify prototyping behavior for Mytest.xs (see perlxs manual)
  5. cc -c Mytest.c
  6. Running Mkbootstrap for Mytest ()
  7. chmod 644 Mytest.bs
  8. rm -f blib/arch/auto/Mytest/Mytest.so
  9. cc -shared -L/usr/local/lib Mytest.o -o blib/arch/auto/Mytest/Mytest.so \
  10. \
  11. chmod 755 blib/arch/auto/Mytest/Mytest.so
  12. cp Mytest.bs blib/arch/auto/Mytest/Mytest.bs
  13. chmod 644 blib/arch/auto/Mytest/Mytest.bs
  14. Manifying blib/man3/Mytest.3pm
  15. %

You can safely ignore the line about "prototyping behavior" - it isexplained in The PROTOTYPES: Keyword in perlxs.

Perl has its own special way of easily writing test scripts, but for thisexample only, we'll create our own test script. Create a file called hellothat looks like this:

  1. #! /opt/perl5/bin/perl
  2. use ExtUtils::testlib;
  3. use Mytest;
  4. Mytest::hello();

Now we make the script executable (chmod +x hello), run the scriptand we should see the following output:

  1. % ./hello
  2. Hello, world!
  3. %

EXAMPLE 2

Now let's add to our extension a subroutine that will take a single numericargument as input and return 1 if the number is even or 0 if the numberis odd.

Add the following to the end of Mytest.xs:

  1. int
  2. is_even(input)
  3. int input
  4. CODE:
  5. RETVAL = (input % 2 == 0);
  6. OUTPUT:
  7. RETVAL

There does not need to be whitespace at the start of the "int input"line, but it is useful for improving readability. Placing a semi-colon atthe end of that line is also optional. Any amount and kind of whitespacemay be placed between the "int" and "input".

Now re-run make to rebuild our new shared library.

Now perform the same steps as before, generating a Makefile from theMakefile.PL file, and running make.

In order to test that our extension works, we now need to look at thefile Mytest.t. This file is set up to imitate the same kind of testingstructure that Perl itself has. Within the test script, you perform anumber of tests to confirm the behavior of the extension, printing "ok"when the test is correct, "not ok" when it is not.

  1. use Test::More tests => 4;
  2. BEGIN { use_ok('Mytest') };
  3. #########################
  4. # Insert your test code below, the Test::More module is use()ed here so read
  5. # its man page ( perldoc Test::More ) for help writing this test script.
  6. is(&Mytest::is_even(0), 1);
  7. is(&Mytest::is_even(1), 0);
  8. is(&Mytest::is_even(2), 1);

We will be calling the test script through the command "make test". Youshould see output that looks something like this:

  1. %make test
  2. PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
  3. t/Mytest....ok
  4. All tests successful.
  5. Files=1, Tests=4, 0 wallclock secs ( 0.03 cusr + 0.00 csys = 0.03 CPU)
  6. %

What has gone on?

The program h2xs is the starting point for creating extensions. In laterexamples we'll see how we can use h2xs to read header files and generatetemplates to connect to C routines.

h2xs creates a number of files in the extension directory. The fileMakefile.PL is a perl script which will generate a true Makefile to buildthe extension. We'll take a closer look at it later.

The .pm and .xs files contain the meat of the extension. The .xs file holdsthe C routines that make up the extension. The .pm file contains routinesthat tell Perl how to load your extension.

Generating the Makefile and running make created a directory called blib(which stands for "build library") in the current working directory. Thisdirectory will contain the shared library that we will build. Once we havetested it, we can install it into its final location.

Invoking the test script via "make test" did something very important.It invoked perl with all those -I arguments so that it could find thevarious files that are part of the extension. It is very important thatwhile you are still testing extensions that you use "make test". If youtry to run the test script all by itself, you will get a fatal error.Another reason it is important to use "make test" to run your testscript is that if you are testing an upgrade to an already-existing version,using "make test" ensures that you will test your new extension, not thealready-existing version.

When Perl sees a use extension;, it searches for a file with the same nameas the use'd extension that has a .pm suffix. If that file cannot be found,Perl dies with a fatal error. The default search path is contained in the@INC array.

In our case, Mytest.pm tells perl that it will need the Exporter and DynamicLoader extensions. It then sets the @ISA and @EXPORT arrays and the$VERSION scalar; finally it tells perl to bootstrap the module. Perlwill call its dynamic loader routine (if there is one) and load the sharedlibrary.

The two arrays @ISA and @EXPORT are very important. The @ISAarray contains a list of other packages in which to search for methods (orsubroutines) that do not exist in the current package. This is usuallyonly important for object-oriented extensions (which we will talk aboutmuch later), and so usually doesn't need to be modified.

The @EXPORT array tells Perl which of the extension's variables andsubroutines should be placed into the calling package's namespace. Becauseyou don't know if the user has already used your variable and subroutinenames, it's vitally important to carefully select what to export. Do notexport method or variable names by default without a good reason.

As a general rule, if the module is trying to be object-oriented then don'texport anything. If it's just a collection of functions and variables, thenyou can export them via another array, called @EXPORT_OK. This arraydoes not automatically place its subroutine and variable names into thenamespace unless the user specifically requests that this be done.

See perlmod for more information.

The $VERSION variable is used to ensure that the .pm file and the sharedlibrary are "in sync" with each other. Any time you make changes tothe .pm or .xs files, you should increment the value of this variable.

Writing good test scripts

The importance of writing good test scripts cannot be over-emphasized. Youshould closely follow the "ok/not ok" style that Perl itself uses, so thatit is very easy and unambiguous to determine the outcome of each test case.When you find and fix a bug, make sure you add a test case for it.

By running "make test", you ensure that your Mytest.t script runs and usesthe correct version of your extension. If you have many test cases,save your test files in the "t" directory and use the suffix ".t".When you run "make test", all of these test files will be executed.

EXAMPLE 3

Our third extension will take one argument as its input, round off thatvalue, and set the argument to the rounded value.

Add the following to the end of Mytest.xs:

  1. void
  2. round(arg)
  3. double arg
  4. CODE:
  5. if (arg > 0.0) {
  6. arg = floor(arg + 0.5);
  7. } else if (arg < 0.0) {
  8. arg = ceil(arg - 0.5);
  9. } else {
  10. arg = 0.0;
  11. }
  12. OUTPUT:
  13. arg

Edit the Makefile.PL file so that the corresponding line looks like this:

  1. 'LIBS' => ['-lm'], # e.g., '-lm'

Generate the Makefile and run make. Change the test number in Mytest.t to"9" and add the following tests:

  1. $i = -1.5; &Mytest::round($i); is( $i, -2.0 );
  2. $i = -1.1; &Mytest::round($i); is( $i, -1.0 );
  3. $i = 0.0; &Mytest::round($i); is( $i, 0.0 );
  4. $i = 0.5; &Mytest::round($i); is( $i, 1.0 );
  5. $i = 1.2; &Mytest::round($i); is( $i, 1.0 );

Running "make test" should now print out that all nine tests are okay.

Notice that in these new test cases, the argument passed to round was ascalar variable. You might be wondering if you can round a constant orliteral. To see what happens, temporarily add the following line to Mytest.t:

  1. &Mytest::round(3);

Run "make test" and notice that Perl dies with a fatal error. Perl won'tlet you change the value of constants!

What's new here?

  • We've made some changes to Makefile.PL. In this case, we've specified anextra library to be linked into the extension's shared library, the mathlibrary libm in this case. We'll talk later about how to write XSUBs thatcan call every routine in a library.

  • The value of the function is not being passed back as the function's returnvalue, but by changing the value of the variable that was passed into thefunction. You might have guessed that when you saw that the return valueof round is of type "void".

Input and Output Parameters

You specify the parameters that will be passed into the XSUB on the line(s)after you declare the function's return value and name. Each input parameterline starts with optional whitespace, and may have an optional terminatingsemicolon.

The list of output parameters occurs at the very end of the function, justafter the OUTPUT: directive. The use of RETVAL tells Perl that youwish to send this value back as the return value of the XSUB function. InExample 3, we wanted the "return value" placed in the original variablewhich we passed in, so we listed it (and not RETVAL) in the OUTPUT: section.

The XSUBPP Program

The xsubpp program takes the XS code in the .xs file and translates it intoC code, placing it in a file whose suffix is .c. The C code created makesheavy use of the C functions within Perl.

The TYPEMAP file

The xsubpp program uses rules to convert from Perl's data types (scalar,array, etc.) to C's data types (int, char, etc.). These rules are storedin the typemap file ($PERLLIB/ExtUtils/typemap). There's a brief discussionbelow, but all the nitty-gritty details can be found in perlxstypemap.If you have a new-enough version of perl (5.16 and up) or an upgradedXS compiler (ExtUtils::ParseXS 3.13_01 or better), then you can inlinetypemaps in your XS instead of writing separate files.Either way, this typemap thing is split into three parts:

The first section maps various C data types to a name, which correspondssomewhat with the various Perl types. The second section contains C codewhich xsubpp uses to handle input parameters. The third section containsC code which xsubpp uses to handle output parameters.

Let's take a look at a portion of the .c file created for our extension.The file name is Mytest.c:

  1. XS(XS_Mytest_round)
  2. {
  3. dXSARGS;
  4. if (items != 1)
  5. Perl_croak(aTHX_ "Usage: Mytest::round(arg)");
  6. PERL_UNUSED_VAR(cv); /* -W */
  7. {
  8. double arg = (double)SvNV(ST(0));/* XXXXX */
  9. if (arg > 0.0) {
  10. arg = floor(arg + 0.5);
  11. } else if (arg < 0.0) {
  12. arg = ceil(arg - 0.5);
  13. } else {
  14. arg = 0.0;
  15. }
  16. sv_setnv(ST(0), (double)arg);/* XXXXX */
  17. SvSETMAGIC(ST(0));
  18. }
  19. XSRETURN_EMPTY;
  20. }

Notice the two lines commented with "XXXXX". If you check the first partof the typemap file (or section), you'll see that doubles are of typeT_DOUBLE. In the INPUT part of the typemap, an argument that is T_DOUBLEis assigned to the variable arg by calling the routine SvNV on something,then casting it to double, then assigned to the variable arg. Similarly,in the OUTPUT section, once arg has its final value, it is passed to thesv_setnv function to be passed back to the calling subroutine. These twofunctions are explained in perlguts; we'll talk more later about whatthat "ST(0)" means in the section on the argument stack.

Warning about Output Arguments

In general, it's not a good idea to write extensions that modify their inputparameters, as in Example 3. Instead, you should probably return multiplevalues in an array and let the caller handle them (we'll do this in a laterexample). However, in order to better accommodate calling pre-existing Croutines, which often do modify their input parameters, this behavior istolerated.

EXAMPLE 4

In this example, we'll now begin to write XSUBs that will interact withpre-defined C libraries. To begin with, we will build a small library ofour own, then let h2xs write our .pm and .xs files for us.

Create a new directory called Mytest2 at the same level as the directoryMytest. In the Mytest2 directory, create another directory called mylib,and cd into that directory.

Here we'll create some files that will generate a test library. These willinclude a C source file and a header file. We'll also create a Makefile.PLin this directory. Then we'll make sure that running make at the Mytest2level will automatically run this Makefile.PL file and the resulting Makefile.

In the mylib directory, create a file mylib.h that looks like this:

  1. #define TESTVAL4
  2. extern doublefoo(int, long, const char*);

Also create a file mylib.c that looks like this:

  1. #include <stdlib.h>
  2. #include "./mylib.h"
  3. double
  4. foo(int a, long b, const char *c)
  5. {
  6. return (a + b + atof(c) + TESTVAL);
  7. }

And finally create a file Makefile.PL that looks like this:

  1. use ExtUtils::MakeMaker;
  2. $Verbose = 1;
  3. WriteMakefile(
  4. NAME => 'Mytest2::mylib',
  5. SKIP => [qw(all static static_lib dynamic dynamic_lib)],
  6. clean => {'FILES' => 'libmylib$(LIB_EXT)'},
  7. );
  8. sub MY::top_targets {
  9. '
  10. all :: static
  11. pure_all :: static
  12. static :: libmylib$(LIB_EXT)
  13. libmylib$(LIB_EXT): $(O_FILES)
  14. $(AR) cr libmylib$(LIB_EXT) $(O_FILES)
  15. $(RANLIB) libmylib$(LIB_EXT)
  16. ';
  17. }

Make sure you use a tab and not spaces on the lines beginning with "$(AR)"and "$(RANLIB)". Make will not function properly if you use spaces.It has also been reported that the "cr" argument to $(AR) is unnecessaryon Win32 systems.

We will now create the main top-level Mytest2 files. Change to the directoryabove Mytest2 and run the following command:

  1. % h2xs -O -n Mytest2 ./Mytest2/mylib/mylib.h

This will print out a warning about overwriting Mytest2, but that's okay.Our files are stored in Mytest2/mylib, and will be untouched.

The normal Makefile.PL that h2xs generates doesn't know about the mylibdirectory. We need to tell it that there is a subdirectory and that wewill be generating a library in it. Let's add the argument MYEXTLIB tothe WriteMakefile call so that it looks like this:

  1. WriteMakefile(
  2. 'NAME' => 'Mytest2',
  3. 'VERSION_FROM' => 'Mytest2.pm', # finds $VERSION
  4. 'LIBS' => [''], # e.g., '-lm'
  5. 'DEFINE' => '', # e.g., '-DHAVE_SOMETHING'
  6. 'INC' => '', # e.g., '-I/usr/include/other'
  7. 'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)',
  8. );

and then at the end add a subroutine (which will override the pre-existingsubroutine). Remember to use a tab character to indent the line beginningwith "cd"!

  1. sub MY::postamble {
  2. '
  3. $(MYEXTLIB): mylib/Makefile
  4. cd mylib && $(MAKE) $(PASSTHRU)
  5. ';
  6. }

Let's also fix the MANIFEST file so that it accurately reflects the contentsof our extension. The single line that says "mylib" should be replaced bythe following three lines:

  1. mylib/Makefile.PL
  2. mylib/mylib.c
  3. mylib/mylib.h

To keep our namespace nice and unpolluted, edit the .pm file and changethe variable @EXPORT to @EXPORT_OK. Finally, in the.xs file, edit the #include line to read:

  1. #include "mylib/mylib.h"

And also add the following function definition to the end of the .xs file:

  1. double
  2. foo(a,b,c)
  3. int a
  4. long b
  5. const char * c
  6. OUTPUT:
  7. RETVAL

Now we also need to create a typemap because the default Perl doesn'tcurrently support the const char * type. Include a new TYPEMAPsection in your XS code before the above function:

  1. TYPEMAP: <<END;
  2. const char *T_PV
  3. END

Now run perl on the top-level Makefile.PL. Notice that it also created aMakefile in the mylib directory. Run make and watch that it does cd intothe mylib directory and run make in there as well.

Now edit the Mytest2.t script and change the number of tests to "4",and add the following lines to the end of the script:

  1. is( &Mytest2::foo(1, 2, "Hello, world!"), 7 );
  2. is( &Mytest2::foo(1, 2, "0.0"), 7 );
  3. ok( abs(&Mytest2::foo(0, 0, "-3.4") - 0.6) <= 0.01 );

(When dealing with floating-point comparisons, it is best to not check forequality, but rather that the difference between the expected and actualresult is below a certain amount (called epsilon) which is 0.01 in this case)

Run "make test" and all should be well. There are some warnings on missing testsfor the Mytest2::mylib extension, but you can ignore them.

What has happened here?

Unlike previous examples, we've now run h2xs on a real include file. Thishas caused some extra goodies to appear in both the .pm and .xs files.

  • In the .xs file, there's now a #include directive with the absolute path tothe mylib.h header file. We changed this to a relative path so that wecould move the extension directory if we wanted to.

  • There's now some new C code that's been added to the .xs file. The purposeof the constant routine is to make the values that are #define'd in theheader file accessible by the Perl script (by calling either TESTVAL or&Mytest2::TESTVAL). There's also some XS code to allow calls to theconstant routine.

  • The .pm file originally exported the name TESTVAL in the @EXPORT array.This could lead to name clashes. A good rule of thumb is that if the #defineis only going to be used by the C routines themselves, and not by the user,they should be removed from the @EXPORT array. Alternately, if you don'tmind using the "fully qualified name" of a variable, you could move mostor all of the items from the @EXPORT array into the @EXPORT_OK array.

  • If our include file had contained #include directives, these would not havebeen processed by h2xs. There is no good solution to this right now.

  • We've also told Perl about the library that we built in the mylibsubdirectory. That required only the addition of the MYEXTLIB variableto the WriteMakefile call and the replacement of the postamble subroutineto cd into the subdirectory and run make. The Makefile.PL for thelibrary is a bit more complicated, but not excessively so. Again wereplaced the postamble subroutine to insert our own code. This codesimply specified that the library to be created here was a static archivelibrary (as opposed to a dynamically loadable library) and provided thecommands to build it.

Anatomy of .xs file

The .xs file of EXAMPLE 4 contained some new elements. To understandthe meaning of these elements, pay attention to the line which reads

  1. MODULE = Mytest2PACKAGE = Mytest2

Anything before this line is plain C code which describes which headersto include, and defines some convenience functions. No translations areperformed on this part, apart from having embedded POD documentationskipped over (see perlpod) it goes into the generated output C file as is.

Anything after this line is the description of XSUB functions.These descriptions are translated by xsubpp into C code whichimplements these functions using Perl calling conventions, and whichmakes these functions visible from Perl interpreter.

Pay a special attention to the function constant. This name appearstwice in the generated .xs file: once in the first part, as a static Cfunction, then another time in the second part, when an XSUB interface tothis static C function is defined.

This is quite typical for .xs files: usually the .xs file providesan interface to an existing C function. Then this C function is definedsomewhere (either in an external library, or in the first part of .xs file),and a Perl interface to this function (i.e. "Perl glue") is described in thesecond part of .xs file. The situation in EXAMPLE 1, EXAMPLE 2,and EXAMPLE 3, when all the work is done inside the "Perl glue", issomewhat of an exception rather than the rule.

Getting the fat out of XSUBs

In EXAMPLE 4 the second part of .xs file contained the followingdescription of an XSUB:

  1. double
  2. foo(a,b,c)
  3. int a
  4. long b
  5. const char * c
  6. OUTPUT:
  7. RETVAL

Note that in contrast with EXAMPLE 1, EXAMPLE 2 and EXAMPLE 3,this description does not contain the actual code for what is doneduring a call to Perl function foo(). To understand what is goingon here, one can add a CODE section to this XSUB:

  1. double
  2. foo(a,b,c)
  3. int a
  4. long b
  5. const char * c
  6. CODE:
  7. RETVAL = foo(a,b,c);
  8. OUTPUT:
  9. RETVAL

However, these two XSUBs provide almost identical generated C code: xsubppcompiler is smart enough to figure out the CODE: section from the firsttwo lines of the description of XSUB. What about OUTPUT: section? Infact, that is absolutely the same! The OUTPUT: section can be removedas well, as far as CODE: section or PPCODE: section is notspecified: xsubpp can see that it needs to generate a function callsection, and will autogenerate the OUTPUT section too. Thus one canshortcut the XSUB to become:

  1. double
  2. foo(a,b,c)
  3. int a
  4. long b
  5. const char * c

Can we do the same with an XSUB

  1. int
  2. is_even(input)
  3. intinput
  4. CODE:
  5. RETVAL = (input % 2 == 0);
  6. OUTPUT:
  7. RETVAL

of EXAMPLE 2? To do this, one needs to define a C function intis_even(int input). As we saw in Anatomy of .xs file, a proper placefor this definition is in the first part of .xs file. In fact a C function

  1. int
  2. is_even(int arg)
  3. {
  4. return (arg % 2 == 0);
  5. }

is probably overkill for this. Something as simple as a #define willdo too:

  1. #define is_even(arg)((arg) % 2 == 0)

After having this in the first part of .xs file, the "Perl glue" part becomesas simple as

  1. int
  2. is_even(input)
  3. intinput

This technique of separation of the glue part from the workhorse part hasobvious tradeoffs: if you want to change a Perl interface, you need tochange two places in your code. However, it removes a lot of clutter,and makes the workhorse part independent from idiosyncrasies of Perl callingconvention. (In fact, there is nothing Perl-specific in the above description,a different version of xsubpp might have translated this to TCL glue orPython glue as well.)

More about XSUB arguments

With the completion of Example 4, we now have an easy way to simulate somereal-life libraries whose interfaces may not be the cleanest in the world.We shall now continue with a discussion of the arguments passed to thexsubpp compiler.

When you specify arguments to routines in the .xs file, you are reallypassing three pieces of information for each argument listed. The firstpiece is the order of that argument relative to the others (first, second,etc). The second is the type of argument, and consists of the typedeclaration of the argument (e.g., int, char*, etc). The third piece isthe calling convention for the argument in the call to the library function.

While Perl passes arguments to functions by reference,C passes arguments by value; to implement a C function which modifies dataof one of the "arguments", the actual argument of this C function would bea pointer to the data. Thus two C functions with declarations

  1. int string_length(char *s);
  2. int upper_case_char(char *cp);

may have completely different semantics: the first one may inspect an arrayof chars pointed by s, and the second one may immediately dereference cpand manipulate *cp only (using the return value as, say, a successindicator). From Perl one would use these functions ina completely different manner.

One conveys this info to xsubpp by replacing * before theargument by &. & means that the argument should be passed to a libraryfunction by its address. The above two function may be XSUB-ified as

  1. int
  2. string_length(s)
  3. char *s
  4. int
  5. upper_case_char(cp)
  6. char&cp

For example, consider:

  1. int
  2. foo(a,b)
  3. char&a
  4. char *b

The first Perl argument to this function would be treated as a char and assignedto the variable a, and its address would be passed into the function foo.The second Perl argument would be treated as a string pointer and assigned to thevariable b. The value of b would be passed into the function foo. Theactual call to the function foo that xsubpp generates would look like this:

  1. foo(&a, b);

xsubpp will parse the following function argument lists identically:

  1. char&a
  2. char&a
  3. char& a

However, to help ease understanding, it is suggested that you place a "&"next to the variable name and away from the variable type), and place a"*" near the variable type, but away from the variable name (as in thecall to foo above). By doing so, it is easy to understand exactly whatwill be passed to the C function; it will be whatever is in the "lastcolumn".

You should take great pains to try to pass the function the type of variableit wants, when possible. It will save you a lot of trouble in the long run.

The Argument Stack

If we look at any of the C code generated by any of the examples exceptexample 1, you will notice a number of references to ST(n), where n isusually 0. "ST" is actually a macro that points to the n'th argumenton the argument stack. ST(0) is thus the first argument on the stack andtherefore the first argument passed to the XSUB, ST(1) is the secondargument, and so on.

When you list the arguments to the XSUB in the .xs file, that tells xsubppwhich argument corresponds to which of the argument stack (i.e., the firstone listed is the first argument, and so on). You invite disaster if youdo not list them in the same order as the function expects them.

The actual values on the argument stack are pointers to the values passedin. When an argument is listed as being an OUTPUT value, its correspondingvalue on the stack (i.e., ST(0) if it was the first argument) is changed.You can verify this by looking at the C code generated for Example 3.The code for the round() XSUB routine contains lines that look like this:

  1. double arg = (double)SvNV(ST(0));
  2. /* Round the contents of the variable arg */
  3. sv_setnv(ST(0), (double)arg);

The arg variable is initially set by taking the value from ST(0), then isstored back into ST(0) at the end of the routine.

XSUBs are also allowed to return lists, not just scalars. This must bedone by manipulating stack values ST(0), ST(1), etc, in a subtlydifferent way. See perlxs for details.

XSUBs are also allowed to avoid automatic conversion of Perl function argumentsto C function arguments. See perlxs for details. Some people prefermanual conversion by inspecting ST(i) even in the cases when automaticconversion will do, arguing that this makes the logic of an XSUB call clearer.Compare with Getting the fat out of XSUBs for a similar tradeoff ofa complete separation of "Perl glue" and "workhorse" parts of an XSUB.

While experts may argue about these idioms, a novice to Perl guts mayprefer a way which is as little Perl-guts-specific as possible, meaningautomatic conversion and automatic call generation, as inGetting the fat out of XSUBs. This approach has the additionalbenefit of protecting the XSUB writer from future changes to the Perl API.

Extending your Extension

Sometimes you might want to provide some extra methods or subroutinesto assist in making the interface between Perl and your extension simpleror easier to understand. These routines should live in the .pm file.Whether they are automatically loaded when the extension itself is loadedor only loaded when called depends on where in the .pm file the subroutinedefinition is placed. You can also consult AutoLoader for an alternateway to store and load your extra subroutines.

Documenting your Extension

There is absolutely no excuse for not documenting your extension.Documentation belongs in the .pm file. This file will be fed to pod2man,and the embedded documentation will be converted to the manpage format,then placed in the blib directory. It will be copied to Perl'smanpage directory when the extension is installed.

You may intersperse documentation and Perl code within the .pm file.In fact, if you want to use method autoloading, you must do this,as the comment inside the .pm file explains.

See perlpod for more information about the pod format.

Installing your Extension

Once your extension is complete and passes all its tests, installing itis quite simple: you simply run "make install". You will either needto have write permission into the directories where Perl is installed,or ask your system administrator to run the make for you.

Alternately, you can specify the exact directory to place the extension'sfiles by placing a "PREFIX=/destination/directory" after the make install.(or in between the make and install if you have a brain-dead version of make).This can be very useful if you are building an extension that will eventuallybe distributed to multiple systems. You can then just archive the files inthe destination directory and distribute them to your destination systems.

EXAMPLE 5

In this example, we'll do some more work with the argument stack. Theprevious examples have all returned only a single value. We'll nowcreate an extension that returns an array.

This extension is very Unix-oriented (struct statfs and the statfs systemcall). If you are not running on a Unix system, you can substitute forstatfs any other function that returns multiple values, you can hard-codevalues to be returned to the caller (although this will be a bit harderto test the error case), or you can simply not do this example. If youchange the XSUB, be sure to fix the test cases to match the changes.

Return to the Mytest directory and add the following code to the end ofMytest.xs:

  1. void
  2. statfs(path)
  3. char * path
  4. INIT:
  5. int i;
  6. struct statfs buf;
  7. PPCODE:
  8. i = statfs(path, &buf);
  9. if (i == 0) {
  10. XPUSHs(sv_2mortal(newSVnv(buf.f_bavail)));
  11. XPUSHs(sv_2mortal(newSVnv(buf.f_bfree)));
  12. XPUSHs(sv_2mortal(newSVnv(buf.f_blocks)));
  13. XPUSHs(sv_2mortal(newSVnv(buf.f_bsize)));
  14. XPUSHs(sv_2mortal(newSVnv(buf.f_ffree)));
  15. XPUSHs(sv_2mortal(newSVnv(buf.f_files)));
  16. XPUSHs(sv_2mortal(newSVnv(buf.f_type)));
  17. } else {
  18. XPUSHs(sv_2mortal(newSVnv(errno)));
  19. }

You'll also need to add the following code to the top of the .xs file, justafter the include of "XSUB.h":

  1. #include <sys/vfs.h>

Also add the following code segment to Mytest.t while incrementing the "9"tests to "11":

  1. @a = &Mytest::statfs("/blech");
  2. ok( scalar(@a) == 1 && $a[0] == 2 );
  3. @a = &Mytest::statfs("/");
  4. is( scalar(@a), 7 );

New Things in this Example

This example added quite a few new concepts. We'll take them one at a time.

  • The INIT: directive contains code that will be placed immediately afterthe argument stack is decoded. C does not allow variable declarations atarbitrary locations inside a function,so this is usually the best way to declare local variables needed by the XSUB.(Alternatively, one could put the whole PPCODE: section into braces, andput these declarations on top.)

  • This routine also returns a different number of arguments depending on thesuccess or failure of the call to statfs. If there is an error, the errornumber is returned as a single-element array. If the call is successful,then a 7-element array is returned. Since only one argument is passed intothis function, we need room on the stack to hold the 7 values which may bereturned.

    We do this by using the PPCODE: directive, rather than the CODE: directive.This tells xsubpp that we will be managing the return values that will beput on the argument stack by ourselves.

  • When we want to place values to be returned to the caller onto the stack,we use the series of macros that begin with "XPUSH". There are fivedifferent versions, for placing integers, unsigned integers, doubles,strings, and Perl scalars on the stack. In our example, we placed aPerl scalar onto the stack. (In fact this is the only macro whichcan be used to return multiple values.)

    The XPUSH* macros will automatically extend the return stack to preventit from being overrun. You push values onto the stack in the order youwant them seen by the calling program.

  • The values pushed onto the return stack of the XSUB are actually mortal SV's.They are made mortal so that once the values are copied by the callingprogram, the SV's that held the returned values can be deallocated.If they were not mortal, then they would continue to exist after the XSUBroutine returned, but would not be accessible. This is a memory leak.

  • If we were interested in performance, not in code compactness, in the successbranch we would not use XPUSHs macros, but PUSHs macros, and wouldpre-extend the stack before pushing the return values:

    1. EXTEND(SP, 7);

    The tradeoff is that one needs to calculate the number of return valuesin advance (though overextending the stack will not typically hurtanything but memory consumption).

    Similarly, in the failure branch we could use PUSHs without extendingthe stack: the Perl function reference comes to an XSUB on the stack, thusthe stack is always large enough to take one return value.

EXAMPLE 6

In this example, we will accept a reference to an array as an inputparameter, and return a reference to an array of hashes. This willdemonstrate manipulation of complex Perl data types from an XSUB.

This extension is somewhat contrived. It is based on the code inthe previous example. It calls the statfs function multiple times,accepting a reference to an array of filenames as input, and returninga reference to an array of hashes containing the data for each of thefilesystems.

Return to the Mytest directory and add the following code to the end ofMytest.xs:

  1. SV *
  2. multi_statfs(paths)
  3. SV * paths
  4. INIT:
  5. AV * results;
  6. I32 numpaths = 0;
  7. int i, n;
  8. struct statfs buf;
  9. SvGETMAGIC(paths);
  10. if ((!SvROK(paths))
  11. || (SvTYPE(SvRV(paths)) != SVt_PVAV)
  12. || ((numpaths = av_len((AV *)SvRV(paths))) < 0))
  13. {
  14. XSRETURN_UNDEF;
  15. }
  16. results = (AV *)sv_2mortal((SV *)newAV());
  17. CODE:
  18. for (n = 0; n <= numpaths; n++) {
  19. HV * rh;
  20. STRLEN l;
  21. char * fn = SvPV(*av_fetch((AV *)SvRV(paths), n, 0), l);
  22. i = statfs(fn, &buf);
  23. if (i != 0) {
  24. av_push(results, newSVnv(errno));
  25. continue;
  26. }
  27. rh = (HV *)sv_2mortal((SV *)newHV());
  28. hv_store(rh, "f_bavail", 8, newSVnv(buf.f_bavail), 0);
  29. hv_store(rh, "f_bfree", 7, newSVnv(buf.f_bfree), 0);
  30. hv_store(rh, "f_blocks", 8, newSVnv(buf.f_blocks), 0);
  31. hv_store(rh, "f_bsize", 7, newSVnv(buf.f_bsize), 0);
  32. hv_store(rh, "f_ffree", 7, newSVnv(buf.f_ffree), 0);
  33. hv_store(rh, "f_files", 7, newSVnv(buf.f_files), 0);
  34. hv_store(rh, "f_type", 6, newSVnv(buf.f_type), 0);
  35. av_push(results, newRV((SV *)rh));
  36. }
  37. RETVAL = newRV((SV *)results);
  38. OUTPUT:
  39. RETVAL

And add the following code to Mytest.t, while incrementing the "11"tests to "13":

  1. $results = Mytest::multi_statfs([ '/', '/blech' ]);
  2. ok( ref $results->[0] );
  3. ok( ! ref $results->[1] );

New Things in this Example

There are a number of new concepts introduced here, described below:

  • This function does not use a typemap. Instead, we declare it as acceptingone SV* (scalar) parameter, and returning an SV* value, and we take care ofpopulating these scalars within the code. Because we are only returningone value, we don't need a PPCODE: directive - instead, we use CODE:and OUTPUT: directives.

  • When dealing with references, it is important to handle them with caution.The INIT: block first calls SvGETMAGIC(paths), in casepaths is a tied variable. Then it checks that SvROK returnstrue, which indicates that paths is a valid reference. (Simplychecking SvROK won't trigger FETCH on a tied variable.) Itthen verifies that the object referenced by paths is an array, using SvRVto dereference paths, and SvTYPE to discover its type. As an added test,it checks that the array referenced by paths is non-empty, using the av_lenfunction (which returns -1 if the array is empty). The XSRETURN_UNDEF macrois used to abort the XSUB and return the undefined value whenever all three ofthese conditions are not met.

  • We manipulate several arrays in this XSUB. Note that an array is representedinternally by an AV* pointer. The functions and macros for manipulatingarrays are similar to the functions in Perl: av_len returns the highestindex in an AV*, much like $#array; av_fetch fetches a single scalar valuefrom an array, given its index; av_push pushes a scalar value onto theend of the array, automatically extending the array as necessary.

    Specifically, we read pathnames one at a time from the input array, andstore the results in an output array (results) in the same order. Ifstatfs fails, the element pushed onto the return array is the value oferrno after the failure. If statfs succeeds, though, the value pushedonto the return array is a reference to a hash containing some of theinformation in the statfs structure.

    As with the return stack, it would be possible (and a small performance win)to pre-extend the return array before pushing data into it, since we knowhow many elements we will return:

    1. av_extend(results, numpaths);
  • We are performing only one hash operation in this function, which is storinga new scalar under a key using hv_store. A hash is represented by an HV*pointer. Like arrays, the functions for manipulating hashes from an XSUBmirror the functionality available from Perl. See perlguts and perlapifor details.

  • To create a reference, we use the newRV function. Note that you cancast an AV* or an HV* to type SV* in this case (and many others). Thisallows you to take references to arrays, hashes and scalars with the samefunction. Conversely, the SvRV function always returns an SV*, which mayneed to be cast to the appropriate type if it is something other than ascalar (check with SvTYPE).

  • At this point, xsubpp is doing very little work - the differences betweenMytest.xs and Mytest.c are minimal.

EXAMPLE 7 (Coming Soon)

XPUSH args AND set RETVAL AND assign return value to array

EXAMPLE 8 (Coming Soon)

Setting $!

EXAMPLE 9 Passing open files to XSes

You would think passing files to an XS is difficult, with all thetypeglobs and stuff. Well, it isn't.

Suppose that for some strange reason we need a wrapper around thestandard C library function fputs(). This is all we need:

  1. #define PERLIO_NOT_STDIO 0
  2. #include "EXTERN.h"
  3. #include "perl.h"
  4. #include "XSUB.h"
  5. #include <stdio.h>
  6. int
  7. fputs(s, stream)
  8. char * s
  9. FILE * stream

The real work is done in the standard typemap.

But you loose all the fine stuff done by the perlio layers. Thiscalls the stdio function fputs(), which knows nothing about them.

The standard typemap offers three variants of PerlIO *:InputStream (T_IN), InOutStream (T_INOUT) and OutputStream(T_OUT). A bare PerlIO * is considered a T_INOUT. If it mattersin your code (see below for why it might) #define or typedefone of the specific names and use that as the argument or resulttype in your XS file.

The standard typemap does not contain PerlIO * before perl 5.7,but it has the three stream variants. Using a PerlIO * directlyis not backwards compatible unless you provide your own typemap.

For streams coming from perl the main difference is thatOutputStream will get the output PerlIO * - which may makea difference on a socket. Like in our example...

For streams being handed to perl a new file handle is created(i.e. a reference to a new glob) and associated with the PerlIO *provided. If the read/write state of the PerlIO * is not correct then youmay get errors or warnings from when the file handle is used.So if you opened the PerlIO * as "w" it should really be anOutputStream if open as "r" it should be an InputStream.

Now, suppose you want to use perlio layers in your XS. We'll use theperlio PerlIO_puts() function as an example.

In the C part of the XS file (above the first MODULE line) youhave

  1. #define OutputStreamPerlIO *
  2. or
  3. typedef PerlIO *OutputStream;

And this is the XS code:

  1. int
  2. perlioputs(s, stream)
  3. char * s
  4. OutputStreamstream
  5. CODE:
  6. RETVAL = PerlIO_puts(stream, s);
  7. OUTPUT:
  8. RETVAL

We have to use a CODE section because PerlIO_puts() has the argumentsreversed compared to fputs(), and we want to keep the arguments the same.

Wanting to explore this thoroughly, we want to use the stdio fputs()on a PerlIO *. This means we have to ask the perlio system for a stdioFILE *:

  1. int
  2. perliofputs(s, stream)
  3. char * s
  4. OutputStreamstream
  5. PREINIT:
  6. FILE *fp = PerlIO_findFILE(stream);
  7. CODE:
  8. if (fp != (FILE*) 0) {
  9. RETVAL = fputs(s, fp);
  10. } else {
  11. RETVAL = -1;
  12. }
  13. OUTPUT:
  14. RETVAL

Note: PerlIO_findFILE() will search the layers for a stdiolayer. If it can't find one, it will call PerlIO_exportFILE() togenerate a new stdio FILE. Please only call PerlIO_exportFILE() ifyou want a new FILE. It will generate one on each call and push anew stdio layer. So don't call it repeatedly on the samefile. PerlIO_findFILE() will retrieve the stdio layer once it has beengenerated by PerlIO_exportFILE().

This applies to the perlio system only. For versions before 5.7,PerlIO_exportFILE() is equivalent to PerlIO_findFILE().

Troubleshooting these Examples

As mentioned at the top of this document, if you are having problems withthese example extensions, you might see if any of these help you.

  • In versions of 5.002 prior to the gamma version, the test script in Example1 will not function properly. You need to change the "use lib" line toread:

    1. use lib './blib';
  • In versions of 5.002 prior to version 5.002b1h, the test.pl file was notautomatically created by h2xs. This means that you cannot say "make test"to run the test script. You will need to add the following line before the"use extension" statement:

    1. use lib './blib';
  • In versions 5.000 and 5.001, instead of using the above line, you will needto use the following line:

    1. BEGIN { unshift(@INC, "./blib") }
  • This document assumes that the executable named "perl" is Perl version 5.Some systems may have installed Perl version 5 as "perl5".

See also

For more information, consult perlguts, perlapi, perlxs, perlmod,and perlpod.

Author

Jeff Okamoto <[email protected]>

Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig,and Tim Bunce.

PerlIO material contributed by Lupe Christoph, with some clarificationby Nick Ing-Simmons.

Changes for h2xs as of Perl 5.8.x by Renee Baecker

Last Changed

2012-01-20

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Tutorial on threads in PerlPerl Unicode Tutorial (Berikutnya)