perlxstut.pod

来自「ARM上的如果你对底层感兴趣」· POD 代码 · 共 740 行 · 第 1/2 页

POD
740
字号
=head1 NAME

perlXStut - Tutorial for XSUBs

=head1 DESCRIPTION

This tutorial will educate the reader on the steps involved in creating
a Perl extension.  The reader is assumed to have access to L<perlguts> and
L<perlxs>.

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

=head2 VERSION CAVEAT

This tutorial tries hard to keep up with the latest development versions
of Perl.  This often means that it is sometimes in advance of the latest
released version of Perl, and that certain features described here might
not work on earlier versions.  This section will keep track of when various
features were added to Perl 5.

=over 4

=item *

In versions of Perl 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 Perl 5.002 prior to version beta 3, the line in the .xs file
about "PROTOTYPES: DISABLE" will cause a compiler error.  Simply remove that
line from the file.

=item *

In versions of Perl 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

=head2 DYNAMIC VERSUS STATIC

It is commonly thought that if a system does not have the capability to
load a library dynamically, you cannot build XSUBs.  This is incorrect.
You I<can> build them, but you must link the XSUB's subroutines with the
rest of Perl, creating a new executable.  This situation is similar to
Perl 4.

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

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

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

=head2 EXAMPLE 1

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

Run C<h2xs -A -n Mytest>.  This creates a directory named Mytest, possibly under
ext/ if that directory exists in the current working directory.  Several files
will be created in the Mytest dir, including MANIFEST, Makefile.PL, Mytest.pm,
Mytest.xs, test.pl, and Changes.

The MANIFEST file contains the names of all the files created.

The file Makefile.PL should look something like this:

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

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

	package Mytest;

	require Exporter;
	require DynaLoader;

	@ISA = qw(Exporter DynaLoader);
	# Items to export into callers namespace by default. Note: do not export
	# names by default without a very good reason. Use EXPORT_OK instead.
	# Do not simply export all your public functions/methods/constants.
	@EXPORT = qw(

	);
	$VERSION = '0.01';

	bootstrap Mytest $VERSION;

	# Preloaded methods go here.

	# Autoload methods go after __END__, and are processed by the autosplit program.

	1;
	__END__
	# Below is the stub of documentation for your module. You better edit it!

And the Mytest.xs file should look something like this:

	#ifdef __cplusplus
	extern "C" {
	#endif
	#include "EXTERN.h"
	#include "perl.h"
	#include "XSUB.h"
	#ifdef __cplusplus
	}
	#endif

	PROTOTYPES: DISABLE

	MODULE = Mytest		PACKAGE = Mytest

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

	void
	hello()
		CODE:
		printf("Hello, world!\n");

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

	% perl Makefile.PL
	Checking if your kit is complete...
	Looks good
	Writing Makefile for Mytest
	%

Now, running make will produce output that looks something like this
(some long lines shortened for clarity):

	% make
	umask 0 && cp Mytest.pm ./blib/Mytest.pm
	perl xsubpp -typemap typemap Mytest.xs >Mytest.tc && mv Mytest.tc Mytest.c
	cc -c Mytest.c
	Running Mkbootstrap for Mytest ()
	chmod 644 Mytest.bs
	LD_RUN_PATH="" ld -o ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl -b Mytest.o
	chmod 755 ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl
	cp Mytest.bs ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
	chmod 644 ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs

Now, although there is already a test.pl template ready for us, for this
example only, we'll create a special test script.  Create a file called hello
that looks like this:

	#! /opt/perl5/bin/perl

	use ExtUtils::testlib;

	use Mytest;

	Mytest::hello();

Now we run the script and we should see the following output:

	% perl hello
	Hello, world!
	%

=head2 EXAMPLE 2

Now let's add to our extension a subroutine that will take a single argument
and return 1 if the argument is even, 0 if the argument is odd.

Add the following to the end of Mytest.xs:

	int
	is_even(input)
		int	input
		CODE:
		RETVAL = (input % 2 == 0);
		OUTPUT:
		RETVAL

There does not need to be white space at the start of the "int input" line,
but it is useful for improving readability.  The semi-colon at the end of
that line is also optional.

Any white space may be between the "int" and "input".  It is also okay for
the four lines starting at the "CODE:" line to not be indented.  However,
for readability purposes, it is suggested that you indent them 8 spaces
(or one normal tab stop).

Now rerun make to rebuild our new shared library.

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

To test that our extension works, we now need to look at the
file test.pl.  This file is set up to imitate the same kind of testing
structure that Perl itself has.  Within the test script, you perform a
number of tests to confirm the behavior of the extension, printing "ok"
when the test is correct, "not ok" when it is not.  Change the print
statement in the BEGIN block to print "1..4", and add the following code
to the end of the file:

	print &Mytest::is_even(0) == 1 ? "ok 2" : "not ok 2", "\n";
	print &Mytest::is_even(1) == 0 ? "ok 3" : "not ok 3", "\n";
	print &Mytest::is_even(2) == 1 ? "ok 4" : "not ok 4", "\n";

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

	% make test
	PERL_DL_NONLAZY=1 /opt/perl5.002b2/bin/perl (lots of -I arguments) test.pl
	1..4
	ok 1
	ok 2
	ok 3
	ok 4
	%

=head2 WHAT HAS GONE ON?

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

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

The files E<lt>extensionE<gt>.pm and E<lt>extensionE<gt>.xs contain the meat
of the extension.
The .xs file holds the C routines that make up the extension.  The .pm file
contains routines that tell Perl how to load your extension.

Generating and invoking the Makefile created a directory blib (which stands
for "build library") in the current working directory.  This directory will
contain the shared library that we will build.  Once we have tested it, we
can install it into its final location.

Invoking the test script via "make test" did something very important.  It
invoked perl with all those C<-I> arguments so that it could find the various
files that are part of the extension.

It is I<very> important that while you are still testing extensions that
you use "make test".  If you try to run the test script all by itself, you
will get a fatal error.

Another reason it is important to use "make test" to run your test script
is that if you are testing an upgrade to an already-existing version, using
"make test" insures that you use your new extension, not the already-existing
version.

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

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

The two arrays that are set in the .pm file are very important.  The @ISA
array contains a list of other packages in which to search for methods (or
subroutines) that do not exist in the current package.  The @EXPORT array
tells Perl which of the extension's routines should be placed into the
calling package's namespace.

It's important to select what to export carefully.  Do NOT export method names
and do NOT export anything else I<by default> without a good reason.

As a general rule, if the module is trying to be object-oriented then don't
export anything.  If it's just a collection of functions then you can export
any of the functions via another array, called @EXPORT_OK.

See L<perlmod> for more information.

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

=head2 WRITING GOOD TEST SCRIPTS

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

By running "make test", you ensure that your test.pl script runs and uses
the correct version of your extension.  If you have many test cases, you
might want to copy Perl's test style.  Create a directory named "t", and
ensure all your test files end with the suffix ".t".  The Makefile will
properly run all these test files.


=head2 EXAMPLE 3

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

Add the following to the end of Mytest.xs:

	void
	round(arg)
		double  arg
		CODE:
		if (arg > 0.0) {
			arg = floor(arg + 0.5);
		} else if (arg < 0.0) {
			arg = ceil(arg - 0.5);
		} else {
			arg = 0.0;
		}
		OUTPUT:
		arg

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

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

Generate the Makefile and run make.  Change the BEGIN block to print out
"1..9" and add the following to test.pl:

	$i = -1.5; &Mytest::round($i); print $i == -2.0 ? "ok 5" : "not ok 5", "\n";
	$i = -1.1; &Mytest::round($i); print $i == -1.0 ? "ok 6" : "not ok 6", "\n";
	$i = 0.0; &Mytest::round($i); print $i == 0.0 ? "ok 7" : "not ok 7", "\n";
	$i = 0.5; &Mytest::round($i); print $i == 1.0 ? "ok 8" : "not ok 8", "\n";
	$i = 1.2; &Mytest::round($i); print $i == 1.0 ? "ok 9" : "not ok 9", "\n";

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

You might be wondering if you can round a constant.  To see what happens, add
the following line to test.pl temporarily:

	&Mytest::round(3);

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?