ExtUtils-ParseXS
view release on metacpan or search on metacpan
lib/perlxstut.pod view on Meta::CPAN
The .xs file of L</EXAMPLE 4> contained some new elements. To understand
the meaning of these elements, pay attention to the line which reads
MODULE = Mytest2 PACKAGE = Mytest2
Anything before this line is plain C code which describes which headers
to include, and defines some convenience functions. No translations are
performed on this part, apart from having embedded POD documentation
skipped over (see L<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 B<xsubpp> into C code which
implements these functions using Perl calling conventions, and which
makes these functions visible from Perl interpreter.
Pay a special attention to the function C<constant>. This name appears
twice in the generated .xs file: once in the first part, as a static C
function, then another time in the second part, when an XSUB interface to
this static C function is defined.
This is quite typical for .xs files: usually the .xs file provides
an interface to an existing C function. Then this C function is defined
somewhere (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 the
second part of .xs file. The situation in L<"EXAMPLE 1">, L<"EXAMPLE 2">,
and L<"EXAMPLE 3">, when all the work is done inside the "Perl glue", is
somewhat of an exception rather than the rule.
=head2 Getting the fat out of XSUBs
In L</EXAMPLE 4> the second part of .xs file contained the following
description of an XSUB:
double
foo(a,b,c)
int a
long b
const char * c
OUTPUT:
RETVAL
Note that in contrast with L<"EXAMPLE 1">, L<"EXAMPLE 2"> and L<"EXAMPLE 3">,
this description does not contain the actual I<code> for what is done
during a call to Perl function foo(). To understand what is going
on here, one can add a CODE section to this XSUB:
double
foo(a,b,c)
int a
long b
const char * c
CODE:
RETVAL = foo(a,b,c);
OUTPUT:
RETVAL
However, these two XSUBs provide almost identical generated C code: B<xsubpp>
compiler is smart enough to figure out the C<CODE:> section from the first
two lines of the description of XSUB. What about C<OUTPUT:> section? In
fact, that is absolutely the same! The C<OUTPUT:> section can be removed
as well, I<as far as C<CODE:> section or C<PPCODE:> section> is not
specified: B<xsubpp> can see that it needs to generate a function call
section, and will autogenerate the OUTPUT section too. Thus one can
shortcut the XSUB to become:
double
foo(a,b,c)
int a
long b
const char * c
Can we do the same with an XSUB
int
is_even(input)
int input
CODE:
RETVAL = (input % 2 == 0);
OUTPUT:
RETVAL
of L<"EXAMPLE 2">? To do this, one needs to define a C function C<int
is_even(int input)>. As we saw in L<Anatomy of .xs file>, a proper place
for this definition is in the first part of .xs file. In fact a C function
int
is_even(int arg)
{
return (arg % 2 == 0);
}
is probably overkill for this. Something as simple as a C<#define> will
do too:
#define is_even(arg) ((arg) % 2 == 0)
After having this in the first part of .xs file, the "Perl glue" part becomes
as simple as
int
is_even(input)
int input
This technique of separation of the glue part from the workhorse part has
obvious tradeoffs: if you want to change a Perl interface, you need to
change two places in your code. However, it removes a lot of clutter,
and makes the workhorse part independent from idiosyncrasies of Perl calling
convention. (In fact, there is nothing Perl-specific in the above description,
a different version of B<xsubpp> might have translated this to TCL glue or
Python glue as well.)
=head2 More about XSUB arguments
With the completion of Example 4, we now have an easy way to simulate some
real-life libraries whose interfaces may not be the cleanest in the world.
We shall now continue with a discussion of the arguments passed to the
B<xsubpp> compiler.
When you specify arguments to routines in the .xs file, you are really
passing three pieces of information for each argument listed. The first
piece is the order of that argument relative to the others (first, second,
lib/perlxstut.pod view on Meta::CPAN
Sometimes you might want to provide some extra methods or subroutines
to assist in making the interface between Perl and your extension simpler
or easier to understand. These routines should live in the .pm file.
Whether they are automatically loaded when the extension itself is loaded
or only loaded when called depends on where in the .pm file the subroutine
definition is placed. You can also consult L<AutoLoader> for an alternate
way to store and load your extra subroutines.
=head2 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's
manpage 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 L<perlpod> for more information about the pod format.
=head2 Installing your Extension
Once your extension is complete and passes all its tests, installing it
is quite simple: you simply run "make install". You will either need
to 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's
files 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 eventually
be distributed to multiple systems. You can then just archive the files in
the destination directory and distribute them to your destination systems.
=head2 EXAMPLE 5
In this example, we'll do some more work with the argument stack. The
previous examples have all returned only a single value. We'll now
create an extension that returns an array.
This extension is very Unix-oriented (struct statfs and the statfs system
call). If you are not running on a Unix system, you can substitute for
statfs any other function that returns multiple values, you can hard-code
values to be returned to the caller (although this will be a bit harder
to test the error case), or you can simply not do this example. If you
change 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 of
Mytest.xs:
void
statfs(path)
char * path
INIT:
int i;
struct statfs buf;
PPCODE:
i = statfs(path, &buf);
if (i == 0) {
XPUSHs(sv_2mortal(newSVnv(buf.f_bavail)));
XPUSHs(sv_2mortal(newSVnv(buf.f_bfree)));
XPUSHs(sv_2mortal(newSVnv(buf.f_blocks)));
XPUSHs(sv_2mortal(newSVnv(buf.f_bsize)));
XPUSHs(sv_2mortal(newSVnv(buf.f_ffree)));
XPUSHs(sv_2mortal(newSVnv(buf.f_files)));
XPUSHs(sv_2mortal(newSVnv(buf.f_type)));
} else {
XPUSHs(sv_2mortal(newSVnv(errno)));
}
You'll also need to add the following code to the top of the .xs file, just
after the include of "XSUB.h":
#include <sys/vfs.h>
Also add the following code segment to Mytest.t while incrementing the "9"
tests to "11":
my @a;
@a = Mytest::statfs("/blech");
ok( scalar(@a) == 1 && $a[0] == 2 );
@a = Mytest::statfs("/");
is( scalar(@a), 7 );
=head2 New Things in this Example
This example added quite a few new concepts. We'll take them one at a time.
=over 4
=item *
The INIT: directive contains code that will be placed immediately after
the argument stack is decoded. C does not allow variable declarations at
arbitrary 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 C<PPCODE:> section into braces, and
put these declarations on top.)
=item *
This routine also returns a different number of arguments depending on the
success or failure of the call to statfs. If there is an error, the error
number 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 into
this function, we need room on the stack to hold the 7 values which may be
returned.
We do this by using the PPCODE: directive, rather than the CODE: directive.
This tells B<xsubpp> that we will be managing the return values that will be
put on the argument stack by ourselves.
=item *
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 five
different versions, for placing integers, unsigned integers, doubles,
strings, and Perl scalars on the stack. In our example, we placed a
Perl scalar onto the stack. (In fact this is the only macro which
can be used to return multiple values.)
The XPUSH* macros will automatically extend the return stack to prevent
it from being overrun. You push values onto the stack in the order you
want them seen by the calling program.
=item *
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 calling
program, the SV's that held the returned values can be deallocated.
If they were not mortal, then they would continue to exist after the XSUB
routine returned, but would not be accessible. This is a memory leak.
=item *
If we were interested in performance, not in code compactness, in the success
branch we would not use C<XPUSHs> macros, but C<PUSHs> macros, and would
pre-extend the stack before pushing the return values:
EXTEND(SP, 7);
The tradeoff is that one needs to calculate the number of return values
in advance (though overextending the stack will not typically hurt
anything but memory consumption).
Similarly, in the failure branch we could use C<PUSHs> I<without> extending
the stack: the Perl function reference comes to an XSUB on the stack, thus
the stack is I<always> large enough to take one return value.
=back
=head2 EXAMPLE 6
In this example, we will accept a reference to an array as an input
parameter, and return a reference to an array of hashes. This will
demonstrate manipulation of complex Perl data types from an XSUB.
This extension is somewhat contrived. It is based on the code in
the previous example. It calls the statfs function multiple times,
accepting a reference to an array of filenames as input, and returning
a reference to an array of hashes containing the data for each of the
filesystems.
Return to the Mytest directory and add the following code to the end of
Mytest.xs:
SV *
multi_statfs(paths)
SV * paths
lib/perlxstut.pod view on Meta::CPAN
AV * results;
SSize_t numpaths = 0, n;
int i;
struct statfs buf;
SvGETMAGIC(paths);
if ((!SvROK(paths))
|| (SvTYPE(SvRV(paths)) != SVt_PVAV)
|| ((numpaths = av_top_index((AV *)SvRV(paths))) < 0))
{
XSRETURN_UNDEF;
}
results = (AV *)sv_2mortal((SV *)newAV());
CODE:
for (n = 0; n <= numpaths; n++) {
HV * rh;
STRLEN l;
SV * path = *av_fetch((AV *)SvRV(paths), n, 0);
char * fn = SvPVbyte(path, l);
i = statfs(fn, &buf);
if (i != 0) {
av_push(results, newSVnv(errno));
continue;
}
rh = (HV *)sv_2mortal((SV *)newHV());
hv_store(rh, "f_bavail", 8, newSVnv(buf.f_bavail), 0);
hv_store(rh, "f_bfree", 7, newSVnv(buf.f_bfree), 0);
hv_store(rh, "f_blocks", 8, newSVnv(buf.f_blocks), 0);
hv_store(rh, "f_bsize", 7, newSVnv(buf.f_bsize), 0);
hv_store(rh, "f_ffree", 7, newSVnv(buf.f_ffree), 0);
hv_store(rh, "f_files", 7, newSVnv(buf.f_files), 0);
hv_store(rh, "f_type", 6, newSVnv(buf.f_type), 0);
av_push(results, newRV_inc((SV *)rh));
}
RETVAL = newRV_inc((SV *)results);
OUTPUT:
RETVAL
And add the following code to Mytest.t, while incrementing the "11"
tests to "13":
my $results = Mytest::multi_statfs([ '/', '/blech' ]);
ok( ref $results->[0] );
ok( ! ref $results->[1] );
=head2 New Things in this Example
There are a number of new concepts introduced here, described below:
=over 4
=item *
This function does not use a typemap. Instead, we declare it as accepting
one SV* (scalar) parameter, and returning an SV* value, and we take care of
populating these scalars within the code. Because we are only returning
one value, we don't need a C<PPCODE:> directive - instead, we use C<CODE:>
and C<OUTPUT:> directives.
=item *
When dealing with references, it is important to handle them with caution.
The C<INIT:> block first calls SvGETMAGIC(paths), in case
paths is a tied variable. Then it checks that C<SvROK> returns
true, which indicates that paths is a valid reference. (Simply
checking C<SvROK> won't trigger FETCH on a tied variable.) It
then verifies that the object referenced by paths is an array, using C<SvRV>
to dereference paths, and C<SvTYPE> to discover its type. As an added test,
it checks that the array referenced by paths is non-empty, using the
C<av_top_index> function (which returns -1 if the array is empty). The
XSRETURN_UNDEF macro is used to abort the XSUB and return the undefined value
whenever all three of these conditions are not met.
=item *
We manipulate several arrays in this XSUB. Note that an array is represented
internally by an AV* pointer. The functions and macros for manipulating
arrays are similar to the functions in Perl: C<av_top_index> returns the
highest index in an AV*, much like $#array; C<av_fetch> fetches a single scalar
value from an array, given its index; C<av_push> pushes a scalar value onto the
end of the array, automatically extending the array as necessary.
Specifically, we read pathnames one at a time from the input array, and
store the results in an output array (results) in the same order. If
statfs fails, the element pushed onto the return array is the value of
errno after the failure. If statfs succeeds, though, the value pushed
onto the return array is a reference to a hash containing some of the
information 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 know
how many elements we will return:
av_extend(results, numpaths);
=item *
We are performing only one hash operation in this function, which is storing
a new scalar under a key using C<hv_store>. A hash is represented by an HV*
pointer. Like arrays, the functions for manipulating hashes from an XSUB
mirror the functionality available from Perl. See L<perlguts> and L<perlapi>
for details.
=item *
To create a reference, we use the C<newRV_inc> function. Note that you can
cast an AV* or an HV* to type SV* in this case (and many others). This
allows you to take references to arrays, hashes and scalars with the same
function. Conversely, the C<SvRV> function always returns an SV*, which may
need to be cast to the appropriate type if it is something other than a
scalar (check with C<SvTYPE>).
=item *
At this point, xsubpp is doing very little work - the differences between
Mytest.xs and Mytest.c are minimal.
( run in 0.652 second using v1.01-cache-2.11-cpan-5511b514fd6 )