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 compiler is smart enough to figure out the C section from the first two lines of the description of XSUB. What about C section? In fact, that is absolutely the same! The C section can be removed as well, I section or C section> is not specified: B 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. As we saw in L, 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 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 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, etc). The second is the type of argument, and consists of the type declaration of the argument (e.g., int, char*, etc). The third piece is the 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 data of one of the "arguments", the actual argument of this C function would be a pointer to the data. Thus two C functions with declarations int string_length(char *s); int upper_case_char(char *cp); may have completely different semantics: the first one may inspect an array of chars pointed by s, and the second one may immediately dereference C and manipulate C<*cp> only (using the return value as, say, a success indicator). From Perl one would use these functions in a completely different manner. One conveys this info to B by replacing C<*> before the argument by C<&>. C<&> means that the argument should be passed to a library function by its address. The above two function may be XSUB-ified as int string_length(s) char * s int upper_case_char(cp) char &cp For example, consider: int foo(a,b) char &a char * b The first Perl argument to this function would be treated as a char and assigned to 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 the variable b. The I of b would be passed into the function foo. The actual call to the function foo that B generates would look like this: foo(&a, b); B will parse the following function argument lists identically: char &a char&a 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 the call to foo above). By doing so, it is easy to understand exactly what will be passed to the C function; it will be whatever is in the "last column". You should take great pains to try to pass the function the type of variable it wants, when possible. It will save you a lot of trouble in the long run. =head2 The Argument Stack If we look at any of the C code generated by any of the examples except example 1, you will notice a number of references to ST(n), where n is usually 0. "ST" is actually a macro that points to the n'th argument on the argument stack. ST(0) is thus the first argument on the stack and therefore the first argument passed to the XSUB, ST(1) is the second argument, and so on. When you list the arguments to the XSUB in the .xs file, that tells B which argument corresponds to which of the argument stack (i.e., the first one listed is the first argument, and so on). You invite disaster if you do not list them in the same order as the function expects them. The actual values on the argument stack are pointers to the values passed in. When an argument is listed as being an OUTPUT value, its corresponding value 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: double arg = (double)SvNV(ST(0)); /* Round the contents of the variable arg */ sv_setnv(ST(0), (double)arg); The arg variable is initially set by taking the value from ST(0), then is stored back into ST(0) at the end of the routine. XSUBs are also allowed to return lists, not just scalars. This must be done by manipulating stack values ST(0), ST(1), etc, in a subtly different way. See L for details. XSUBs are also allowed to avoid automatic conversion of Perl function arguments to C function arguments. See L for details. Some people prefer manual conversion by inspecting C even in the cases when automatic conversion will do, arguing that this makes the logic of an XSUB call clearer. Compare with L<"Getting the fat out of XSUBs"> for a similar tradeoff of a complete separation of "Perl glue" and "workhorse" parts of an XSUB. While experts may argue about these idioms, a novice to Perl guts may prefer a way which is as little Perl-guts-specific as possible, meaning automatic conversion and automatic call generation, as in L<"Getting the fat out of XSUBs">. This approach has the additional benefit of protecting the XSUB writer from future changes to the Perl API. =head2 Extending your Extension 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 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 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 Also add the following code segment to Mytest.t while incrementing the "9" tests to "11": @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 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 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 macros, but C 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 I extending the stack: the Perl function reference comes to an XSUB on the stack, thus the stack is I 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 INIT: 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; char * fn = SvPV(*av_fetch((AV *)SvRV(paths), n, 0), 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": $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 directive - instead, we use C and C directives. =item * When dealing with references, it is important to handle them with caution. The C block first calls SvGETMAGIC(paths), in case paths is a tied variable. Then it checks that C returns true, which indicates that paths is a valid reference. (Simply checking C won't trigger FETCH on a tied variable.) It then verifies that the object referenced by paths is an array, using C to dereference paths, and C to discover its type. As an added test, it checks that the array referenced by paths is non-empty, using the C 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 returns the highest index in an AV*, much like $#array; C fetches a single scalar value from an array, given its index; C 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. 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 and L for details. =item * To create a reference, we use the C 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 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). =item * At this point, xsubpp is doing very little work - the differences between Mytest.xs and Mytest.c are minimal. =back =head2 EXAMPLE 7 (Coming Soon) XPUSH args AND set RETVAL AND assign return value to array =head2 EXAMPLE 8 (Coming Soon) Setting $! =head2 EXAMPLE 9 Passing open files to XSes You would think passing files to an XS is difficult, with all the typeglobs and stuff. Well, it isn't. Suppose that for some strange reason we need a wrapper around the standard C library function C. This is all we need: #define PERLIO_NOT_STDIO 0 #define PERL_NO_GET_CONTEXT #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include int fputs(s, stream) char * s FILE * stream The real work is done in the standard typemap. B you lose all the fine stuff done by the perlio layers. This calls the stdio function C, which knows nothing about them. The standard typemap offers three variants of PerlIO *: C (T_IN), C (T_INOUT) and C (T_OUT). A bare C is considered a T_INOUT. If it matters in your code (see below for why it might) #define or typedef one of the specific names and use that as the argument or result type 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 * directly is not backwards compatible unless you provide your own typemap. For streams coming I perl the main difference is that C will get the output PerlIO * - which may make a difference on a socket. Like in our example... For streams being handed I 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 you may get errors or warnings from when the file handle is used. So if you opened the PerlIO * as "w" it should really be an C if open as "r" it should be an C. Now, suppose you want to use perlio layers in your XS. We'll use the perlio C function as an example. In the C part of the XS file (above the first MODULE line) you have #define OutputStream PerlIO * or typedef PerlIO * OutputStream; And this is the XS code: int perlioputs(s, stream) char * s OutputStream stream CODE: RETVAL = PerlIO_puts(stream, s); OUTPUT: RETVAL We have to use a C section because C has the arguments reversed compared to C, and we want to keep the arguments the same. Wanting to explore this thoroughly, we want to use the stdio C on a PerlIO *. This means we have to ask the perlio system for a stdio C: int perliofputs(s, stream) char * s OutputStream stream PREINIT: FILE *fp = PerlIO_findFILE(stream); CODE: if (fp != (FILE*) 0) { RETVAL = fputs(s, fp); } else { RETVAL = -1; } OUTPUT: RETVAL Note: C will search the layers for a stdio layer. If it can't find one, it will call C to generate a new stdio C. Please only call C if you want a I C. It will generate one on each call and push a new stdio layer. So don't call it repeatedly on the same file. C will retrieve the stdio layer once it has been generated by C. This applies to the perlio system only. For versions before 5.7, C is equivalent to C. =head2 Troubleshooting these Examples As mentioned at the top of this document, if you are having problems with these example extensions, you might see if any of these help you. =over 4 =item * In versions of 5.002 prior to the gamma version, the test script in Example 1 will not function properly. You need to change the "use lib" line to read: use lib './blib'; =item * In versions of 5.002 prior to version 5.002b1h, the test.pl file was not automatically 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: use lib './blib'; =item * In versions 5.000 and 5.001, instead of using the above line, you will need to use the following line: BEGIN { unshift(@INC, "./blib") } =item * This document assumes that the executable named "perl" is Perl version 5. Some systems may have installed Perl version 5 as "perl5". =back =head1 See also For more information, consult L, L, L, L, and L. =head1 Author Jeff Okamoto > Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig, and Tim Bunce. PerlIO material contributed by Lupe Christoph, with some clarification by Nick Ing-Simmons. Changes for h2xs as of Perl 5.8.x by Renee Baecker =head2 Last Changed 2012-01-20
section because C has the arguments reversed compared to C, and we want to keep the arguments the same. Wanting to explore this thoroughly, we want to use the stdio C on a PerlIO *. This means we have to ask the perlio system for a stdio C: int perliofputs(s, stream) char * s OutputStream stream PREINIT: FILE *fp = PerlIO_findFILE(stream); CODE: if (fp != (FILE*) 0) { RETVAL = fputs(s, fp); } else { RETVAL = -1; } OUTPUT: RETVAL Note: C will search the layers for a stdio layer. If it can't find one, it will call C to generate a new stdio C. Please only call C if you want a I C. It will generate one on each call and push a new stdio layer. So don't call it repeatedly on the same file. C will retrieve the stdio layer once it has been generated by C. This applies to the perlio system only. For versions before 5.7, C is equivalent to C. =head2 Troubleshooting these Examples As mentioned at the top of this document, if you are having problems with these example extensions, you might see if any of these help you. =over 4 =item * In versions of 5.002 prior to the gamma version, the test script in Example 1 will not function properly. You need to change the "use lib" line to read: use lib './blib'; =item * In versions of 5.002 prior to version 5.002b1h, the test.pl file was not automatically 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: use lib './blib'; =item * In versions 5.000 and 5.001, instead of using the above line, you will need to use the following line: BEGIN { unshift(@INC, "./blib") } =item * This document assumes that the executable named "perl" is Perl version 5. Some systems may have installed Perl version 5 as "perl5". =back =head1 See also For more information, consult L, L, L, L, and L. =head1 Author Jeff Okamoto > Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig, and Tim Bunce. PerlIO material contributed by Lupe Christoph, with some clarification by Nick Ing-Simmons. Changes for h2xs as of Perl 5.8.x by Renee Baecker =head2 Last Changed 2012-01-20