xref: /onnv-gate/usr/src/cmd/perl/5.8.4/distrib/pod/perlxstut.pod (revision 0:68f95e015346)
1*0Sstevel@tonic-gate=head1 NAME
2*0Sstevel@tonic-gate
3*0Sstevel@tonic-gateperlXStut - Tutorial for writing XSUBs
4*0Sstevel@tonic-gate
5*0Sstevel@tonic-gate=head1 DESCRIPTION
6*0Sstevel@tonic-gate
7*0Sstevel@tonic-gateThis tutorial will educate the reader on the steps involved in creating
8*0Sstevel@tonic-gatea Perl extension.  The reader is assumed to have access to L<perlguts>,
9*0Sstevel@tonic-gateL<perlapi> and L<perlxs>.
10*0Sstevel@tonic-gate
11*0Sstevel@tonic-gateThis tutorial starts with very simple examples and becomes more complex,
12*0Sstevel@tonic-gatewith each new example adding new features.  Certain concepts may not be
13*0Sstevel@tonic-gatecompletely explained until later in the tutorial in order to slowly ease
14*0Sstevel@tonic-gatethe reader into building extensions.
15*0Sstevel@tonic-gate
16*0Sstevel@tonic-gateThis tutorial was written from a Unix point of view.  Where I know them
17*0Sstevel@tonic-gateto be otherwise different for other platforms (e.g. Win32), I will list
18*0Sstevel@tonic-gatethem.  If you find something that was missed, please let me know.
19*0Sstevel@tonic-gate
20*0Sstevel@tonic-gate=head1 SPECIAL NOTES
21*0Sstevel@tonic-gate
22*0Sstevel@tonic-gate=head2 make
23*0Sstevel@tonic-gate
24*0Sstevel@tonic-gateThis tutorial assumes that the make program that Perl is configured to
25*0Sstevel@tonic-gateuse is called C<make>.  Instead of running "make" in the examples that
26*0Sstevel@tonic-gatefollow, you may have to substitute whatever make program Perl has been
27*0Sstevel@tonic-gateconfigured to use.  Running B<perl -V:make> should tell you what it is.
28*0Sstevel@tonic-gate
29*0Sstevel@tonic-gate=head2 Version caveat
30*0Sstevel@tonic-gate
31*0Sstevel@tonic-gateWhen writing a Perl extension for general consumption, one should expect that
32*0Sstevel@tonic-gatethe extension will be used with versions of Perl different from the
33*0Sstevel@tonic-gateversion available on your machine.  Since you are reading this document,
34*0Sstevel@tonic-gatethe version of Perl on your machine is probably 5.005 or later, but the users
35*0Sstevel@tonic-gateof your extension may have more ancient versions.
36*0Sstevel@tonic-gate
37*0Sstevel@tonic-gateTo understand what kinds of incompatibilities one may expect, and in the rare
38*0Sstevel@tonic-gatecase that the version of Perl on your machine is older than this document,
39*0Sstevel@tonic-gatesee the section on "Troubleshooting these Examples" for more information.
40*0Sstevel@tonic-gate
41*0Sstevel@tonic-gateIf your extension uses some features of Perl which are not available on older
42*0Sstevel@tonic-gatereleases of Perl, your users would appreciate an early meaningful warning.
43*0Sstevel@tonic-gateYou would probably put this information into the F<README> file, but nowadays
44*0Sstevel@tonic-gateinstallation of extensions may be performed automatically, guided by F<CPAN.pm>
45*0Sstevel@tonic-gatemodule or other tools.
46*0Sstevel@tonic-gate
47*0Sstevel@tonic-gateIn MakeMaker-based installations, F<Makefile.PL> provides the earliest
48*0Sstevel@tonic-gateopportunity to perform version checks.  One can put something like this
49*0Sstevel@tonic-gatein F<Makefile.PL> for this purpose:
50*0Sstevel@tonic-gate
51*0Sstevel@tonic-gate    eval { require 5.007 }
52*0Sstevel@tonic-gate        or die <<EOD;
53*0Sstevel@tonic-gate    ############
54*0Sstevel@tonic-gate    ### This module uses frobnication framework which is not available before
55*0Sstevel@tonic-gate    ### version 5.007 of Perl.  Upgrade your Perl before installing Kara::Mba.
56*0Sstevel@tonic-gate    ############
57*0Sstevel@tonic-gate    EOD
58*0Sstevel@tonic-gate
59*0Sstevel@tonic-gate=head2 Dynamic Loading versus Static Loading
60*0Sstevel@tonic-gate
61*0Sstevel@tonic-gateIt is commonly thought that if a system does not have the capability to
62*0Sstevel@tonic-gatedynamically load a library, you cannot build XSUBs.  This is incorrect.
63*0Sstevel@tonic-gateYou I<can> build them, but you must link the XSUBs subroutines with the
64*0Sstevel@tonic-gaterest of Perl, creating a new executable.  This situation is similar to
65*0Sstevel@tonic-gatePerl 4.
66*0Sstevel@tonic-gate
67*0Sstevel@tonic-gateThis tutorial can still be used on such a system.  The XSUB build mechanism
68*0Sstevel@tonic-gatewill check the system and build a dynamically-loadable library if possible,
69*0Sstevel@tonic-gateor else a static library and then, optionally, a new statically-linked
70*0Sstevel@tonic-gateexecutable with that static library linked in.
71*0Sstevel@tonic-gate
72*0Sstevel@tonic-gateShould you wish to build a statically-linked executable on a system which
73*0Sstevel@tonic-gatecan dynamically load libraries, you may, in all the following examples,
74*0Sstevel@tonic-gatewhere the command "C<make>" with no arguments is executed, run the command
75*0Sstevel@tonic-gate"C<make perl>" instead.
76*0Sstevel@tonic-gate
77*0Sstevel@tonic-gateIf you have generated such a statically-linked executable by choice, then
78*0Sstevel@tonic-gateinstead of saying "C<make test>", you should say "C<make test_static>".
79*0Sstevel@tonic-gateOn systems that cannot build dynamically-loadable libraries at all, simply
80*0Sstevel@tonic-gatesaying "C<make test>" is sufficient.
81*0Sstevel@tonic-gate
82*0Sstevel@tonic-gate=head1 TUTORIAL
83*0Sstevel@tonic-gate
84*0Sstevel@tonic-gateNow let's go on with the show!
85*0Sstevel@tonic-gate
86*0Sstevel@tonic-gate=head2 EXAMPLE 1
87*0Sstevel@tonic-gate
88*0Sstevel@tonic-gateOur first extension will be very simple.  When we call the routine in the
89*0Sstevel@tonic-gateextension, it will print out a well-known message and return.
90*0Sstevel@tonic-gate
91*0Sstevel@tonic-gateRun "C<h2xs -A -n Mytest>".  This creates a directory named Mytest,
92*0Sstevel@tonic-gatepossibly under ext/ if that directory exists in the current working
93*0Sstevel@tonic-gatedirectory.  Several files will be created in the Mytest dir, including
94*0Sstevel@tonic-gateMANIFEST, Makefile.PL, Mytest.pm, Mytest.xs, test.pl, and Changes.
95*0Sstevel@tonic-gate
96*0Sstevel@tonic-gateThe MANIFEST file contains the names of all the files just created in the
97*0Sstevel@tonic-gateMytest directory.
98*0Sstevel@tonic-gate
99*0Sstevel@tonic-gateThe file Makefile.PL should look something like this:
100*0Sstevel@tonic-gate
101*0Sstevel@tonic-gate	use ExtUtils::MakeMaker;
102*0Sstevel@tonic-gate	# See lib/ExtUtils/MakeMaker.pm for details of how to influence
103*0Sstevel@tonic-gate	# the contents of the Makefile that is written.
104*0Sstevel@tonic-gate	WriteMakefile(
105*0Sstevel@tonic-gate	    NAME         => 'Mytest',
106*0Sstevel@tonic-gate	    VERSION_FROM => 'Mytest.pm', # finds $VERSION
107*0Sstevel@tonic-gate	    LIBS         => [''],   # e.g., '-lm'
108*0Sstevel@tonic-gate	    DEFINE       => '',     # e.g., '-DHAVE_SOMETHING'
109*0Sstevel@tonic-gate	    INC          => '',     # e.g., '-I/usr/include/other'
110*0Sstevel@tonic-gate	);
111*0Sstevel@tonic-gate
112*0Sstevel@tonic-gateThe file Mytest.pm should start with something like this:
113*0Sstevel@tonic-gate
114*0Sstevel@tonic-gate	package Mytest;
115*0Sstevel@tonic-gate
116*0Sstevel@tonic-gate	use strict;
117*0Sstevel@tonic-gate        use warnings;
118*0Sstevel@tonic-gate
119*0Sstevel@tonic-gate	require Exporter;
120*0Sstevel@tonic-gate	require DynaLoader;
121*0Sstevel@tonic-gate
122*0Sstevel@tonic-gate	our @ISA = qw(Exporter DynaLoader);
123*0Sstevel@tonic-gate	# Items to export into callers namespace by default. Note: do not export
124*0Sstevel@tonic-gate	# names by default without a very good reason. Use EXPORT_OK instead.
125*0Sstevel@tonic-gate	# Do not simply export all your public functions/methods/constants.
126*0Sstevel@tonic-gate	our @EXPORT = qw(
127*0Sstevel@tonic-gate
128*0Sstevel@tonic-gate	);
129*0Sstevel@tonic-gate	our $VERSION = '0.01';
130*0Sstevel@tonic-gate
131*0Sstevel@tonic-gate	bootstrap Mytest $VERSION;
132*0Sstevel@tonic-gate
133*0Sstevel@tonic-gate	# Preloaded methods go here.
134*0Sstevel@tonic-gate
135*0Sstevel@tonic-gate	# Autoload methods go after __END__, and are processed by the autosplit program.
136*0Sstevel@tonic-gate
137*0Sstevel@tonic-gate	1;
138*0Sstevel@tonic-gate	__END__
139*0Sstevel@tonic-gate	# Below is the stub of documentation for your module. You better edit it!
140*0Sstevel@tonic-gate
141*0Sstevel@tonic-gateThe rest of the .pm file contains sample code for providing documentation for
142*0Sstevel@tonic-gatethe extension.
143*0Sstevel@tonic-gate
144*0Sstevel@tonic-gateFinally, the Mytest.xs file should look something like this:
145*0Sstevel@tonic-gate
146*0Sstevel@tonic-gate	#include "EXTERN.h"
147*0Sstevel@tonic-gate	#include "perl.h"
148*0Sstevel@tonic-gate	#include "XSUB.h"
149*0Sstevel@tonic-gate
150*0Sstevel@tonic-gate	MODULE = Mytest		PACKAGE = Mytest
151*0Sstevel@tonic-gate
152*0Sstevel@tonic-gateLet's edit the .xs file by adding this to the end of the file:
153*0Sstevel@tonic-gate
154*0Sstevel@tonic-gate	void
155*0Sstevel@tonic-gate	hello()
156*0Sstevel@tonic-gate	    CODE:
157*0Sstevel@tonic-gate		printf("Hello, world!\n");
158*0Sstevel@tonic-gate
159*0Sstevel@tonic-gateIt is okay for the lines starting at the "CODE:" line to not be indented.
160*0Sstevel@tonic-gateHowever, for readability purposes, it is suggested that you indent CODE:
161*0Sstevel@tonic-gateone level and the lines following one more level.
162*0Sstevel@tonic-gate
163*0Sstevel@tonic-gateNow we'll run "C<perl Makefile.PL>".  This will create a real Makefile,
164*0Sstevel@tonic-gatewhich make needs.  Its output looks something like:
165*0Sstevel@tonic-gate
166*0Sstevel@tonic-gate	% perl Makefile.PL
167*0Sstevel@tonic-gate	Checking if your kit is complete...
168*0Sstevel@tonic-gate	Looks good
169*0Sstevel@tonic-gate	Writing Makefile for Mytest
170*0Sstevel@tonic-gate	%
171*0Sstevel@tonic-gate
172*0Sstevel@tonic-gateNow, running make will produce output that looks something like this (some
173*0Sstevel@tonic-gatelong lines have been shortened for clarity and some extraneous lines have
174*0Sstevel@tonic-gatebeen deleted):
175*0Sstevel@tonic-gate
176*0Sstevel@tonic-gate	% make
177*0Sstevel@tonic-gate	umask 0 && cp Mytest.pm ./blib/Mytest.pm
178*0Sstevel@tonic-gate	perl xsubpp -typemap typemap Mytest.xs >Mytest.tc && mv Mytest.tc Mytest.c
179*0Sstevel@tonic-gate	Please specify prototyping behavior for Mytest.xs (see perlxs manual)
180*0Sstevel@tonic-gate	cc -c Mytest.c
181*0Sstevel@tonic-gate	Running Mkbootstrap for Mytest ()
182*0Sstevel@tonic-gate	chmod 644 Mytest.bs
183*0Sstevel@tonic-gate	LD_RUN_PATH="" ld -o ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl -b Mytest.o
184*0Sstevel@tonic-gate	chmod 755 ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl
185*0Sstevel@tonic-gate	cp Mytest.bs ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
186*0Sstevel@tonic-gate	chmod 644 ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
187*0Sstevel@tonic-gate	Manifying ./blib/man3/Mytest.3
188*0Sstevel@tonic-gate	%
189*0Sstevel@tonic-gate
190*0Sstevel@tonic-gateYou can safely ignore the line about "prototyping behavior" - it is
191*0Sstevel@tonic-gateexplained in the section "The PROTOTYPES: Keyword" in L<perlxs>.
192*0Sstevel@tonic-gate
193*0Sstevel@tonic-gateIf you are on a Win32 system, and the build process fails with linker
194*0Sstevel@tonic-gateerrors for functions in the C library, check if your Perl is configured
195*0Sstevel@tonic-gateto use PerlCRT (running B<perl -V:libc> should show you if this is the
196*0Sstevel@tonic-gatecase).  If Perl is configured to use PerlCRT, you have to make sure
197*0Sstevel@tonic-gatePerlCRT.lib is copied to the same location that msvcrt.lib lives in,
198*0Sstevel@tonic-gateso that the compiler can find it on its own.  msvcrt.lib is usually
199*0Sstevel@tonic-gatefound in the Visual C compiler's lib directory (e.g. C:/DevStudio/VC/lib).
200*0Sstevel@tonic-gate
201*0Sstevel@tonic-gatePerl has its own special way of easily writing test scripts, but for this
202*0Sstevel@tonic-gateexample only, we'll create our own test script.  Create a file called hello
203*0Sstevel@tonic-gatethat looks like this:
204*0Sstevel@tonic-gate
205*0Sstevel@tonic-gate	#! /opt/perl5/bin/perl
206*0Sstevel@tonic-gate
207*0Sstevel@tonic-gate	use ExtUtils::testlib;
208*0Sstevel@tonic-gate
209*0Sstevel@tonic-gate	use Mytest;
210*0Sstevel@tonic-gate
211*0Sstevel@tonic-gate	Mytest::hello();
212*0Sstevel@tonic-gate
213*0Sstevel@tonic-gateNow we make the script executable (C<chmod +x hello>), run the script
214*0Sstevel@tonic-gateand we should see the following output:
215*0Sstevel@tonic-gate
216*0Sstevel@tonic-gate	% ./hello
217*0Sstevel@tonic-gate	Hello, world!
218*0Sstevel@tonic-gate	%
219*0Sstevel@tonic-gate
220*0Sstevel@tonic-gate=head2 EXAMPLE 2
221*0Sstevel@tonic-gate
222*0Sstevel@tonic-gateNow let's add to our extension a subroutine that will take a single numeric
223*0Sstevel@tonic-gateargument as input and return 0 if the number is even or 1 if the number
224*0Sstevel@tonic-gateis odd.
225*0Sstevel@tonic-gate
226*0Sstevel@tonic-gateAdd the following to the end of Mytest.xs:
227*0Sstevel@tonic-gate
228*0Sstevel@tonic-gate	int
229*0Sstevel@tonic-gate	is_even(input)
230*0Sstevel@tonic-gate		int	input
231*0Sstevel@tonic-gate	    CODE:
232*0Sstevel@tonic-gate		RETVAL = (input % 2 == 0);
233*0Sstevel@tonic-gate	    OUTPUT:
234*0Sstevel@tonic-gate		RETVAL
235*0Sstevel@tonic-gate
236*0Sstevel@tonic-gateThere does not need to be white space at the start of the "C<int input>"
237*0Sstevel@tonic-gateline, but it is useful for improving readability.  Placing a semi-colon at
238*0Sstevel@tonic-gatethe end of that line is also optional.  Any amount and kind of white space
239*0Sstevel@tonic-gatemay be placed between the "C<int>" and "C<input>".
240*0Sstevel@tonic-gate
241*0Sstevel@tonic-gateNow re-run make to rebuild our new shared library.
242*0Sstevel@tonic-gate
243*0Sstevel@tonic-gateNow perform the same steps as before, generating a Makefile from the
244*0Sstevel@tonic-gateMakefile.PL file, and running make.
245*0Sstevel@tonic-gate
246*0Sstevel@tonic-gateIn order to test that our extension works, we now need to look at the
247*0Sstevel@tonic-gatefile test.pl.  This file is set up to imitate the same kind of testing
248*0Sstevel@tonic-gatestructure that Perl itself has.  Within the test script, you perform a
249*0Sstevel@tonic-gatenumber of tests to confirm the behavior of the extension, printing "ok"
250*0Sstevel@tonic-gatewhen the test is correct, "not ok" when it is not.  Change the print
251*0Sstevel@tonic-gatestatement in the BEGIN block to print "1..4", and add the following code
252*0Sstevel@tonic-gateto the end of the file:
253*0Sstevel@tonic-gate
254*0Sstevel@tonic-gate	print &Mytest::is_even(0) == 1 ? "ok 2" : "not ok 2", "\n";
255*0Sstevel@tonic-gate	print &Mytest::is_even(1) == 0 ? "ok 3" : "not ok 3", "\n";
256*0Sstevel@tonic-gate	print &Mytest::is_even(2) == 1 ? "ok 4" : "not ok 4", "\n";
257*0Sstevel@tonic-gate
258*0Sstevel@tonic-gateWe will be calling the test script through the command "C<make test>".  You
259*0Sstevel@tonic-gateshould see output that looks something like this:
260*0Sstevel@tonic-gate
261*0Sstevel@tonic-gate	% make test
262*0Sstevel@tonic-gate	PERL_DL_NONLAZY=1 /opt/perl5.004/bin/perl (lots of -I arguments) test.pl
263*0Sstevel@tonic-gate	1..4
264*0Sstevel@tonic-gate	ok 1
265*0Sstevel@tonic-gate	ok 2
266*0Sstevel@tonic-gate	ok 3
267*0Sstevel@tonic-gate	ok 4
268*0Sstevel@tonic-gate	%
269*0Sstevel@tonic-gate
270*0Sstevel@tonic-gate=head2 What has gone on?
271*0Sstevel@tonic-gate
272*0Sstevel@tonic-gateThe program h2xs is the starting point for creating extensions.  In later
273*0Sstevel@tonic-gateexamples we'll see how we can use h2xs to read header files and generate
274*0Sstevel@tonic-gatetemplates to connect to C routines.
275*0Sstevel@tonic-gate
276*0Sstevel@tonic-gateh2xs creates a number of files in the extension directory.  The file
277*0Sstevel@tonic-gateMakefile.PL is a perl script which will generate a true Makefile to build
278*0Sstevel@tonic-gatethe extension.  We'll take a closer look at it later.
279*0Sstevel@tonic-gate
280*0Sstevel@tonic-gateThe .pm and .xs files contain the meat of the extension.  The .xs file holds
281*0Sstevel@tonic-gatethe C routines that make up the extension.  The .pm file contains routines
282*0Sstevel@tonic-gatethat tell Perl how to load your extension.
283*0Sstevel@tonic-gate
284*0Sstevel@tonic-gateGenerating the Makefile and running C<make> created a directory called blib
285*0Sstevel@tonic-gate(which stands for "build library") in the current working directory.  This
286*0Sstevel@tonic-gatedirectory will contain the shared library that we will build.  Once we have
287*0Sstevel@tonic-gatetested it, we can install it into its final location.
288*0Sstevel@tonic-gate
289*0Sstevel@tonic-gateInvoking the test script via "C<make test>" did something very important.
290*0Sstevel@tonic-gateIt invoked perl with all those C<-I> arguments so that it could find the
291*0Sstevel@tonic-gatevarious files that are part of the extension.  It is I<very> important that
292*0Sstevel@tonic-gatewhile you are still testing extensions that you use "C<make test>".  If you
293*0Sstevel@tonic-gatetry to run the test script all by itself, you will get a fatal error.
294*0Sstevel@tonic-gateAnother reason it is important to use "C<make test>" to run your test
295*0Sstevel@tonic-gatescript is that if you are testing an upgrade to an already-existing version,
296*0Sstevel@tonic-gateusing "C<make test>" insures that you will test your new extension, not the
297*0Sstevel@tonic-gatealready-existing version.
298*0Sstevel@tonic-gate
299*0Sstevel@tonic-gateWhen Perl sees a C<use extension;>, it searches for a file with the same name
300*0Sstevel@tonic-gateas the C<use>'d extension that has a .pm suffix.  If that file cannot be found,
301*0Sstevel@tonic-gatePerl dies with a fatal error.  The default search path is contained in the
302*0Sstevel@tonic-gateC<@INC> array.
303*0Sstevel@tonic-gate
304*0Sstevel@tonic-gateIn our case, Mytest.pm tells perl that it will need the Exporter and Dynamic
305*0Sstevel@tonic-gateLoader extensions.  It then sets the C<@ISA> and C<@EXPORT> arrays and the
306*0Sstevel@tonic-gateC<$VERSION> scalar; finally it tells perl to bootstrap the module.  Perl
307*0Sstevel@tonic-gatewill call its dynamic loader routine (if there is one) and load the shared
308*0Sstevel@tonic-gatelibrary.
309*0Sstevel@tonic-gate
310*0Sstevel@tonic-gateThe two arrays C<@ISA> and C<@EXPORT> are very important.  The C<@ISA>
311*0Sstevel@tonic-gatearray contains a list of other packages in which to search for methods (or
312*0Sstevel@tonic-gatesubroutines) that do not exist in the current package.  This is usually
313*0Sstevel@tonic-gateonly important for object-oriented extensions (which we will talk about
314*0Sstevel@tonic-gatemuch later), and so usually doesn't need to be modified.
315*0Sstevel@tonic-gate
316*0Sstevel@tonic-gateThe C<@EXPORT> array tells Perl which of the extension's variables and
317*0Sstevel@tonic-gatesubroutines should be placed into the calling package's namespace.  Because
318*0Sstevel@tonic-gateyou don't know if the user has already used your variable and subroutine
319*0Sstevel@tonic-gatenames, it's vitally important to carefully select what to export.  Do I<not>
320*0Sstevel@tonic-gateexport method or variable names I<by default> without a good reason.
321*0Sstevel@tonic-gate
322*0Sstevel@tonic-gateAs a general rule, if the module is trying to be object-oriented then don't
323*0Sstevel@tonic-gateexport anything.  If it's just a collection of functions and variables, then
324*0Sstevel@tonic-gateyou can export them via another array, called C<@EXPORT_OK>.  This array
325*0Sstevel@tonic-gatedoes not automatically place its subroutine and variable names into the
326*0Sstevel@tonic-gatenamespace unless the user specifically requests that this be done.
327*0Sstevel@tonic-gate
328*0Sstevel@tonic-gateSee L<perlmod> for more information.
329*0Sstevel@tonic-gate
330*0Sstevel@tonic-gateThe C<$VERSION> variable is used to ensure that the .pm file and the shared
331*0Sstevel@tonic-gatelibrary are "in sync" with each other.  Any time you make changes to
332*0Sstevel@tonic-gatethe .pm or .xs files, you should increment the value of this variable.
333*0Sstevel@tonic-gate
334*0Sstevel@tonic-gate=head2 Writing good test scripts
335*0Sstevel@tonic-gate
336*0Sstevel@tonic-gateThe importance of writing good test scripts cannot be overemphasized.  You
337*0Sstevel@tonic-gateshould closely follow the "ok/not ok" style that Perl itself uses, so that
338*0Sstevel@tonic-gateit is very easy and unambiguous to determine the outcome of each test case.
339*0Sstevel@tonic-gateWhen you find and fix a bug, make sure you add a test case for it.
340*0Sstevel@tonic-gate
341*0Sstevel@tonic-gateBy running "C<make test>", you ensure that your test.pl script runs and uses
342*0Sstevel@tonic-gatethe correct version of your extension.  If you have many test cases, you
343*0Sstevel@tonic-gatemight want to copy Perl's test style.  Create a directory named "t" in the
344*0Sstevel@tonic-gateextension's directory and append the suffix ".t" to the names of your test
345*0Sstevel@tonic-gatefiles.  When you run "C<make test>", all of these test files will be executed.
346*0Sstevel@tonic-gate
347*0Sstevel@tonic-gate=head2 EXAMPLE 3
348*0Sstevel@tonic-gate
349*0Sstevel@tonic-gateOur third extension will take one argument as its input, round off that
350*0Sstevel@tonic-gatevalue, and set the I<argument> to the rounded value.
351*0Sstevel@tonic-gate
352*0Sstevel@tonic-gateAdd the following to the end of Mytest.xs:
353*0Sstevel@tonic-gate
354*0Sstevel@tonic-gate	void
355*0Sstevel@tonic-gate	round(arg)
356*0Sstevel@tonic-gate		double  arg
357*0Sstevel@tonic-gate	    CODE:
358*0Sstevel@tonic-gate		if (arg > 0.0) {
359*0Sstevel@tonic-gate			arg = floor(arg + 0.5);
360*0Sstevel@tonic-gate		} else if (arg < 0.0) {
361*0Sstevel@tonic-gate			arg = ceil(arg - 0.5);
362*0Sstevel@tonic-gate		} else {
363*0Sstevel@tonic-gate			arg = 0.0;
364*0Sstevel@tonic-gate		}
365*0Sstevel@tonic-gate	    OUTPUT:
366*0Sstevel@tonic-gate		arg
367*0Sstevel@tonic-gate
368*0Sstevel@tonic-gateEdit the Makefile.PL file so that the corresponding line looks like this:
369*0Sstevel@tonic-gate
370*0Sstevel@tonic-gate	'LIBS'      => ['-lm'],   # e.g., '-lm'
371*0Sstevel@tonic-gate
372*0Sstevel@tonic-gateGenerate the Makefile and run make.  Change the BEGIN block to print
373*0Sstevel@tonic-gate"1..9" and add the following to test.pl:
374*0Sstevel@tonic-gate
375*0Sstevel@tonic-gate	$i = -1.5; &Mytest::round($i); print $i == -2.0 ? "ok 5" : "not ok 5", "\n";
376*0Sstevel@tonic-gate	$i = -1.1; &Mytest::round($i); print $i == -1.0 ? "ok 6" : "not ok 6", "\n";
377*0Sstevel@tonic-gate	$i = 0.0; &Mytest::round($i); print $i == 0.0 ? "ok 7" : "not ok 7", "\n";
378*0Sstevel@tonic-gate	$i = 0.5; &Mytest::round($i); print $i == 1.0 ? "ok 8" : "not ok 8", "\n";
379*0Sstevel@tonic-gate	$i = 1.2; &Mytest::round($i); print $i == 1.0 ? "ok 9" : "not ok 9", "\n";
380*0Sstevel@tonic-gate
381*0Sstevel@tonic-gateRunning "C<make test>" should now print out that all nine tests are okay.
382*0Sstevel@tonic-gate
383*0Sstevel@tonic-gateNotice that in these new test cases, the argument passed to round was a
384*0Sstevel@tonic-gatescalar variable.  You might be wondering if you can round a constant or
385*0Sstevel@tonic-gateliteral.  To see what happens, temporarily add the following line to test.pl:
386*0Sstevel@tonic-gate
387*0Sstevel@tonic-gate	&Mytest::round(3);
388*0Sstevel@tonic-gate
389*0Sstevel@tonic-gateRun "C<make test>" and notice that Perl dies with a fatal error.  Perl won't
390*0Sstevel@tonic-gatelet you change the value of constants!
391*0Sstevel@tonic-gate
392*0Sstevel@tonic-gate=head2 What's new here?
393*0Sstevel@tonic-gate
394*0Sstevel@tonic-gate=over 4
395*0Sstevel@tonic-gate
396*0Sstevel@tonic-gate=item *
397*0Sstevel@tonic-gate
398*0Sstevel@tonic-gateWe've made some changes to Makefile.PL.  In this case, we've specified an
399*0Sstevel@tonic-gateextra library to be linked into the extension's shared library, the math
400*0Sstevel@tonic-gatelibrary libm in this case.  We'll talk later about how to write XSUBs that
401*0Sstevel@tonic-gatecan call every routine in a library.
402*0Sstevel@tonic-gate
403*0Sstevel@tonic-gate=item *
404*0Sstevel@tonic-gate
405*0Sstevel@tonic-gateThe value of the function is not being passed back as the function's return
406*0Sstevel@tonic-gatevalue, but by changing the value of the variable that was passed into the
407*0Sstevel@tonic-gatefunction.  You might have guessed that when you saw that the return value
408*0Sstevel@tonic-gateof round is of type "void".
409*0Sstevel@tonic-gate
410*0Sstevel@tonic-gate=back
411*0Sstevel@tonic-gate
412*0Sstevel@tonic-gate=head2 Input and Output Parameters
413*0Sstevel@tonic-gate
414*0Sstevel@tonic-gateYou specify the parameters that will be passed into the XSUB on the line(s)
415*0Sstevel@tonic-gateafter you declare the function's return value and name.  Each input parameter
416*0Sstevel@tonic-gateline starts with optional white space, and may have an optional terminating
417*0Sstevel@tonic-gatesemicolon.
418*0Sstevel@tonic-gate
419*0Sstevel@tonic-gateThe list of output parameters occurs at the very end of the function, just
420*0Sstevel@tonic-gatebefore after the OUTPUT: directive.  The use of RETVAL tells Perl that you
421*0Sstevel@tonic-gatewish to send this value back as the return value of the XSUB function.  In
422*0Sstevel@tonic-gateExample 3, we wanted the "return value" placed in the original variable
423*0Sstevel@tonic-gatewhich we passed in, so we listed it (and not RETVAL) in the OUTPUT: section.
424*0Sstevel@tonic-gate
425*0Sstevel@tonic-gate=head2 The XSUBPP Program
426*0Sstevel@tonic-gate
427*0Sstevel@tonic-gateThe B<xsubpp> program takes the XS code in the .xs file and translates it into
428*0Sstevel@tonic-gateC code, placing it in a file whose suffix is .c.  The C code created makes
429*0Sstevel@tonic-gateheavy use of the C functions within Perl.
430*0Sstevel@tonic-gate
431*0Sstevel@tonic-gate=head2 The TYPEMAP file
432*0Sstevel@tonic-gate
433*0Sstevel@tonic-gateThe B<xsubpp> program uses rules to convert from Perl's data types (scalar,
434*0Sstevel@tonic-gatearray, etc.) to C's data types (int, char, etc.).  These rules are stored
435*0Sstevel@tonic-gatein the typemap file ($PERLLIB/ExtUtils/typemap).  This file is split into
436*0Sstevel@tonic-gatethree parts.
437*0Sstevel@tonic-gate
438*0Sstevel@tonic-gateThe first section maps various C data types to a name, which corresponds
439*0Sstevel@tonic-gatesomewhat with the various Perl types.  The second section contains C code
440*0Sstevel@tonic-gatewhich B<xsubpp> uses to handle input parameters.  The third section contains
441*0Sstevel@tonic-gateC code which B<xsubpp> uses to handle output parameters.
442*0Sstevel@tonic-gate
443*0Sstevel@tonic-gateLet's take a look at a portion of the .c file created for our extension.
444*0Sstevel@tonic-gateThe file name is Mytest.c:
445*0Sstevel@tonic-gate
446*0Sstevel@tonic-gate	XS(XS_Mytest_round)
447*0Sstevel@tonic-gate	{
448*0Sstevel@tonic-gate	    dXSARGS;
449*0Sstevel@tonic-gate	    if (items != 1)
450*0Sstevel@tonic-gate		croak("Usage: Mytest::round(arg)");
451*0Sstevel@tonic-gate	    {
452*0Sstevel@tonic-gate		double  arg = (double)SvNV(ST(0));	/* XXXXX */
453*0Sstevel@tonic-gate		if (arg > 0.0) {
454*0Sstevel@tonic-gate			arg = floor(arg + 0.5);
455*0Sstevel@tonic-gate		} else if (arg < 0.0) {
456*0Sstevel@tonic-gate			arg = ceil(arg - 0.5);
457*0Sstevel@tonic-gate		} else {
458*0Sstevel@tonic-gate			arg = 0.0;
459*0Sstevel@tonic-gate		}
460*0Sstevel@tonic-gate		sv_setnv(ST(0), (double)arg);	/* XXXXX */
461*0Sstevel@tonic-gate	    }
462*0Sstevel@tonic-gate	    XSRETURN(1);
463*0Sstevel@tonic-gate	}
464*0Sstevel@tonic-gate
465*0Sstevel@tonic-gateNotice the two lines commented with "XXXXX".  If you check the first section
466*0Sstevel@tonic-gateof the typemap file, you'll see that doubles are of type T_DOUBLE.  In the
467*0Sstevel@tonic-gateINPUT section, an argument that is T_DOUBLE is assigned to the variable
468*0Sstevel@tonic-gatearg by calling the routine SvNV on something, then casting it to double,
469*0Sstevel@tonic-gatethen assigned to the variable arg.  Similarly, in the OUTPUT section,
470*0Sstevel@tonic-gateonce arg has its final value, it is passed to the sv_setnv function to
471*0Sstevel@tonic-gatebe passed back to the calling subroutine.  These two functions are explained
472*0Sstevel@tonic-gatein L<perlguts>; we'll talk more later about what that "ST(0)" means in the
473*0Sstevel@tonic-gatesection on the argument stack.
474*0Sstevel@tonic-gate
475*0Sstevel@tonic-gate=head2 Warning about Output Arguments
476*0Sstevel@tonic-gate
477*0Sstevel@tonic-gateIn general, it's not a good idea to write extensions that modify their input
478*0Sstevel@tonic-gateparameters, as in Example 3.  Instead, you should probably return multiple
479*0Sstevel@tonic-gatevalues in an array and let the caller handle them (we'll do this in a later
480*0Sstevel@tonic-gateexample).  However, in order to better accommodate calling pre-existing C
481*0Sstevel@tonic-gateroutines, which often do modify their input parameters, this behavior is
482*0Sstevel@tonic-gatetolerated.
483*0Sstevel@tonic-gate
484*0Sstevel@tonic-gate=head2 EXAMPLE 4
485*0Sstevel@tonic-gate
486*0Sstevel@tonic-gateIn this example, we'll now begin to write XSUBs that will interact with
487*0Sstevel@tonic-gatepre-defined C libraries.  To begin with, we will build a small library of
488*0Sstevel@tonic-gateour own, then let h2xs write our .pm and .xs files for us.
489*0Sstevel@tonic-gate
490*0Sstevel@tonic-gateCreate a new directory called Mytest2 at the same level as the directory
491*0Sstevel@tonic-gateMytest.  In the Mytest2 directory, create another directory called mylib,
492*0Sstevel@tonic-gateand cd into that directory.
493*0Sstevel@tonic-gate
494*0Sstevel@tonic-gateHere we'll create some files that will generate a test library.  These will
495*0Sstevel@tonic-gateinclude a C source file and a header file.  We'll also create a Makefile.PL
496*0Sstevel@tonic-gatein this directory.  Then we'll make sure that running make at the Mytest2
497*0Sstevel@tonic-gatelevel will automatically run this Makefile.PL file and the resulting Makefile.
498*0Sstevel@tonic-gate
499*0Sstevel@tonic-gateIn the mylib directory, create a file mylib.h that looks like this:
500*0Sstevel@tonic-gate
501*0Sstevel@tonic-gate	#define TESTVAL	4
502*0Sstevel@tonic-gate
503*0Sstevel@tonic-gate	extern double	foo(int, long, const char*);
504*0Sstevel@tonic-gate
505*0Sstevel@tonic-gateAlso create a file mylib.c that looks like this:
506*0Sstevel@tonic-gate
507*0Sstevel@tonic-gate	#include <stdlib.h>
508*0Sstevel@tonic-gate	#include "./mylib.h"
509*0Sstevel@tonic-gate
510*0Sstevel@tonic-gate	double
511*0Sstevel@tonic-gate	foo(int a, long b, const char *c)
512*0Sstevel@tonic-gate	{
513*0Sstevel@tonic-gate		return (a + b + atof(c) + TESTVAL);
514*0Sstevel@tonic-gate	}
515*0Sstevel@tonic-gate
516*0Sstevel@tonic-gateAnd finally create a file Makefile.PL that looks like this:
517*0Sstevel@tonic-gate
518*0Sstevel@tonic-gate	use ExtUtils::MakeMaker;
519*0Sstevel@tonic-gate	$Verbose = 1;
520*0Sstevel@tonic-gate	WriteMakefile(
521*0Sstevel@tonic-gate	    NAME   => 'Mytest2::mylib',
522*0Sstevel@tonic-gate	    SKIP   => [qw(all static static_lib dynamic dynamic_lib)],
523*0Sstevel@tonic-gate	    clean  => {'FILES' => 'libmylib$(LIB_EXT)'},
524*0Sstevel@tonic-gate	);
525*0Sstevel@tonic-gate
526*0Sstevel@tonic-gate
527*0Sstevel@tonic-gate	sub MY::top_targets {
528*0Sstevel@tonic-gate		'
529*0Sstevel@tonic-gate	all :: static
530*0Sstevel@tonic-gate
531*0Sstevel@tonic-gate	pure_all :: static
532*0Sstevel@tonic-gate
533*0Sstevel@tonic-gate	static ::       libmylib$(LIB_EXT)
534*0Sstevel@tonic-gate
535*0Sstevel@tonic-gate	libmylib$(LIB_EXT): $(O_FILES)
536*0Sstevel@tonic-gate		$(AR) cr libmylib$(LIB_EXT) $(O_FILES)
537*0Sstevel@tonic-gate		$(RANLIB) libmylib$(LIB_EXT)
538*0Sstevel@tonic-gate
539*0Sstevel@tonic-gate	';
540*0Sstevel@tonic-gate	}
541*0Sstevel@tonic-gate
542*0Sstevel@tonic-gateMake sure you use a tab and not spaces on the lines beginning with "$(AR)"
543*0Sstevel@tonic-gateand "$(RANLIB)".  Make will not function properly if you use spaces.
544*0Sstevel@tonic-gateIt has also been reported that the "cr" argument to $(AR) is unnecessary
545*0Sstevel@tonic-gateon Win32 systems.
546*0Sstevel@tonic-gate
547*0Sstevel@tonic-gateWe will now create the main top-level Mytest2 files.  Change to the directory
548*0Sstevel@tonic-gateabove Mytest2 and run the following command:
549*0Sstevel@tonic-gate
550*0Sstevel@tonic-gate	% h2xs -O -n Mytest2 ./Mytest2/mylib/mylib.h
551*0Sstevel@tonic-gate
552*0Sstevel@tonic-gateThis will print out a warning about overwriting Mytest2, but that's okay.
553*0Sstevel@tonic-gateOur files are stored in Mytest2/mylib, and will be untouched.
554*0Sstevel@tonic-gate
555*0Sstevel@tonic-gateThe normal Makefile.PL that h2xs generates doesn't know about the mylib
556*0Sstevel@tonic-gatedirectory.  We need to tell it that there is a subdirectory and that we
557*0Sstevel@tonic-gatewill be generating a library in it.  Let's add the argument MYEXTLIB to
558*0Sstevel@tonic-gatethe WriteMakefile call so that it looks like this:
559*0Sstevel@tonic-gate
560*0Sstevel@tonic-gate	WriteMakefile(
561*0Sstevel@tonic-gate	    'NAME'      => 'Mytest2',
562*0Sstevel@tonic-gate	    'VERSION_FROM' => 'Mytest2.pm', # finds $VERSION
563*0Sstevel@tonic-gate	    'LIBS'      => [''],   # e.g., '-lm'
564*0Sstevel@tonic-gate	    'DEFINE'    => '',     # e.g., '-DHAVE_SOMETHING'
565*0Sstevel@tonic-gate	    'INC'       => '',     # e.g., '-I/usr/include/other'
566*0Sstevel@tonic-gate	    'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)',
567*0Sstevel@tonic-gate	);
568*0Sstevel@tonic-gate
569*0Sstevel@tonic-gateand then at the end add a subroutine (which will override the pre-existing
570*0Sstevel@tonic-gatesubroutine).  Remember to use a tab character to indent the line beginning
571*0Sstevel@tonic-gatewith "cd"!
572*0Sstevel@tonic-gate
573*0Sstevel@tonic-gate	sub MY::postamble {
574*0Sstevel@tonic-gate	'
575*0Sstevel@tonic-gate	$(MYEXTLIB): mylib/Makefile
576*0Sstevel@tonic-gate		cd mylib && $(MAKE) $(PASSTHRU)
577*0Sstevel@tonic-gate	';
578*0Sstevel@tonic-gate	}
579*0Sstevel@tonic-gate
580*0Sstevel@tonic-gateLet's also fix the MANIFEST file so that it accurately reflects the contents
581*0Sstevel@tonic-gateof our extension.  The single line that says "mylib" should be replaced by
582*0Sstevel@tonic-gatethe following three lines:
583*0Sstevel@tonic-gate
584*0Sstevel@tonic-gate	mylib/Makefile.PL
585*0Sstevel@tonic-gate	mylib/mylib.c
586*0Sstevel@tonic-gate	mylib/mylib.h
587*0Sstevel@tonic-gate
588*0Sstevel@tonic-gateTo keep our namespace nice and unpolluted, edit the .pm file and change
589*0Sstevel@tonic-gatethe variable C<@EXPORT> to C<@EXPORT_OK>.  Finally, in the
590*0Sstevel@tonic-gate.xs file, edit the #include line to read:
591*0Sstevel@tonic-gate
592*0Sstevel@tonic-gate	#include "mylib/mylib.h"
593*0Sstevel@tonic-gate
594*0Sstevel@tonic-gateAnd also add the following function definition to the end of the .xs file:
595*0Sstevel@tonic-gate
596*0Sstevel@tonic-gate	double
597*0Sstevel@tonic-gate	foo(a,b,c)
598*0Sstevel@tonic-gate		int             a
599*0Sstevel@tonic-gate		long            b
600*0Sstevel@tonic-gate		const char *    c
601*0Sstevel@tonic-gate	    OUTPUT:
602*0Sstevel@tonic-gate		RETVAL
603*0Sstevel@tonic-gate
604*0Sstevel@tonic-gateNow we also need to create a typemap file because the default Perl doesn't
605*0Sstevel@tonic-gatecurrently support the const char * type.  Create a file called typemap in
606*0Sstevel@tonic-gatethe Mytest2 directory and place the following in it:
607*0Sstevel@tonic-gate
608*0Sstevel@tonic-gate	const char *	T_PV
609*0Sstevel@tonic-gate
610*0Sstevel@tonic-gateNow run perl on the top-level Makefile.PL.  Notice that it also created a
611*0Sstevel@tonic-gateMakefile in the mylib directory.  Run make and watch that it does cd into
612*0Sstevel@tonic-gatethe mylib directory and run make in there as well.
613*0Sstevel@tonic-gate
614*0Sstevel@tonic-gateNow edit the test.pl script and change the BEGIN block to print "1..4",
615*0Sstevel@tonic-gateand add the following lines to the end of the script:
616*0Sstevel@tonic-gate
617*0Sstevel@tonic-gate	print &Mytest2::foo(1, 2, "Hello, world!") == 7 ? "ok 2\n" : "not ok 2\n";
618*0Sstevel@tonic-gate	print &Mytest2::foo(1, 2, "0.0") == 7 ? "ok 3\n" : "not ok 3\n";
619*0Sstevel@tonic-gate	print abs(&Mytest2::foo(0, 0, "-3.4") - 0.6) <= 0.01 ? "ok 4\n" : "not ok 4\n";
620*0Sstevel@tonic-gate
621*0Sstevel@tonic-gate(When dealing with floating-point comparisons, it is best to not check for
622*0Sstevel@tonic-gateequality, but rather that the difference between the expected and actual
623*0Sstevel@tonic-gateresult is below a certain amount (called epsilon) which is 0.01 in this case)
624*0Sstevel@tonic-gate
625*0Sstevel@tonic-gateRun "C<make test>" and all should be well.
626*0Sstevel@tonic-gate
627*0Sstevel@tonic-gate=head2 What has happened here?
628*0Sstevel@tonic-gate
629*0Sstevel@tonic-gateUnlike previous examples, we've now run h2xs on a real include file.  This
630*0Sstevel@tonic-gatehas caused some extra goodies to appear in both the .pm and .xs files.
631*0Sstevel@tonic-gate
632*0Sstevel@tonic-gate=over 4
633*0Sstevel@tonic-gate
634*0Sstevel@tonic-gate=item *
635*0Sstevel@tonic-gate
636*0Sstevel@tonic-gateIn the .xs file, there's now a #include directive with the absolute path to
637*0Sstevel@tonic-gatethe mylib.h header file.  We changed this to a relative path so that we
638*0Sstevel@tonic-gatecould move the extension directory if we wanted to.
639*0Sstevel@tonic-gate
640*0Sstevel@tonic-gate=item *
641*0Sstevel@tonic-gate
642*0Sstevel@tonic-gateThere's now some new C code that's been added to the .xs file.  The purpose
643*0Sstevel@tonic-gateof the C<constant> routine is to make the values that are #define'd in the
644*0Sstevel@tonic-gateheader file accessible by the Perl script (by calling either C<TESTVAL> or
645*0Sstevel@tonic-gateC<&Mytest2::TESTVAL>).  There's also some XS code to allow calls to the
646*0Sstevel@tonic-gateC<constant> routine.
647*0Sstevel@tonic-gate
648*0Sstevel@tonic-gate=item *
649*0Sstevel@tonic-gate
650*0Sstevel@tonic-gateThe .pm file originally exported the name C<TESTVAL> in the C<@EXPORT> array.
651*0Sstevel@tonic-gateThis could lead to name clashes.  A good rule of thumb is that if the #define
652*0Sstevel@tonic-gateis only going to be used by the C routines themselves, and not by the user,
653*0Sstevel@tonic-gatethey should be removed from the C<@EXPORT> array.  Alternately, if you don't
654*0Sstevel@tonic-gatemind using the "fully qualified name" of a variable, you could move most
655*0Sstevel@tonic-gateor all of the items from the C<@EXPORT> array into the C<@EXPORT_OK> array.
656*0Sstevel@tonic-gate
657*0Sstevel@tonic-gate=item *
658*0Sstevel@tonic-gate
659*0Sstevel@tonic-gateIf our include file had contained #include directives, these would not have
660*0Sstevel@tonic-gatebeen processed by h2xs.  There is no good solution to this right now.
661*0Sstevel@tonic-gate
662*0Sstevel@tonic-gate=item *
663*0Sstevel@tonic-gate
664*0Sstevel@tonic-gateWe've also told Perl about the library that we built in the mylib
665*0Sstevel@tonic-gatesubdirectory.  That required only the addition of the C<MYEXTLIB> variable
666*0Sstevel@tonic-gateto the WriteMakefile call and the replacement of the postamble subroutine
667*0Sstevel@tonic-gateto cd into the subdirectory and run make.  The Makefile.PL for the
668*0Sstevel@tonic-gatelibrary is a bit more complicated, but not excessively so.  Again we
669*0Sstevel@tonic-gatereplaced the postamble subroutine to insert our own code.  This code
670*0Sstevel@tonic-gatesimply specified that the library to be created here was a static archive
671*0Sstevel@tonic-gatelibrary (as opposed to a dynamically loadable library) and provided the
672*0Sstevel@tonic-gatecommands to build it.
673*0Sstevel@tonic-gate
674*0Sstevel@tonic-gate=back
675*0Sstevel@tonic-gate
676*0Sstevel@tonic-gate=head2 Anatomy of .xs file
677*0Sstevel@tonic-gate
678*0Sstevel@tonic-gateThe .xs file of L<"EXAMPLE 4"> contained some new elements.  To understand
679*0Sstevel@tonic-gatethe meaning of these elements, pay attention to the line which reads
680*0Sstevel@tonic-gate
681*0Sstevel@tonic-gate	MODULE = Mytest2		PACKAGE = Mytest2
682*0Sstevel@tonic-gate
683*0Sstevel@tonic-gateAnything before this line is plain C code which describes which headers
684*0Sstevel@tonic-gateto include, and defines some convenience functions.  No translations are
685*0Sstevel@tonic-gateperformed on this part, apart from having embedded POD documentation
686*0Sstevel@tonic-gateskipped over (see L<perlpod>) it goes into the generated output C file as is.
687*0Sstevel@tonic-gate
688*0Sstevel@tonic-gateAnything after this line is the description of XSUB functions.
689*0Sstevel@tonic-gateThese descriptions are translated by B<xsubpp> into C code which
690*0Sstevel@tonic-gateimplements these functions using Perl calling conventions, and which
691*0Sstevel@tonic-gatemakes these functions visible from Perl interpreter.
692*0Sstevel@tonic-gate
693*0Sstevel@tonic-gatePay a special attention to the function C<constant>.  This name appears
694*0Sstevel@tonic-gatetwice in the generated .xs file: once in the first part, as a static C
695*0Sstevel@tonic-gatefunction, then another time in the second part, when an XSUB interface to
696*0Sstevel@tonic-gatethis static C function is defined.
697*0Sstevel@tonic-gate
698*0Sstevel@tonic-gateThis is quite typical for .xs files: usually the .xs file provides
699*0Sstevel@tonic-gatean interface to an existing C function.  Then this C function is defined
700*0Sstevel@tonic-gatesomewhere (either in an external library, or in the first part of .xs file),
701*0Sstevel@tonic-gateand a Perl interface to this function (i.e. "Perl glue") is described in the
702*0Sstevel@tonic-gatesecond part of .xs file.  The situation in L<"EXAMPLE 1">, L<"EXAMPLE 2">,
703*0Sstevel@tonic-gateand L<"EXAMPLE 3">, when all the work is done inside the "Perl glue", is
704*0Sstevel@tonic-gatesomewhat of an exception rather than the rule.
705*0Sstevel@tonic-gate
706*0Sstevel@tonic-gate=head2 Getting the fat out of XSUBs
707*0Sstevel@tonic-gate
708*0Sstevel@tonic-gateIn L<"EXAMPLE 4"> the second part of .xs file contained the following
709*0Sstevel@tonic-gatedescription of an XSUB:
710*0Sstevel@tonic-gate
711*0Sstevel@tonic-gate	double
712*0Sstevel@tonic-gate	foo(a,b,c)
713*0Sstevel@tonic-gate		int             a
714*0Sstevel@tonic-gate		long            b
715*0Sstevel@tonic-gate		const char *    c
716*0Sstevel@tonic-gate	    OUTPUT:
717*0Sstevel@tonic-gate		RETVAL
718*0Sstevel@tonic-gate
719*0Sstevel@tonic-gateNote that in contrast with L<"EXAMPLE 1">, L<"EXAMPLE 2"> and L<"EXAMPLE 3">,
720*0Sstevel@tonic-gatethis description does not contain the actual I<code> for what is done
721*0Sstevel@tonic-gateis done during a call to Perl function foo().  To understand what is going
722*0Sstevel@tonic-gateon here, one can add a CODE section to this XSUB:
723*0Sstevel@tonic-gate
724*0Sstevel@tonic-gate	double
725*0Sstevel@tonic-gate	foo(a,b,c)
726*0Sstevel@tonic-gate		int             a
727*0Sstevel@tonic-gate		long            b
728*0Sstevel@tonic-gate		const char *    c
729*0Sstevel@tonic-gate	    CODE:
730*0Sstevel@tonic-gate		RETVAL = foo(a,b,c);
731*0Sstevel@tonic-gate	    OUTPUT:
732*0Sstevel@tonic-gate		RETVAL
733*0Sstevel@tonic-gate
734*0Sstevel@tonic-gateHowever, these two XSUBs provide almost identical generated C code: B<xsubpp>
735*0Sstevel@tonic-gatecompiler is smart enough to figure out the C<CODE:> section from the first
736*0Sstevel@tonic-gatetwo lines of the description of XSUB.  What about C<OUTPUT:> section?  In
737*0Sstevel@tonic-gatefact, that is absolutely the same!  The C<OUTPUT:> section can be removed
738*0Sstevel@tonic-gateas well, I<as far as C<CODE:> section or C<PPCODE:> section> is not
739*0Sstevel@tonic-gatespecified: B<xsubpp> can see that it needs to generate a function call
740*0Sstevel@tonic-gatesection, and will autogenerate the OUTPUT section too.  Thus one can
741*0Sstevel@tonic-gateshortcut the XSUB to become:
742*0Sstevel@tonic-gate
743*0Sstevel@tonic-gate	double
744*0Sstevel@tonic-gate	foo(a,b,c)
745*0Sstevel@tonic-gate		int             a
746*0Sstevel@tonic-gate		long            b
747*0Sstevel@tonic-gate		const char *    c
748*0Sstevel@tonic-gate
749*0Sstevel@tonic-gateCan we do the same with an XSUB
750*0Sstevel@tonic-gate
751*0Sstevel@tonic-gate	int
752*0Sstevel@tonic-gate	is_even(input)
753*0Sstevel@tonic-gate		int	input
754*0Sstevel@tonic-gate	    CODE:
755*0Sstevel@tonic-gate		RETVAL = (input % 2 == 0);
756*0Sstevel@tonic-gate	    OUTPUT:
757*0Sstevel@tonic-gate		RETVAL
758*0Sstevel@tonic-gate
759*0Sstevel@tonic-gateof L<"EXAMPLE 2">?  To do this, one needs to define a C function C<int
760*0Sstevel@tonic-gateis_even(int input)>.  As we saw in L<Anatomy of .xs file>, a proper place
761*0Sstevel@tonic-gatefor this definition is in the first part of .xs file.  In fact a C function
762*0Sstevel@tonic-gate
763*0Sstevel@tonic-gate	int
764*0Sstevel@tonic-gate	is_even(int arg)
765*0Sstevel@tonic-gate	{
766*0Sstevel@tonic-gate		return (arg % 2 == 0);
767*0Sstevel@tonic-gate	}
768*0Sstevel@tonic-gate
769*0Sstevel@tonic-gateis probably overkill for this.  Something as simple as a C<#define> will
770*0Sstevel@tonic-gatedo too:
771*0Sstevel@tonic-gate
772*0Sstevel@tonic-gate	#define is_even(arg)	((arg) % 2 == 0)
773*0Sstevel@tonic-gate
774*0Sstevel@tonic-gateAfter having this in the first part of .xs file, the "Perl glue" part becomes
775*0Sstevel@tonic-gateas simple as
776*0Sstevel@tonic-gate
777*0Sstevel@tonic-gate	int
778*0Sstevel@tonic-gate	is_even(input)
779*0Sstevel@tonic-gate		int	input
780*0Sstevel@tonic-gate
781*0Sstevel@tonic-gateThis technique of separation of the glue part from the workhorse part has
782*0Sstevel@tonic-gateobvious tradeoffs: if you want to change a Perl interface, you need to
783*0Sstevel@tonic-gatechange two places in your code.  However, it removes a lot of clutter,
784*0Sstevel@tonic-gateand makes the workhorse part independent from idiosyncrasies of Perl calling
785*0Sstevel@tonic-gateconvention.  (In fact, there is nothing Perl-specific in the above description,
786*0Sstevel@tonic-gatea different version of B<xsubpp> might have translated this to TCL glue or
787*0Sstevel@tonic-gatePython glue as well.)
788*0Sstevel@tonic-gate
789*0Sstevel@tonic-gate=head2 More about XSUB arguments
790*0Sstevel@tonic-gate
791*0Sstevel@tonic-gateWith the completion of Example 4, we now have an easy way to simulate some
792*0Sstevel@tonic-gatereal-life libraries whose interfaces may not be the cleanest in the world.
793*0Sstevel@tonic-gateWe shall now continue with a discussion of the arguments passed to the
794*0Sstevel@tonic-gateB<xsubpp> compiler.
795*0Sstevel@tonic-gate
796*0Sstevel@tonic-gateWhen you specify arguments to routines in the .xs file, you are really
797*0Sstevel@tonic-gatepassing three pieces of information for each argument listed.  The first
798*0Sstevel@tonic-gatepiece is the order of that argument relative to the others (first, second,
799*0Sstevel@tonic-gateetc).  The second is the type of argument, and consists of the type
800*0Sstevel@tonic-gatedeclaration of the argument (e.g., int, char*, etc).  The third piece is
801*0Sstevel@tonic-gatethe calling convention for the argument in the call to the library function.
802*0Sstevel@tonic-gate
803*0Sstevel@tonic-gateWhile Perl passes arguments to functions by reference,
804*0Sstevel@tonic-gateC passes arguments by value; to implement a C function which modifies data
805*0Sstevel@tonic-gateof one of the "arguments", the actual argument of this C function would be
806*0Sstevel@tonic-gatea pointer to the data.  Thus two C functions with declarations
807*0Sstevel@tonic-gate
808*0Sstevel@tonic-gate	int string_length(char *s);
809*0Sstevel@tonic-gate	int upper_case_char(char *cp);
810*0Sstevel@tonic-gate
811*0Sstevel@tonic-gatemay have completely different semantics: the first one may inspect an array
812*0Sstevel@tonic-gateof chars pointed by s, and the second one may immediately dereference C<cp>
813*0Sstevel@tonic-gateand manipulate C<*cp> only (using the return value as, say, a success
814*0Sstevel@tonic-gateindicator).  From Perl one would use these functions in
815*0Sstevel@tonic-gatea completely different manner.
816*0Sstevel@tonic-gate
817*0Sstevel@tonic-gateOne conveys this info to B<xsubpp> by replacing C<*> before the
818*0Sstevel@tonic-gateargument by C<&>.  C<&> means that the argument should be passed to a library
819*0Sstevel@tonic-gatefunction by its address.  The above two function may be XSUB-ified as
820*0Sstevel@tonic-gate
821*0Sstevel@tonic-gate	int
822*0Sstevel@tonic-gate	string_length(s)
823*0Sstevel@tonic-gate		char *	s
824*0Sstevel@tonic-gate
825*0Sstevel@tonic-gate	int
826*0Sstevel@tonic-gate	upper_case_char(cp)
827*0Sstevel@tonic-gate		char	&cp
828*0Sstevel@tonic-gate
829*0Sstevel@tonic-gateFor example, consider:
830*0Sstevel@tonic-gate
831*0Sstevel@tonic-gate	int
832*0Sstevel@tonic-gate	foo(a,b)
833*0Sstevel@tonic-gate		char	&a
834*0Sstevel@tonic-gate		char *	b
835*0Sstevel@tonic-gate
836*0Sstevel@tonic-gateThe first Perl argument to this function would be treated as a char and assigned
837*0Sstevel@tonic-gateto the variable a, and its address would be passed into the function foo.
838*0Sstevel@tonic-gateThe second Perl argument would be treated as a string pointer and assigned to the
839*0Sstevel@tonic-gatevariable b.  The I<value> of b would be passed into the function foo.  The
840*0Sstevel@tonic-gateactual call to the function foo that B<xsubpp> generates would look like this:
841*0Sstevel@tonic-gate
842*0Sstevel@tonic-gate	foo(&a, b);
843*0Sstevel@tonic-gate
844*0Sstevel@tonic-gateB<xsubpp> will parse the following function argument lists identically:
845*0Sstevel@tonic-gate
846*0Sstevel@tonic-gate	char	&a
847*0Sstevel@tonic-gate	char&a
848*0Sstevel@tonic-gate	char	& a
849*0Sstevel@tonic-gate
850*0Sstevel@tonic-gateHowever, to help ease understanding, it is suggested that you place a "&"
851*0Sstevel@tonic-gatenext to the variable name and away from the variable type), and place a
852*0Sstevel@tonic-gate"*" near the variable type, but away from the variable name (as in the
853*0Sstevel@tonic-gatecall to foo above).  By doing so, it is easy to understand exactly what
854*0Sstevel@tonic-gatewill be passed to the C function -- it will be whatever is in the "last
855*0Sstevel@tonic-gatecolumn".
856*0Sstevel@tonic-gate
857*0Sstevel@tonic-gateYou should take great pains to try to pass the function the type of variable
858*0Sstevel@tonic-gateit wants, when possible.  It will save you a lot of trouble in the long run.
859*0Sstevel@tonic-gate
860*0Sstevel@tonic-gate=head2 The Argument Stack
861*0Sstevel@tonic-gate
862*0Sstevel@tonic-gateIf we look at any of the C code generated by any of the examples except
863*0Sstevel@tonic-gateexample 1, you will notice a number of references to ST(n), where n is
864*0Sstevel@tonic-gateusually 0.  "ST" is actually a macro that points to the n'th argument
865*0Sstevel@tonic-gateon the argument stack.  ST(0) is thus the first argument on the stack and
866*0Sstevel@tonic-gatetherefore the first argument passed to the XSUB, ST(1) is the second
867*0Sstevel@tonic-gateargument, and so on.
868*0Sstevel@tonic-gate
869*0Sstevel@tonic-gateWhen you list the arguments to the XSUB in the .xs file, that tells B<xsubpp>
870*0Sstevel@tonic-gatewhich argument corresponds to which of the argument stack (i.e., the first
871*0Sstevel@tonic-gateone listed is the first argument, and so on).  You invite disaster if you
872*0Sstevel@tonic-gatedo not list them in the same order as the function expects them.
873*0Sstevel@tonic-gate
874*0Sstevel@tonic-gateThe actual values on the argument stack are pointers to the values passed
875*0Sstevel@tonic-gatein.  When an argument is listed as being an OUTPUT value, its corresponding
876*0Sstevel@tonic-gatevalue on the stack (i.e., ST(0) if it was the first argument) is changed.
877*0Sstevel@tonic-gateYou can verify this by looking at the C code generated for Example 3.
878*0Sstevel@tonic-gateThe code for the round() XSUB routine contains lines that look like this:
879*0Sstevel@tonic-gate
880*0Sstevel@tonic-gate	double  arg = (double)SvNV(ST(0));
881*0Sstevel@tonic-gate	/* Round the contents of the variable arg */
882*0Sstevel@tonic-gate	sv_setnv(ST(0), (double)arg);
883*0Sstevel@tonic-gate
884*0Sstevel@tonic-gateThe arg variable is initially set by taking the value from ST(0), then is
885*0Sstevel@tonic-gatestored back into ST(0) at the end of the routine.
886*0Sstevel@tonic-gate
887*0Sstevel@tonic-gateXSUBs are also allowed to return lists, not just scalars.  This must be
888*0Sstevel@tonic-gatedone by manipulating stack values ST(0), ST(1), etc, in a subtly
889*0Sstevel@tonic-gatedifferent way.  See L<perlxs> for details.
890*0Sstevel@tonic-gate
891*0Sstevel@tonic-gateXSUBs are also allowed to avoid automatic conversion of Perl function arguments
892*0Sstevel@tonic-gateto C function arguments.  See L<perlxs> for details.  Some people prefer
893*0Sstevel@tonic-gatemanual conversion by inspecting C<ST(i)> even in the cases when automatic
894*0Sstevel@tonic-gateconversion will do, arguing that this makes the logic of an XSUB call clearer.
895*0Sstevel@tonic-gateCompare with L<"Getting the fat out of XSUBs"> for a similar tradeoff of
896*0Sstevel@tonic-gatea complete separation of "Perl glue" and "workhorse" parts of an XSUB.
897*0Sstevel@tonic-gate
898*0Sstevel@tonic-gateWhile experts may argue about these idioms, a novice to Perl guts may
899*0Sstevel@tonic-gateprefer a way which is as little Perl-guts-specific as possible, meaning
900*0Sstevel@tonic-gateautomatic conversion and automatic call generation, as in
901*0Sstevel@tonic-gateL<"Getting the fat out of XSUBs">.  This approach has the additional
902*0Sstevel@tonic-gatebenefit of protecting the XSUB writer from future changes to the Perl API.
903*0Sstevel@tonic-gate
904*0Sstevel@tonic-gate=head2 Extending your Extension
905*0Sstevel@tonic-gate
906*0Sstevel@tonic-gateSometimes you might want to provide some extra methods or subroutines
907*0Sstevel@tonic-gateto assist in making the interface between Perl and your extension simpler
908*0Sstevel@tonic-gateor easier to understand.  These routines should live in the .pm file.
909*0Sstevel@tonic-gateWhether they are automatically loaded when the extension itself is loaded
910*0Sstevel@tonic-gateor only loaded when called depends on where in the .pm file the subroutine
911*0Sstevel@tonic-gatedefinition is placed.  You can also consult L<AutoLoader> for an alternate
912*0Sstevel@tonic-gateway to store and load your extra subroutines.
913*0Sstevel@tonic-gate
914*0Sstevel@tonic-gate=head2 Documenting your Extension
915*0Sstevel@tonic-gate
916*0Sstevel@tonic-gateThere is absolutely no excuse for not documenting your extension.
917*0Sstevel@tonic-gateDocumentation belongs in the .pm file.  This file will be fed to pod2man,
918*0Sstevel@tonic-gateand the embedded documentation will be converted to the manpage format,
919*0Sstevel@tonic-gatethen placed in the blib directory.  It will be copied to Perl's
920*0Sstevel@tonic-gatemanpage directory when the extension is installed.
921*0Sstevel@tonic-gate
922*0Sstevel@tonic-gateYou may intersperse documentation and Perl code within the .pm file.
923*0Sstevel@tonic-gateIn fact, if you want to use method autoloading, you must do this,
924*0Sstevel@tonic-gateas the comment inside the .pm file explains.
925*0Sstevel@tonic-gate
926*0Sstevel@tonic-gateSee L<perlpod> for more information about the pod format.
927*0Sstevel@tonic-gate
928*0Sstevel@tonic-gate=head2 Installing your Extension
929*0Sstevel@tonic-gate
930*0Sstevel@tonic-gateOnce your extension is complete and passes all its tests, installing it
931*0Sstevel@tonic-gateis quite simple: you simply run "make install".  You will either need
932*0Sstevel@tonic-gateto have write permission into the directories where Perl is installed,
933*0Sstevel@tonic-gateor ask your system administrator to run the make for you.
934*0Sstevel@tonic-gate
935*0Sstevel@tonic-gateAlternately, you can specify the exact directory to place the extension's
936*0Sstevel@tonic-gatefiles by placing a "PREFIX=/destination/directory" after the make install.
937*0Sstevel@tonic-gate(or in between the make and install if you have a brain-dead version of make).
938*0Sstevel@tonic-gateThis can be very useful if you are building an extension that will eventually
939*0Sstevel@tonic-gatebe distributed to multiple systems.  You can then just archive the files in
940*0Sstevel@tonic-gatethe destination directory and distribute them to your destination systems.
941*0Sstevel@tonic-gate
942*0Sstevel@tonic-gate=head2 EXAMPLE 5
943*0Sstevel@tonic-gate
944*0Sstevel@tonic-gateIn this example, we'll do some more work with the argument stack.  The
945*0Sstevel@tonic-gateprevious examples have all returned only a single value.  We'll now
946*0Sstevel@tonic-gatecreate an extension that returns an array.
947*0Sstevel@tonic-gate
948*0Sstevel@tonic-gateThis extension is very Unix-oriented (struct statfs and the statfs system
949*0Sstevel@tonic-gatecall).  If you are not running on a Unix system, you can substitute for
950*0Sstevel@tonic-gatestatfs any other function that returns multiple values, you can hard-code
951*0Sstevel@tonic-gatevalues to be returned to the caller (although this will be a bit harder
952*0Sstevel@tonic-gateto test the error case), or you can simply not do this example.  If you
953*0Sstevel@tonic-gatechange the XSUB, be sure to fix the test cases to match the changes.
954*0Sstevel@tonic-gate
955*0Sstevel@tonic-gateReturn to the Mytest directory and add the following code to the end of
956*0Sstevel@tonic-gateMytest.xs:
957*0Sstevel@tonic-gate
958*0Sstevel@tonic-gate	void
959*0Sstevel@tonic-gate	statfs(path)
960*0Sstevel@tonic-gate		char *  path
961*0Sstevel@tonic-gate	    INIT:
962*0Sstevel@tonic-gate		int i;
963*0Sstevel@tonic-gate		struct statfs buf;
964*0Sstevel@tonic-gate
965*0Sstevel@tonic-gate	    PPCODE:
966*0Sstevel@tonic-gate		i = statfs(path, &buf);
967*0Sstevel@tonic-gate		if (i == 0) {
968*0Sstevel@tonic-gate			XPUSHs(sv_2mortal(newSVnv(buf.f_bavail)));
969*0Sstevel@tonic-gate			XPUSHs(sv_2mortal(newSVnv(buf.f_bfree)));
970*0Sstevel@tonic-gate			XPUSHs(sv_2mortal(newSVnv(buf.f_blocks)));
971*0Sstevel@tonic-gate			XPUSHs(sv_2mortal(newSVnv(buf.f_bsize)));
972*0Sstevel@tonic-gate			XPUSHs(sv_2mortal(newSVnv(buf.f_ffree)));
973*0Sstevel@tonic-gate			XPUSHs(sv_2mortal(newSVnv(buf.f_files)));
974*0Sstevel@tonic-gate			XPUSHs(sv_2mortal(newSVnv(buf.f_type)));
975*0Sstevel@tonic-gate			XPUSHs(sv_2mortal(newSVnv(buf.f_fsid[0])));
976*0Sstevel@tonic-gate			XPUSHs(sv_2mortal(newSVnv(buf.f_fsid[1])));
977*0Sstevel@tonic-gate		} else {
978*0Sstevel@tonic-gate			XPUSHs(sv_2mortal(newSVnv(errno)));
979*0Sstevel@tonic-gate		}
980*0Sstevel@tonic-gate
981*0Sstevel@tonic-gateYou'll also need to add the following code to the top of the .xs file, just
982*0Sstevel@tonic-gateafter the include of "XSUB.h":
983*0Sstevel@tonic-gate
984*0Sstevel@tonic-gate	#include <sys/vfs.h>
985*0Sstevel@tonic-gate
986*0Sstevel@tonic-gateAlso add the following code segment to test.pl while incrementing the "1..9"
987*0Sstevel@tonic-gatestring in the BEGIN block to "1..11":
988*0Sstevel@tonic-gate
989*0Sstevel@tonic-gate	@a = &Mytest::statfs("/blech");
990*0Sstevel@tonic-gate	print ((scalar(@a) == 1 && $a[0] == 2) ? "ok 10\n" : "not ok 10\n");
991*0Sstevel@tonic-gate	@a = &Mytest::statfs("/");
992*0Sstevel@tonic-gate	print scalar(@a) == 9 ? "ok 11\n" : "not ok 11\n";
993*0Sstevel@tonic-gate
994*0Sstevel@tonic-gate=head2 New Things in this Example
995*0Sstevel@tonic-gate
996*0Sstevel@tonic-gateThis example added quite a few new concepts.  We'll take them one at a time.
997*0Sstevel@tonic-gate
998*0Sstevel@tonic-gate=over 4
999*0Sstevel@tonic-gate
1000*0Sstevel@tonic-gate=item *
1001*0Sstevel@tonic-gate
1002*0Sstevel@tonic-gateThe INIT: directive contains code that will be placed immediately after
1003*0Sstevel@tonic-gatethe argument stack is decoded.  C does not allow variable declarations at
1004*0Sstevel@tonic-gatearbitrary locations inside a function,
1005*0Sstevel@tonic-gateso this is usually the best way to declare local variables needed by the XSUB.
1006*0Sstevel@tonic-gate(Alternatively, one could put the whole C<PPCODE:> section into braces, and
1007*0Sstevel@tonic-gateput these declarations on top.)
1008*0Sstevel@tonic-gate
1009*0Sstevel@tonic-gate=item *
1010*0Sstevel@tonic-gate
1011*0Sstevel@tonic-gateThis routine also returns a different number of arguments depending on the
1012*0Sstevel@tonic-gatesuccess or failure of the call to statfs.  If there is an error, the error
1013*0Sstevel@tonic-gatenumber is returned as a single-element array.  If the call is successful,
1014*0Sstevel@tonic-gatethen a 9-element array is returned.  Since only one argument is passed into
1015*0Sstevel@tonic-gatethis function, we need room on the stack to hold the 9 values which may be
1016*0Sstevel@tonic-gatereturned.
1017*0Sstevel@tonic-gate
1018*0Sstevel@tonic-gateWe do this by using the PPCODE: directive, rather than the CODE: directive.
1019*0Sstevel@tonic-gateThis tells B<xsubpp> that we will be managing the return values that will be
1020*0Sstevel@tonic-gateput on the argument stack by ourselves.
1021*0Sstevel@tonic-gate
1022*0Sstevel@tonic-gate=item *
1023*0Sstevel@tonic-gate
1024*0Sstevel@tonic-gateWhen we want to place values to be returned to the caller onto the stack,
1025*0Sstevel@tonic-gatewe use the series of macros that begin with "XPUSH".  There are five
1026*0Sstevel@tonic-gatedifferent versions, for placing integers, unsigned integers, doubles,
1027*0Sstevel@tonic-gatestrings, and Perl scalars on the stack.  In our example, we placed a
1028*0Sstevel@tonic-gatePerl scalar onto the stack.  (In fact this is the only macro which
1029*0Sstevel@tonic-gatecan be used to return multiple values.)
1030*0Sstevel@tonic-gate
1031*0Sstevel@tonic-gateThe XPUSH* macros will automatically extend the return stack to prevent
1032*0Sstevel@tonic-gateit from being overrun.  You push values onto the stack in the order you
1033*0Sstevel@tonic-gatewant them seen by the calling program.
1034*0Sstevel@tonic-gate
1035*0Sstevel@tonic-gate=item *
1036*0Sstevel@tonic-gate
1037*0Sstevel@tonic-gateThe values pushed onto the return stack of the XSUB are actually mortal SV's.
1038*0Sstevel@tonic-gateThey are made mortal so that once the values are copied by the calling
1039*0Sstevel@tonic-gateprogram, the SV's that held the returned values can be deallocated.
1040*0Sstevel@tonic-gateIf they were not mortal, then they would continue to exist after the XSUB
1041*0Sstevel@tonic-gateroutine returned, but would not be accessible.  This is a memory leak.
1042*0Sstevel@tonic-gate
1043*0Sstevel@tonic-gate=item *
1044*0Sstevel@tonic-gate
1045*0Sstevel@tonic-gateIf we were interested in performance, not in code compactness, in the success
1046*0Sstevel@tonic-gatebranch we would not use C<XPUSHs> macros, but C<PUSHs> macros, and would
1047*0Sstevel@tonic-gatepre-extend the stack before pushing the return values:
1048*0Sstevel@tonic-gate
1049*0Sstevel@tonic-gate	EXTEND(SP, 9);
1050*0Sstevel@tonic-gate
1051*0Sstevel@tonic-gateThe tradeoff is that one needs to calculate the number of return values
1052*0Sstevel@tonic-gatein advance (though overextending the stack will not typically hurt
1053*0Sstevel@tonic-gateanything but memory consumption).
1054*0Sstevel@tonic-gate
1055*0Sstevel@tonic-gateSimilarly, in the failure branch we could use C<PUSHs> I<without> extending
1056*0Sstevel@tonic-gatethe stack: the Perl function reference comes to an XSUB on the stack, thus
1057*0Sstevel@tonic-gatethe stack is I<always> large enough to take one return value.
1058*0Sstevel@tonic-gate
1059*0Sstevel@tonic-gate=back
1060*0Sstevel@tonic-gate
1061*0Sstevel@tonic-gate=head2 EXAMPLE 6
1062*0Sstevel@tonic-gate
1063*0Sstevel@tonic-gateIn this example, we will accept a reference to an array as an input
1064*0Sstevel@tonic-gateparameter, and return a reference to an array of hashes.  This will
1065*0Sstevel@tonic-gatedemonstrate manipulation of complex Perl data types from an XSUB.
1066*0Sstevel@tonic-gate
1067*0Sstevel@tonic-gateThis extension is somewhat contrived.  It is based on the code in
1068*0Sstevel@tonic-gatethe previous example.  It calls the statfs function multiple times,
1069*0Sstevel@tonic-gateaccepting a reference to an array of filenames as input, and returning
1070*0Sstevel@tonic-gatea reference to an array of hashes containing the data for each of the
1071*0Sstevel@tonic-gatefilesystems.
1072*0Sstevel@tonic-gate
1073*0Sstevel@tonic-gateReturn to the Mytest directory and add the following code to the end of
1074*0Sstevel@tonic-gateMytest.xs:
1075*0Sstevel@tonic-gate
1076*0Sstevel@tonic-gate	SV *
1077*0Sstevel@tonic-gate	multi_statfs(paths)
1078*0Sstevel@tonic-gate		SV * paths
1079*0Sstevel@tonic-gate	    INIT:
1080*0Sstevel@tonic-gate        	AV * results;
1081*0Sstevel@tonic-gate        	I32 numpaths = 0;
1082*0Sstevel@tonic-gate        	int i, n;
1083*0Sstevel@tonic-gate        	struct statfs buf;
1084*0Sstevel@tonic-gate
1085*0Sstevel@tonic-gate        	if ((!SvROK(paths))
1086*0Sstevel@tonic-gate		    || (SvTYPE(SvRV(paths)) != SVt_PVAV)
1087*0Sstevel@tonic-gate		    || ((numpaths = av_len((AV *)SvRV(paths))) < 0))
1088*0Sstevel@tonic-gate		{
1089*0Sstevel@tonic-gate		    XSRETURN_UNDEF;
1090*0Sstevel@tonic-gate        	}
1091*0Sstevel@tonic-gate        	results = (AV *)sv_2mortal((SV *)newAV());
1092*0Sstevel@tonic-gate	    CODE:
1093*0Sstevel@tonic-gate        	for (n = 0; n <= numpaths; n++) {
1094*0Sstevel@tonic-gate		    HV * rh;
1095*0Sstevel@tonic-gate            	    STRLEN l;
1096*0Sstevel@tonic-gate            	    char * fn = SvPV(*av_fetch((AV *)SvRV(paths), n, 0), l);
1097*0Sstevel@tonic-gate
1098*0Sstevel@tonic-gate            	    i = statfs(fn, &buf);
1099*0Sstevel@tonic-gate            	    if (i != 0) {
1100*0Sstevel@tonic-gate		        av_push(results, newSVnv(errno));
1101*0Sstevel@tonic-gate		        continue;
1102*0Sstevel@tonic-gate            	    }
1103*0Sstevel@tonic-gate
1104*0Sstevel@tonic-gate            	    rh = (HV *)sv_2mortal((SV *)newHV());
1105*0Sstevel@tonic-gate
1106*0Sstevel@tonic-gate            	    hv_store(rh, "f_bavail", 8, newSVnv(buf.f_bavail), 0);
1107*0Sstevel@tonic-gate            	    hv_store(rh, "f_bfree",  7, newSVnv(buf.f_bfree),  0);
1108*0Sstevel@tonic-gate            	    hv_store(rh, "f_blocks", 8, newSVnv(buf.f_blocks), 0);
1109*0Sstevel@tonic-gate            	    hv_store(rh, "f_bsize",  7, newSVnv(buf.f_bsize),  0);
1110*0Sstevel@tonic-gate            	    hv_store(rh, "f_ffree",  7, newSVnv(buf.f_ffree),  0);
1111*0Sstevel@tonic-gate            	    hv_store(rh, "f_files",  7, newSVnv(buf.f_files),  0);
1112*0Sstevel@tonic-gate            	    hv_store(rh, "f_type",   6, newSVnv(buf.f_type),   0);
1113*0Sstevel@tonic-gate
1114*0Sstevel@tonic-gate            	    av_push(results, newRV((SV *)rh));
1115*0Sstevel@tonic-gate        	}
1116*0Sstevel@tonic-gate        	RETVAL = newRV((SV *)results);
1117*0Sstevel@tonic-gate	    OUTPUT:
1118*0Sstevel@tonic-gate        	RETVAL
1119*0Sstevel@tonic-gate
1120*0Sstevel@tonic-gateAnd add the following code to test.pl, while incrementing the "1..11"
1121*0Sstevel@tonic-gatestring in the BEGIN block to "1..13":
1122*0Sstevel@tonic-gate
1123*0Sstevel@tonic-gate	$results = Mytest::multi_statfs([ '/', '/blech' ]);
1124*0Sstevel@tonic-gate	print ((ref $results->[0]) ? "ok 12\n" : "not ok 12\n");
1125*0Sstevel@tonic-gate	print ((! ref $results->[1]) ? "ok 13\n" : "not ok 13\n");
1126*0Sstevel@tonic-gate
1127*0Sstevel@tonic-gate=head2 New Things in this Example
1128*0Sstevel@tonic-gate
1129*0Sstevel@tonic-gateThere are a number of new concepts introduced here, described below:
1130*0Sstevel@tonic-gate
1131*0Sstevel@tonic-gate=over 4
1132*0Sstevel@tonic-gate
1133*0Sstevel@tonic-gate=item *
1134*0Sstevel@tonic-gate
1135*0Sstevel@tonic-gateThis function does not use a typemap.  Instead, we declare it as accepting
1136*0Sstevel@tonic-gateone SV* (scalar) parameter, and returning an SV* value, and we take care of
1137*0Sstevel@tonic-gatepopulating these scalars within the code.  Because we are only returning
1138*0Sstevel@tonic-gateone value, we don't need a C<PPCODE:> directive - instead, we use C<CODE:>
1139*0Sstevel@tonic-gateand C<OUTPUT:> directives.
1140*0Sstevel@tonic-gate
1141*0Sstevel@tonic-gate=item *
1142*0Sstevel@tonic-gate
1143*0Sstevel@tonic-gateWhen dealing with references, it is important to handle them with caution.
1144*0Sstevel@tonic-gateThe C<INIT:> block first checks that
1145*0Sstevel@tonic-gateC<SvROK> returns true, which indicates that paths is a valid reference.  It
1146*0Sstevel@tonic-gatethen verifies that the object referenced by paths is an array, using C<SvRV>
1147*0Sstevel@tonic-gateto dereference paths, and C<SvTYPE> to discover its type.  As an added test,
1148*0Sstevel@tonic-gateit checks that the array referenced by paths is non-empty, using the C<av_len>
1149*0Sstevel@tonic-gatefunction (which returns -1 if the array is empty).  The XSRETURN_UNDEF macro
1150*0Sstevel@tonic-gateis used to abort the XSUB and return the undefined value whenever all three of
1151*0Sstevel@tonic-gatethese conditions are not met.
1152*0Sstevel@tonic-gate
1153*0Sstevel@tonic-gate=item *
1154*0Sstevel@tonic-gate
1155*0Sstevel@tonic-gateWe manipulate several arrays in this XSUB.  Note that an array is represented
1156*0Sstevel@tonic-gateinternally by an AV* pointer.  The functions and macros for manipulating
1157*0Sstevel@tonic-gatearrays are similar to the functions in Perl: C<av_len> returns the highest
1158*0Sstevel@tonic-gateindex in an AV*, much like $#array; C<av_fetch> fetches a single scalar value
1159*0Sstevel@tonic-gatefrom an array, given its index; C<av_push> pushes a scalar value onto the
1160*0Sstevel@tonic-gateend of the array, automatically extending the array as necessary.
1161*0Sstevel@tonic-gate
1162*0Sstevel@tonic-gateSpecifically, we read pathnames one at a time from the input array, and
1163*0Sstevel@tonic-gatestore the results in an output array (results) in the same order.  If
1164*0Sstevel@tonic-gatestatfs fails, the element pushed onto the return array is the value of
1165*0Sstevel@tonic-gateerrno after the failure.  If statfs succeeds, though, the value pushed
1166*0Sstevel@tonic-gateonto the return array is a reference to a hash containing some of the
1167*0Sstevel@tonic-gateinformation in the statfs structure.
1168*0Sstevel@tonic-gate
1169*0Sstevel@tonic-gateAs with the return stack, it would be possible (and a small performance win)
1170*0Sstevel@tonic-gateto pre-extend the return array before pushing data into it, since we know
1171*0Sstevel@tonic-gatehow many elements we will return:
1172*0Sstevel@tonic-gate
1173*0Sstevel@tonic-gate	av_extend(results, numpaths);
1174*0Sstevel@tonic-gate
1175*0Sstevel@tonic-gate=item *
1176*0Sstevel@tonic-gate
1177*0Sstevel@tonic-gateWe are performing only one hash operation in this function, which is storing
1178*0Sstevel@tonic-gatea new scalar under a key using C<hv_store>.  A hash is represented by an HV*
1179*0Sstevel@tonic-gatepointer.  Like arrays, the functions for manipulating hashes from an XSUB
1180*0Sstevel@tonic-gatemirror the functionality available from Perl.  See L<perlguts> and L<perlapi>
1181*0Sstevel@tonic-gatefor details.
1182*0Sstevel@tonic-gate
1183*0Sstevel@tonic-gate=item *
1184*0Sstevel@tonic-gate
1185*0Sstevel@tonic-gateTo create a reference, we use the C<newRV> function.  Note that you can
1186*0Sstevel@tonic-gatecast an AV* or an HV* to type SV* in this case (and many others).  This
1187*0Sstevel@tonic-gateallows you to take references to arrays, hashes and scalars with the same
1188*0Sstevel@tonic-gatefunction.  Conversely, the C<SvRV> function always returns an SV*, which may
1189*0Sstevel@tonic-gateneed to be cast to the appropriate type if it is something other than a
1190*0Sstevel@tonic-gatescalar (check with C<SvTYPE>).
1191*0Sstevel@tonic-gate
1192*0Sstevel@tonic-gate=item *
1193*0Sstevel@tonic-gate
1194*0Sstevel@tonic-gateAt this point, xsubpp is doing very little work - the differences between
1195*0Sstevel@tonic-gateMytest.xs and Mytest.c are minimal.
1196*0Sstevel@tonic-gate
1197*0Sstevel@tonic-gate=back
1198*0Sstevel@tonic-gate
1199*0Sstevel@tonic-gate=head2 EXAMPLE 7 (Coming Soon)
1200*0Sstevel@tonic-gate
1201*0Sstevel@tonic-gateXPUSH args AND set RETVAL AND assign return value to array
1202*0Sstevel@tonic-gate
1203*0Sstevel@tonic-gate=head2 EXAMPLE 8 (Coming Soon)
1204*0Sstevel@tonic-gate
1205*0Sstevel@tonic-gateSetting $!
1206*0Sstevel@tonic-gate
1207*0Sstevel@tonic-gate=head2 EXAMPLE 9 Passing open files to XSes
1208*0Sstevel@tonic-gate
1209*0Sstevel@tonic-gateYou would think passing files to an XS is difficult, with all the
1210*0Sstevel@tonic-gatetypeglobs and stuff. Well, it isn't.
1211*0Sstevel@tonic-gate
1212*0Sstevel@tonic-gateSuppose that for some strange reason we need a wrapper around the
1213*0Sstevel@tonic-gatestandard C library function C<fputs()>. This is all we need:
1214*0Sstevel@tonic-gate
1215*0Sstevel@tonic-gate	#define PERLIO_NOT_STDIO 0
1216*0Sstevel@tonic-gate	#include "EXTERN.h"
1217*0Sstevel@tonic-gate	#include "perl.h"
1218*0Sstevel@tonic-gate	#include "XSUB.h"
1219*0Sstevel@tonic-gate
1220*0Sstevel@tonic-gate	#include <stdio.h>
1221*0Sstevel@tonic-gate
1222*0Sstevel@tonic-gate	int
1223*0Sstevel@tonic-gate	fputs(s, stream)
1224*0Sstevel@tonic-gate		char *          s
1225*0Sstevel@tonic-gate		FILE *	        stream
1226*0Sstevel@tonic-gate
1227*0Sstevel@tonic-gateThe real work is done in the standard typemap.
1228*0Sstevel@tonic-gate
1229*0Sstevel@tonic-gateB<But> you loose all the fine stuff done by the perlio layers. This
1230*0Sstevel@tonic-gatecalls the stdio function C<fputs()>, which knows nothing about them.
1231*0Sstevel@tonic-gate
1232*0Sstevel@tonic-gateThe standard typemap offers three variants of PerlIO *:
1233*0Sstevel@tonic-gateC<InputStream> (T_IN), C<InOutStream> (T_INOUT) and C<OutputStream>
1234*0Sstevel@tonic-gate(T_OUT). A bare C<PerlIO *> is considered a T_INOUT. If it matters
1235*0Sstevel@tonic-gatein your code (see below for why it might) #define or typedef
1236*0Sstevel@tonic-gateone of the specific names and use that as the argument or result
1237*0Sstevel@tonic-gatetype in your XS file.
1238*0Sstevel@tonic-gate
1239*0Sstevel@tonic-gateThe standard typemap does not contain PerlIO * before perl 5.7,
1240*0Sstevel@tonic-gatebut it has the three stream variants. Using a PerlIO * directly
1241*0Sstevel@tonic-gateis not backwards compatible unless you provide your own typemap.
1242*0Sstevel@tonic-gate
1243*0Sstevel@tonic-gateFor streams coming I<from> perl the main difference is that
1244*0Sstevel@tonic-gateC<OutputStream> will get the output PerlIO * - which may make
1245*0Sstevel@tonic-gatea difference on a socket. Like in our example...
1246*0Sstevel@tonic-gate
1247*0Sstevel@tonic-gateFor streams being handed I<to> perl a new file handle is created
1248*0Sstevel@tonic-gate(i.e. a reference to a new glob) and associated with the PerlIO *
1249*0Sstevel@tonic-gateprovided. If the read/write state of the PerlIO * is not correct then you
1250*0Sstevel@tonic-gatemay get errors or warnings from when the file handle is used.
1251*0Sstevel@tonic-gateSo if you opened the PerlIO * as "w" it should really be an
1252*0Sstevel@tonic-gateC<OutputStream> if open as "r" it should be an C<InputStream>.
1253*0Sstevel@tonic-gate
1254*0Sstevel@tonic-gateNow, suppose you want to use perlio layers in your XS. We'll use the
1255*0Sstevel@tonic-gateperlio C<PerlIO_puts()> function as an example.
1256*0Sstevel@tonic-gate
1257*0Sstevel@tonic-gateIn the C part of the XS file (above the first MODULE line) you
1258*0Sstevel@tonic-gatehave
1259*0Sstevel@tonic-gate
1260*0Sstevel@tonic-gate	#define OutputStream	PerlIO *
1261*0Sstevel@tonic-gate    or
1262*0Sstevel@tonic-gate	typedef PerlIO *	OutputStream;
1263*0Sstevel@tonic-gate
1264*0Sstevel@tonic-gate
1265*0Sstevel@tonic-gateAnd this is the XS code:
1266*0Sstevel@tonic-gate
1267*0Sstevel@tonic-gate	int
1268*0Sstevel@tonic-gate	perlioputs(s, stream)
1269*0Sstevel@tonic-gate		char *          s
1270*0Sstevel@tonic-gate		OutputStream	stream
1271*0Sstevel@tonic-gate	CODE:
1272*0Sstevel@tonic-gate		RETVAL = PerlIO_puts(stream, s);
1273*0Sstevel@tonic-gate	OUTPUT:
1274*0Sstevel@tonic-gate		RETVAL
1275*0Sstevel@tonic-gate
1276*0Sstevel@tonic-gateWe have to use a C<CODE> section because C<PerlIO_puts()> has the arguments
1277*0Sstevel@tonic-gatereversed compared to C<fputs()>, and we want to keep the arguments the same.
1278*0Sstevel@tonic-gate
1279*0Sstevel@tonic-gateWanting to explore this thoroughly, we want to use the stdio C<fputs()>
1280*0Sstevel@tonic-gateon a PerlIO *. This means we have to ask the perlio system for a stdio
1281*0Sstevel@tonic-gateC<FILE *>:
1282*0Sstevel@tonic-gate
1283*0Sstevel@tonic-gate	int
1284*0Sstevel@tonic-gate	perliofputs(s, stream)
1285*0Sstevel@tonic-gate		char *          s
1286*0Sstevel@tonic-gate		OutputStream	stream
1287*0Sstevel@tonic-gate	PREINIT:
1288*0Sstevel@tonic-gate		FILE *fp = PerlIO_findFILE(stream);
1289*0Sstevel@tonic-gate	CODE:
1290*0Sstevel@tonic-gate		if (fp != (FILE*) 0) {
1291*0Sstevel@tonic-gate			RETVAL = fputs(s, fp);
1292*0Sstevel@tonic-gate		} else {
1293*0Sstevel@tonic-gate			RETVAL = -1;
1294*0Sstevel@tonic-gate		}
1295*0Sstevel@tonic-gate	OUTPUT:
1296*0Sstevel@tonic-gate		RETVAL
1297*0Sstevel@tonic-gate
1298*0Sstevel@tonic-gateNote: C<PerlIO_findFILE()> will search the layers for a stdio
1299*0Sstevel@tonic-gatelayer. If it can't find one, it will call C<PerlIO_exportFILE()> to
1300*0Sstevel@tonic-gategenerate a new stdio C<FILE>. Please only call C<PerlIO_exportFILE()> if
1301*0Sstevel@tonic-gateyou want a I<new> C<FILE>. It will generate one on each call and push a
1302*0Sstevel@tonic-gatenew stdio layer. So don't call it repeatedly on the same
1303*0Sstevel@tonic-gatefile. C<PerlIO()>_findFILE will retrieve the stdio layer once it has been
1304*0Sstevel@tonic-gategenerated by C<PerlIO_exportFILE()>.
1305*0Sstevel@tonic-gate
1306*0Sstevel@tonic-gateThis applies to the perlio system only. For versions before 5.7,
1307*0Sstevel@tonic-gateC<PerlIO_exportFILE()> is equivalent to C<PerlIO_findFILE()>.
1308*0Sstevel@tonic-gate
1309*0Sstevel@tonic-gate=head2 Troubleshooting these Examples
1310*0Sstevel@tonic-gate
1311*0Sstevel@tonic-gateAs mentioned at the top of this document, if you are having problems with
1312*0Sstevel@tonic-gatethese example extensions, you might see if any of these help you.
1313*0Sstevel@tonic-gate
1314*0Sstevel@tonic-gate=over 4
1315*0Sstevel@tonic-gate
1316*0Sstevel@tonic-gate=item *
1317*0Sstevel@tonic-gate
1318*0Sstevel@tonic-gateIn versions of 5.002 prior to the gamma version, the test script in Example
1319*0Sstevel@tonic-gate1 will not function properly.  You need to change the "use lib" line to
1320*0Sstevel@tonic-gateread:
1321*0Sstevel@tonic-gate
1322*0Sstevel@tonic-gate	use lib './blib';
1323*0Sstevel@tonic-gate
1324*0Sstevel@tonic-gate=item *
1325*0Sstevel@tonic-gate
1326*0Sstevel@tonic-gateIn versions of 5.002 prior to version 5.002b1h, the test.pl file was not
1327*0Sstevel@tonic-gateautomatically created by h2xs.  This means that you cannot say "make test"
1328*0Sstevel@tonic-gateto run the test script.  You will need to add the following line before the
1329*0Sstevel@tonic-gate"use extension" statement:
1330*0Sstevel@tonic-gate
1331*0Sstevel@tonic-gate	use lib './blib';
1332*0Sstevel@tonic-gate
1333*0Sstevel@tonic-gate=item *
1334*0Sstevel@tonic-gate
1335*0Sstevel@tonic-gateIn versions 5.000 and 5.001, instead of using the above line, you will need
1336*0Sstevel@tonic-gateto use the following line:
1337*0Sstevel@tonic-gate
1338*0Sstevel@tonic-gate	BEGIN { unshift(@INC, "./blib") }
1339*0Sstevel@tonic-gate
1340*0Sstevel@tonic-gate=item *
1341*0Sstevel@tonic-gate
1342*0Sstevel@tonic-gateThis document assumes that the executable named "perl" is Perl version 5.
1343*0Sstevel@tonic-gateSome systems may have installed Perl version 5 as "perl5".
1344*0Sstevel@tonic-gate
1345*0Sstevel@tonic-gate=back
1346*0Sstevel@tonic-gate
1347*0Sstevel@tonic-gate=head1 See also
1348*0Sstevel@tonic-gate
1349*0Sstevel@tonic-gateFor more information, consult L<perlguts>, L<perlapi>, L<perlxs>, L<perlmod>,
1350*0Sstevel@tonic-gateand L<perlpod>.
1351*0Sstevel@tonic-gate
1352*0Sstevel@tonic-gate=head1 Author
1353*0Sstevel@tonic-gate
1354*0Sstevel@tonic-gateJeff Okamoto <F<okamoto@corp.hp.com>>
1355*0Sstevel@tonic-gate
1356*0Sstevel@tonic-gateReviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig,
1357*0Sstevel@tonic-gateand Tim Bunce.
1358*0Sstevel@tonic-gate
1359*0Sstevel@tonic-gatePerlIO material contributed by Lupe Christoph, with some clarification
1360*0Sstevel@tonic-gateby Nick Ing-Simmons.
1361*0Sstevel@tonic-gate
1362*0Sstevel@tonic-gate=head2 Last Changed
1363*0Sstevel@tonic-gate
1364*0Sstevel@tonic-gate2002/05/08
1365