perlxstut.pod

来自「MSYS在windows下模拟了一个类unix的终端」· POD 代码 · 共 1,264 行 · 第 1/4 页

POD
1,264
字号
=head1 NAMEperlXStut - Tutorial for writing XSUBs=head1 DESCRIPTIONThis tutorial will educate the reader on the steps involved in creatinga Perl extension.  The reader is assumed to have access to L<perlguts>,L<perlapi> 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 becompletely explained until later in the tutorial in order to slowly easethe reader into building extensions.This tutorial was written from a Unix point of view.  Where I know themto be otherwise different for other platforms (e.g. Win32), I will listthem.  If you find something that was missed, please let me know.=head1 SPECIAL NOTES=head2 makeThis tutorial assumes that the make program that Perl is configured touse is called C<make>.  Instead of running "make" in the examples thatfollow, you may have to substitute whatever make program Perl has beenconfigured to use.  Running B<perl -V:make> should tell you what it is.=head2 Version caveatWhen writing a Perl extension for general consumption, one should expect thatthe extension will be used with versions of Perl different from theversion available on your machine.  Since you are reading this document,the version of Perl on your machine is probably 5.005 or later, but the usersof your extension may have more ancient versions.To understand what kinds of incompatibilities one may expect, and in the rarecase that the version of Perl on your machine is older than this document,see the section on "Troubleshooting these Examples" for more information.If your extension uses some features of Perl which are not available on olderreleases of Perl, your users would appreciate an early meaningful warning.You would probably put this information into the F<README> file, but nowadaysinstallation of extensions may be performed automatically, guided by F<CPAN.pm>module or other tools.In MakeMaker-based installations, F<Makefile.PL> provides the earliestopportunity to perform version checks.  One can put something like thisin F<Makefile.PL> for this purpose:    eval { require 5.007 }        or die <<EOD;    ############    ### This module uses frobnication framework which is not available before    ### version 5.007 of Perl.  Upgrade your Perl before installing Kara::Mba.    ############    EOD=head2 Dynamic Loading versus Static LoadingIt is commonly thought that if a system does not have the capability todynamically load a library, you cannot build XSUBs.  This is incorrect.You I<can> build them, but you must link the XSUBs subroutines with therest of Perl, creating a new executable.  This situation is similar toPerl 4.This tutorial can still be used on such a system.  The XSUB build mechanismwill check the system and build a dynamically-loadable library if possible,or else a static library and then, optionally, a new statically-linkedexecutable with that static library linked in.Should you wish to build a statically-linked executable on a system whichcan dynamically load libraries, you may, in all the following examples,where the command "C<make>" with no arguments is executed, run the command"C<make perl>" instead.If you have generated such a statically-linked executable by choice, theninstead of saying "C<make test>", you should say "C<make test_static>".On systems that cannot build dynamically-loadable libraries at all, simplysaying "C<make test>" is sufficient.=head1 TUTORIALNow let's go on with the show!=head2 EXAMPLE 1Our first extension will be very simple.  When we call the routine in theextension, 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 workingdirectory.  Several files will be created in the Mytest dir, includingMANIFEST, Makefile.PL, Mytest.pm, Mytest.xs, test.pl, and Changes.The MANIFEST file contains the names of all the files just created in theMytest directory.The file Makefile.PL should look something like this:	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;	use strict;        use warnings;	require Exporter;	require DynaLoader;	our @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.	our @EXPORT = qw(	);	our $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!The rest of the .pm file contains sample code for providing documentation forthe extension.Finally, the Mytest.xs file should look something like this:	#include "EXTERN.h"	#include "perl.h"	#include "XSUB.h"	MODULE = Mytest		PACKAGE = MytestLet's edit the .xs file by adding this to the end of the file:	void	hello()	    CODE:		printf("Hello, world!\n");It is okay for the lines starting at the "CODE:" line to not be indented.However, for readability purposes, it is suggested that you indent CODE:one level and the lines following one more level.Now we'll run "C<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 (somelong lines have been shortened for clarity and some extraneous lines havebeen deleted):	% make	umask 0 && cp Mytest.pm ./blib/Mytest.pm	perl xsubpp -typemap typemap Mytest.xs >Mytest.tc && mv Mytest.tc Mytest.c	Please specify prototyping behavior for Mytest.xs (see perlxs manual)	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	Manifying ./blib/man3/Mytest.3	%You can safely ignore the line about "prototyping behavior" - it isexplained in the section "The PROTOTYPES: Keyword" in L<perlxs>.If you are on a Win32 system, and the build process fails with linkererrors for functions in the C library, check if your Perl is configuredto use PerlCRT (running B<perl -V:libc> should show you if this is thecase).  If Perl is configured to use PerlCRT, you have to make surePerlCRT.lib is copied to the same location that msvcrt.lib lives in,so that the compiler can find it on its own.  msvcrt.lib is usuallyfound in the Visual C compiler's lib directory (e.g. C:/DevStudio/VC/lib).Perl has its own special way of easily writing test scripts, but for thisexample only, we'll create our own test script.  Create a file called hellothat looks like this:	#! /opt/perl5/bin/perl	use ExtUtils::testlib;	use Mytest;	Mytest::hello();Now we make the script executable (C<chmod -x hello>), run the scriptand we should see the following output:	% ./hello	Hello, world!	%=head2 EXAMPLE 2Now let's add to our extension a subroutine that will take a single numericargument as input and return 0 if the number is even or 1 if the numberis odd.Add the following to the end of Mytest.xs:	int	is_even(input)		int	input	    CODE:		RETVAL = (input % 2 == 0);	    OUTPUT:		RETVALThere does not need to be white space at the start of the "C<int input>"line, but it is useful for improving readability.  Placing a semi-colon atthe end of that line is also optional.  Any amount and kind of white spacemay be placed between the "C<int>" and "C<input>".Now re-run make to rebuild our new shared library.Now perform the same steps as before, generating a Makefile from theMakefile.PL file, and running make.In order to test that our extension works, we now need to look at thefile test.pl.  This file is set up to imitate the same kind of testingstructure that Perl itself has.  Within the test script, you perform anumber of tests to confirm the behavior of the extension, printing "ok"when the test is correct, "not ok" when it is not.  Change the printstatement in the BEGIN block to print "1..4", and add the following codeto 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 "C<make test>".  Youshould see output that looks something like this:	% make test	PERL_DL_NONLAZY=1 /opt/perl5.004/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 laterexamples we'll see how we can use h2xs to read header files and generatetemplates to connect to C routines.h2xs creates a number of files in the extension directory.  The fileMakefile.PL is a perl script which will generate a true Makefile to buildthe extension.  We'll take a closer look at it later.The .pm and .xs files contain the meat of the extension.  The .xs file holdsthe C routines that make up the extension.  The .pm file contains routinesthat tell Perl how to load your extension.Generating the Makefile and running C<make> created a directory called blib(which stands for "build library") in the current working directory.  Thisdirectory will contain the shared library that we will build.  Once we havetested it, we can install it into its final location.Invoking the test script via "C<make test>" did something very important.It invoked perl with all those C<-I> arguments so that it could find thevarious files that are part of the extension.  It is I<very> important thatwhile you are still testing extensions that you use "C<make test>".  If youtry to run the test script all by itself, you will get a fatal error.Another reason it is important to use "C<make test>" to run your testscript is that if you are testing an upgrade to an already-existing version,using "C<make test>" insures that you will test your new extension, not thealready-existing version.When Perl sees a C<use extension;>, it searches for a file with the same nameas the C<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 theC<@INC> array.In our case, Mytest.pm tells perl that it will need the Exporter and DynamicLoader extensions.  It then sets the C<@ISA> and C<@EXPORT> arrays and theC<$VERSION> scalar; finally it tells perl to bootstrap the module.  Perlwill call its dynamic loader routine (if there is one) and load the sharedlibrary.The two arrays C<@ISA> and C<@EXPORT> are very important.  The C<@ISA>array contains a list of other packages in which to search for methods (orsubroutines) that do not exist in the current package.  This is usuallyonly important for object-oriented extensions (which we will talk aboutmuch later), and so usually doesn't need to be modified.The C<@EXPORT> array tells Perl which of the extension's variables and

⌨️ 快捷键说明

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