Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1263 lines
47 KiB

  1. =head1 NAME
  2. perlXStut - Tutorial for writing XSUBs
  3. =head1 DESCRIPTION
  4. This tutorial will educate the reader on the steps involved in creating
  5. a Perl extension. The reader is assumed to have access to L<perlguts>,
  6. L<perlapi> and L<perlxs>.
  7. This tutorial starts with very simple examples and becomes more complex,
  8. with each new example adding new features. Certain concepts may not be
  9. completely explained until later in the tutorial in order to slowly ease
  10. the reader into building extensions.
  11. This tutorial was written from a Unix point of view. Where I know them
  12. to be otherwise different for other platforms (e.g. Win32), I will list
  13. them. If you find something that was missed, please let me know.
  14. =head1 SPECIAL NOTES
  15. =head2 make
  16. This tutorial assumes that the make program that Perl is configured to
  17. use is called C<make>. Instead of running "make" in the examples that
  18. follow, you may have to substitute whatever make program Perl has been
  19. configured to use. Running B<perl -V:make> should tell you what it is.
  20. =head2 Version caveat
  21. When writing a Perl extension for general consumption, one should expect that
  22. the extension will be used with versions of Perl different from the
  23. version available on your machine. Since you are reading this document,
  24. the version of Perl on your machine is probably 5.005 or later, but the users
  25. of your extension may have more ancient versions.
  26. To understand what kinds of incompatibilities one may expect, and in the rare
  27. case that the version of Perl on your machine is older than this document,
  28. see the section on "Troubleshooting these Examples" for more information.
  29. If your extension uses some features of Perl which are not available on older
  30. releases of Perl, your users would appreciate an early meaningful warning.
  31. You would probably put this information into the F<README> file, but nowadays
  32. installation of extensions may be performed automatically, guided by F<CPAN.pm>
  33. module or other tools.
  34. In MakeMaker-based installations, F<Makefile.PL> provides the earliest
  35. opportunity to perform version checks. One can put something like this
  36. in F<Makefile.PL> for this purpose:
  37. eval { require 5.007 }
  38. or die <<EOD;
  39. ############
  40. ### This module uses frobnication framework which is not available before
  41. ### version 5.007 of Perl. Upgrade your Perl before installing Kara::Mba.
  42. ############
  43. EOD
  44. =head2 Dynamic Loading versus Static Loading
  45. It is commonly thought that if a system does not have the capability to
  46. dynamically load a library, you cannot build XSUBs. This is incorrect.
  47. You I<can> build them, but you must link the XSUBs subroutines with the
  48. rest of Perl, creating a new executable. This situation is similar to
  49. Perl 4.
  50. This tutorial can still be used on such a system. The XSUB build mechanism
  51. will check the system and build a dynamically-loadable library if possible,
  52. or else a static library and then, optionally, a new statically-linked
  53. executable with that static library linked in.
  54. Should you wish to build a statically-linked executable on a system which
  55. can dynamically load libraries, you may, in all the following examples,
  56. where the command "C<make>" with no arguments is executed, run the command
  57. "C<make perl>" instead.
  58. If you have generated such a statically-linked executable by choice, then
  59. instead of saying "C<make test>", you should say "C<make test_static>".
  60. On systems that cannot build dynamically-loadable libraries at all, simply
  61. saying "C<make test>" is sufficient.
  62. =head1 TUTORIAL
  63. Now let's go on with the show!
  64. =head2 EXAMPLE 1
  65. Our first extension will be very simple. When we call the routine in the
  66. extension, it will print out a well-known message and return.
  67. Run "C<h2xs -A -n Mytest>". This creates a directory named Mytest,
  68. possibly under ext/ if that directory exists in the current working
  69. directory. Several files will be created in the Mytest dir, including
  70. MANIFEST, Makefile.PL, Mytest.pm, Mytest.xs, test.pl, and Changes.
  71. The MANIFEST file contains the names of all the files just created in the
  72. Mytest directory.
  73. The file Makefile.PL should look something like this:
  74. use ExtUtils::MakeMaker;
  75. # See lib/ExtUtils/MakeMaker.pm for details of how to influence
  76. # the contents of the Makefile that is written.
  77. WriteMakefile(
  78. NAME => 'Mytest',
  79. VERSION_FROM => 'Mytest.pm', # finds $VERSION
  80. LIBS => [''], # e.g., '-lm'
  81. DEFINE => '', # e.g., '-DHAVE_SOMETHING'
  82. INC => '', # e.g., '-I/usr/include/other'
  83. );
  84. The file Mytest.pm should start with something like this:
  85. package Mytest;
  86. use strict;
  87. use warnings;
  88. require Exporter;
  89. require DynaLoader;
  90. our @ISA = qw(Exporter DynaLoader);
  91. # Items to export into callers namespace by default. Note: do not export
  92. # names by default without a very good reason. Use EXPORT_OK instead.
  93. # Do not simply export all your public functions/methods/constants.
  94. our @EXPORT = qw(
  95. );
  96. our $VERSION = '0.01';
  97. bootstrap Mytest $VERSION;
  98. # Preloaded methods go here.
  99. # Autoload methods go after __END__, and are processed by the autosplit program.
  100. 1;
  101. __END__
  102. # Below is the stub of documentation for your module. You better edit it!
  103. The rest of the .pm file contains sample code for providing documentation for
  104. the extension.
  105. Finally, the Mytest.xs file should look something like this:
  106. #include "EXTERN.h"
  107. #include "perl.h"
  108. #include "XSUB.h"
  109. MODULE = Mytest PACKAGE = Mytest
  110. Let's edit the .xs file by adding this to the end of the file:
  111. void
  112. hello()
  113. CODE:
  114. printf("Hello, world!\n");
  115. It is okay for the lines starting at the "CODE:" line to not be indented.
  116. However, for readability purposes, it is suggested that you indent CODE:
  117. one level and the lines following one more level.
  118. Now we'll run "C<perl Makefile.PL>". This will create a real Makefile,
  119. which make needs. Its output looks something like:
  120. % perl Makefile.PL
  121. Checking if your kit is complete...
  122. Looks good
  123. Writing Makefile for Mytest
  124. %
  125. Now, running make will produce output that looks something like this (some
  126. long lines have been shortened for clarity and some extraneous lines have
  127. been deleted):
  128. % make
  129. umask 0 && cp Mytest.pm ./blib/Mytest.pm
  130. perl xsubpp -typemap typemap Mytest.xs >Mytest.tc && mv Mytest.tc Mytest.c
  131. Please specify prototyping behavior for Mytest.xs (see perlxs manual)
  132. cc -c Mytest.c
  133. Running Mkbootstrap for Mytest ()
  134. chmod 644 Mytest.bs
  135. LD_RUN_PATH="" ld -o ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl -b Mytest.o
  136. chmod 755 ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl
  137. cp Mytest.bs ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
  138. chmod 644 ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
  139. Manifying ./blib/man3/Mytest.3
  140. %
  141. You can safely ignore the line about "prototyping behavior" - it is
  142. explained in the section "The PROTOTYPES: Keyword" in L<perlxs>.
  143. If you are on a Win32 system, and the build process fails with linker
  144. errors for functions in the C library, check if your Perl is configured
  145. to use PerlCRT (running B<perl -V:libc> should show you if this is the
  146. case). If Perl is configured to use PerlCRT, you have to make sure
  147. PerlCRT.lib is copied to the same location that msvcrt.lib lives in,
  148. so that the compiler can find it on its own. msvcrt.lib is usually
  149. found in the Visual C compiler's lib directory (e.g. C:/DevStudio/VC/lib).
  150. Perl has its own special way of easily writing test scripts, but for this
  151. example only, we'll create our own test script. Create a file called hello
  152. that looks like this:
  153. #! /opt/perl5/bin/perl
  154. use ExtUtils::testlib;
  155. use Mytest;
  156. Mytest::hello();
  157. Now we make the script executable (C<chmod -x hello>), run the script
  158. and we should see the following output:
  159. % ./hello
  160. Hello, world!
  161. %
  162. =head2 EXAMPLE 2
  163. Now let's add to our extension a subroutine that will take a single numeric
  164. argument as input and return 0 if the number is even or 1 if the number
  165. is odd.
  166. Add the following to the end of Mytest.xs:
  167. int
  168. is_even(input)
  169. int input
  170. CODE:
  171. RETVAL = (input % 2 == 0);
  172. OUTPUT:
  173. RETVAL
  174. There does not need to be white space at the start of the "C<int input>"
  175. line, but it is useful for improving readability. Placing a semi-colon at
  176. the end of that line is also optional. Any amount and kind of white space
  177. may be placed between the "C<int>" and "C<input>".
  178. Now re-run make to rebuild our new shared library.
  179. Now perform the same steps as before, generating a Makefile from the
  180. Makefile.PL file, and running make.
  181. In order to test that our extension works, we now need to look at the
  182. file test.pl. This file is set up to imitate the same kind of testing
  183. structure that Perl itself has. Within the test script, you perform a
  184. number of tests to confirm the behavior of the extension, printing "ok"
  185. when the test is correct, "not ok" when it is not. Change the print
  186. statement in the BEGIN block to print "1..4", and add the following code
  187. to the end of the file:
  188. print &Mytest::is_even(0) == 1 ? "ok 2" : "not ok 2", "\n";
  189. print &Mytest::is_even(1) == 0 ? "ok 3" : "not ok 3", "\n";
  190. print &Mytest::is_even(2) == 1 ? "ok 4" : "not ok 4", "\n";
  191. We will be calling the test script through the command "C<make test>". You
  192. should see output that looks something like this:
  193. % make test
  194. PERL_DL_NONLAZY=1 /opt/perl5.004/bin/perl (lots of -I arguments) test.pl
  195. 1..4
  196. ok 1
  197. ok 2
  198. ok 3
  199. ok 4
  200. %
  201. =head2 What has gone on?
  202. The program h2xs is the starting point for creating extensions. In later
  203. examples we'll see how we can use h2xs to read header files and generate
  204. templates to connect to C routines.
  205. h2xs creates a number of files in the extension directory. The file
  206. Makefile.PL is a perl script which will generate a true Makefile to build
  207. the extension. We'll take a closer look at it later.
  208. The .pm and .xs files contain the meat of the extension. The .xs file holds
  209. the C routines that make up the extension. The .pm file contains routines
  210. that tell Perl how to load your extension.
  211. Generating the Makefile and running C<make> created a directory called blib
  212. (which stands for "build library") in the current working directory. This
  213. directory will contain the shared library that we will build. Once we have
  214. tested it, we can install it into its final location.
  215. Invoking the test script via "C<make test>" did something very important.
  216. It invoked perl with all those C<-I> arguments so that it could find the
  217. various files that are part of the extension. It is I<very> important that
  218. while you are still testing extensions that you use "C<make test>". If you
  219. try to run the test script all by itself, you will get a fatal error.
  220. Another reason it is important to use "C<make test>" to run your test
  221. script is that if you are testing an upgrade to an already-existing version,
  222. using "C<make test>" insures that you will test your new extension, not the
  223. already-existing version.
  224. When Perl sees a C<use extension;>, it searches for a file with the same name
  225. as the C<use>'d extension that has a .pm suffix. If that file cannot be found,
  226. Perl dies with a fatal error. The default search path is contained in the
  227. C<@INC> array.
  228. In our case, Mytest.pm tells perl that it will need the Exporter and Dynamic
  229. Loader extensions. It then sets the C<@ISA> and C<@EXPORT> arrays and the
  230. C<$VERSION> scalar; finally it tells perl to bootstrap the module. Perl
  231. will call its dynamic loader routine (if there is one) and load the shared
  232. library.
  233. The two arrays C<@ISA> and C<@EXPORT> are very important. The C<@ISA>
  234. array contains a list of other packages in which to search for methods (or
  235. subroutines) that do not exist in the current package. This is usually
  236. only important for object-oriented extensions (which we will talk about
  237. much later), and so usually doesn't need to be modified.
  238. The C<@EXPORT> array tells Perl which of the extension's variables and
  239. subroutines should be placed into the calling package's namespace. Because
  240. you don't know if the user has already used your variable and subroutine
  241. names, it's vitally important to carefully select what to export. Do I<not>
  242. export method or variable names I<by default> without a good reason.
  243. As a general rule, if the module is trying to be object-oriented then don't
  244. export anything. If it's just a collection of functions and variables, then
  245. you can export them via another array, called C<@EXPORT_OK>. This array
  246. does not automatically place its subroutine and variable names into the
  247. namespace unless the user specifically requests that this be done.
  248. See L<perlmod> for more information.
  249. The C<$VERSION> variable is used to ensure that the .pm file and the shared
  250. library are "in sync" with each other. Any time you make changes to
  251. the .pm or .xs files, you should increment the value of this variable.
  252. =head2 Writing good test scripts
  253. The importance of writing good test scripts cannot be overemphasized. You
  254. should closely follow the "ok/not ok" style that Perl itself uses, so that
  255. it is very easy and unambiguous to determine the outcome of each test case.
  256. When you find and fix a bug, make sure you add a test case for it.
  257. By running "C<make test>", you ensure that your test.pl script runs and uses
  258. the correct version of your extension. If you have many test cases, you
  259. might want to copy Perl's test style. Create a directory named "t" in the
  260. extension's directory and append the suffix ".t" to the names of your test
  261. files. When you run "C<make test>", all of these test files will be executed.
  262. =head2 EXAMPLE 3
  263. Our third extension will take one argument as its input, round off that
  264. value, and set the I<argument> to the rounded value.
  265. Add the following to the end of Mytest.xs:
  266. void
  267. round(arg)
  268. double arg
  269. CODE:
  270. if (arg > 0.0) {
  271. arg = floor(arg + 0.5);
  272. } else if (arg < 0.0) {
  273. arg = ceil(arg - 0.5);
  274. } else {
  275. arg = 0.0;
  276. }
  277. OUTPUT:
  278. arg
  279. Edit the Makefile.PL file so that the corresponding line looks like this:
  280. 'LIBS' => ['-lm'], # e.g., '-lm'
  281. Generate the Makefile and run make. Change the BEGIN block to print
  282. "1..9" and add the following to test.pl:
  283. $i = -1.5; &Mytest::round($i); print $i == -2.0 ? "ok 5" : "not ok 5", "\n";
  284. $i = -1.1; &Mytest::round($i); print $i == -1.0 ? "ok 6" : "not ok 6", "\n";
  285. $i = 0.0; &Mytest::round($i); print $i == 0.0 ? "ok 7" : "not ok 7", "\n";
  286. $i = 0.5; &Mytest::round($i); print $i == 1.0 ? "ok 8" : "not ok 8", "\n";
  287. $i = 1.2; &Mytest::round($i); print $i == 1.0 ? "ok 9" : "not ok 9", "\n";
  288. Running "C<make test>" should now print out that all nine tests are okay.
  289. Notice that in these new test cases, the argument passed to round was a
  290. scalar variable. You might be wondering if you can round a constant or
  291. literal. To see what happens, temporarily add the following line to test.pl:
  292. &Mytest::round(3);
  293. Run "C<make test>" and notice that Perl dies with a fatal error. Perl won't
  294. let you change the value of constants!
  295. =head2 What's new here?
  296. =over 4
  297. =item *
  298. We've made some changes to Makefile.PL. In this case, we've specified an
  299. extra library to be linked into the extension's shared library, the math
  300. library libm in this case. We'll talk later about how to write XSUBs that
  301. can call every routine in a library.
  302. =item *
  303. The value of the function is not being passed back as the function's return
  304. value, but by changing the value of the variable that was passed into the
  305. function. You might have guessed that when you saw that the return value
  306. of round is of type "void".
  307. =back
  308. =head2 Input and Output Parameters
  309. You specify the parameters that will be passed into the XSUB on the line(s)
  310. after you declare the function's return value and name. Each input parameter
  311. line starts with optional white space, and may have an optional terminating
  312. semicolon.
  313. The list of output parameters occurs at the very end of the function, just
  314. before after the OUTPUT: directive. The use of RETVAL tells Perl that you
  315. wish to send this value back as the return value of the XSUB function. In
  316. Example 3, we wanted the "return value" placed in the original variable
  317. which we passed in, so we listed it (and not RETVAL) in the OUTPUT: section.
  318. =head2 The XSUBPP Program
  319. The B<xsubpp> program takes the XS code in the .xs file and translates it into
  320. C code, placing it in a file whose suffix is .c. The C code created makes
  321. heavy use of the C functions within Perl.
  322. =head2 The TYPEMAP file
  323. The B<xsubpp> program uses rules to convert from Perl's data types (scalar,
  324. array, etc.) to C's data types (int, char, etc.). These rules are stored
  325. in the typemap file ($PERLLIB/ExtUtils/typemap). This file is split into
  326. three parts.
  327. The first section maps various C data types to a name, which corresponds
  328. somewhat with the various Perl types. The second section contains C code
  329. which B<xsubpp> uses to handle input parameters. The third section contains
  330. C code which B<xsubpp> uses to handle output parameters.
  331. Let's take a look at a portion of the .c file created for our extension.
  332. The file name is Mytest.c:
  333. XS(XS_Mytest_round)
  334. {
  335. dXSARGS;
  336. if (items != 1)
  337. croak("Usage: Mytest::round(arg)");
  338. {
  339. double arg = (double)SvNV(ST(0)); /* XXXXX */
  340. if (arg > 0.0) {
  341. arg = floor(arg + 0.5);
  342. } else if (arg < 0.0) {
  343. arg = ceil(arg - 0.5);
  344. } else {
  345. arg = 0.0;
  346. }
  347. sv_setnv(ST(0), (double)arg); /* XXXXX */
  348. }
  349. XSRETURN(1);
  350. }
  351. Notice the two lines commented with "XXXXX". If you check the first section
  352. of the typemap file, you'll see that doubles are of type T_DOUBLE. In the
  353. INPUT section, an argument that is T_DOUBLE is assigned to the variable
  354. arg by calling the routine SvNV on something, then casting it to double,
  355. then assigned to the variable arg. Similarly, in the OUTPUT section,
  356. once arg has its final value, it is passed to the sv_setnv function to
  357. be passed back to the calling subroutine. These two functions are explained
  358. in L<perlguts>; we'll talk more later about what that "ST(0)" means in the
  359. section on the argument stack.
  360. =head2 Warning about Output Arguments
  361. In general, it's not a good idea to write extensions that modify their input
  362. parameters, as in Example 3. Instead, you should probably return multiple
  363. values in an array and let the caller handle them (we'll do this in a later
  364. example). However, in order to better accommodate calling pre-existing C
  365. routines, which often do modify their input parameters, this behavior is
  366. tolerated.
  367. =head2 EXAMPLE 4
  368. In this example, we'll now begin to write XSUBs that will interact with
  369. pre-defined C libraries. To begin with, we will build a small library of
  370. our own, then let h2xs write our .pm and .xs files for us.
  371. Create a new directory called Mytest2 at the same level as the directory
  372. Mytest. In the Mytest2 directory, create another directory called mylib,
  373. and cd into that directory.
  374. Here we'll create some files that will generate a test library. These will
  375. include a C source file and a header file. We'll also create a Makefile.PL
  376. in this directory. Then we'll make sure that running make at the Mytest2
  377. level will automatically run this Makefile.PL file and the resulting Makefile.
  378. In the mylib directory, create a file mylib.h that looks like this:
  379. #define TESTVAL 4
  380. extern double foo(int, long, const char*);
  381. Also create a file mylib.c that looks like this:
  382. #include <stdlib.h>
  383. #include "./mylib.h"
  384. double
  385. foo(int a, long b, const char *c)
  386. {
  387. return (a + b + atof(c) + TESTVAL);
  388. }
  389. And finally create a file Makefile.PL that looks like this:
  390. use ExtUtils::MakeMaker;
  391. $Verbose = 1;
  392. WriteMakefile(
  393. NAME => 'Mytest2::mylib',
  394. SKIP => [qw(all static static_lib dynamic dynamic_lib)],
  395. clean => {'FILES' => 'libmylib$(LIBEEXT)'},
  396. );
  397. sub MY::top_targets {
  398. '
  399. all :: static
  400. pure_all :: static
  401. static :: libmylib$(LIB_EXT)
  402. libmylib$(LIB_EXT): $(O_FILES)
  403. $(AR) cr libmylib$(LIB_EXT) $(O_FILES)
  404. $(RANLIB) libmylib$(LIB_EXT)
  405. ';
  406. }
  407. Make sure you use a tab and not spaces on the lines beginning with "$(AR)"
  408. and "$(RANLIB)". Make will not function properly if you use spaces.
  409. It has also been reported that the "cr" argument to $(AR) is unnecessary
  410. on Win32 systems.
  411. We will now create the main top-level Mytest2 files. Change to the directory
  412. above Mytest2 and run the following command:
  413. % h2xs -O -n Mytest2 ./Mytest2/mylib/mylib.h
  414. This will print out a warning about overwriting Mytest2, but that's okay.
  415. Our files are stored in Mytest2/mylib, and will be untouched.
  416. The normal Makefile.PL that h2xs generates doesn't know about the mylib
  417. directory. We need to tell it that there is a subdirectory and that we
  418. will be generating a library in it. Let's add the argument MYEXTLIB to
  419. the WriteMakefile call so that it looks like this:
  420. WriteMakefile(
  421. 'NAME' => 'Mytest2',
  422. 'VERSION_FROM' => 'Mytest2.pm', # finds $VERSION
  423. 'LIBS' => [''], # e.g., '-lm'
  424. 'DEFINE' => '', # e.g., '-DHAVE_SOMETHING'
  425. 'INC' => '', # e.g., '-I/usr/include/other'
  426. 'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)',
  427. );
  428. and then at the end add a subroutine (which will override the pre-existing
  429. subroutine). Remember to use a tab character to indent the line beginning
  430. with "cd"!
  431. sub MY::postamble {
  432. '
  433. $(MYEXTLIB): mylib/Makefile
  434. cd mylib && $(MAKE) $(PASSTHRU)
  435. ';
  436. }
  437. Let's also fix the MANIFEST file so that it accurately reflects the contents
  438. of our extension. The single line that says "mylib" should be replaced by
  439. the following three lines:
  440. mylib/Makefile.PL
  441. mylib/mylib.c
  442. mylib/mylib.h
  443. To keep our namespace nice and unpolluted, edit the .pm file and change
  444. the variable C<@EXPORT> to C<@EXPORT_OK>. Finally, in the
  445. .xs file, edit the #include line to read:
  446. #include "mylib/mylib.h"
  447. And also add the following function definition to the end of the .xs file:
  448. double
  449. foo(a,b,c)
  450. int a
  451. long b
  452. const char * c
  453. OUTPUT:
  454. RETVAL
  455. Now we also need to create a typemap file because the default Perl doesn't
  456. currently support the const char * type. Create a file called typemap in
  457. the Mytest2 directory and place the following in it:
  458. const char * T_PV
  459. Now run perl on the top-level Makefile.PL. Notice that it also created a
  460. Makefile in the mylib directory. Run make and watch that it does cd into
  461. the mylib directory and run make in there as well.
  462. Now edit the test.pl script and change the BEGIN block to print "1..4",
  463. and add the following lines to the end of the script:
  464. print &Mytest2::foo(1, 2, "Hello, world!") == 7 ? "ok 2\n" : "not ok 2\n";
  465. print &Mytest2::foo(1, 2, "0.0") == 7 ? "ok 3\n" : "not ok 3\n";
  466. print abs(&Mytest2::foo(0, 0, "-3.4") - 0.6) <= 0.01 ? "ok 4\n" : "not ok 4\n";
  467. (When dealing with floating-point comparisons, it is best to not check for
  468. equality, but rather that the difference between the expected and actual
  469. result is below a certain amount (called epsilon) which is 0.01 in this case)
  470. Run "C<make test>" and all should be well.
  471. =head2 What has happened here?
  472. Unlike previous examples, we've now run h2xs on a real include file. This
  473. has caused some extra goodies to appear in both the .pm and .xs files.
  474. =over 4
  475. =item *
  476. In the .xs file, there's now a #include directive with the absolute path to
  477. the mylib.h header file. We changed this to a relative path so that we
  478. could move the extension directory if we wanted to.
  479. =item *
  480. There's now some new C code that's been added to the .xs file. The purpose
  481. of the C<constant> routine is to make the values that are #define'd in the
  482. header file accessible by the Perl script (by calling either C<TESTVAL> or
  483. C<&Mytest2::TESTVAL>). There's also some XS code to allow calls to the
  484. C<constant> routine.
  485. =item *
  486. The .pm file originally exported the name C<TESTVAL> in the C<@EXPORT> array.
  487. This could lead to name clashes. A good rule of thumb is that if the #define
  488. is only going to be used by the C routines themselves, and not by the user,
  489. they should be removed from the C<@EXPORT> array. Alternately, if you don't
  490. mind using the "fully qualified name" of a variable, you could move most
  491. or all of the items from the C<@EXPORT> array into the C<@EXPORT_OK> array.
  492. =item *
  493. If our include file had contained #include directives, these would not have
  494. been processed by h2xs. There is no good solution to this right now.
  495. =item *
  496. We've also told Perl about the library that we built in the mylib
  497. subdirectory. That required only the addition of the C<MYEXTLIB> variable
  498. to the WriteMakefile call and the replacement of the postamble subroutine
  499. to cd into the subdirectory and run make. The Makefile.PL for the
  500. library is a bit more complicated, but not excessively so. Again we
  501. replaced the postamble subroutine to insert our own code. This code
  502. simply specified that the library to be created here was a static archive
  503. library (as opposed to a dynamically loadable library) and provided the
  504. commands to build it.
  505. =back
  506. =head2 Anatomy of .xs file
  507. The .xs file of L<"EXAMPLE 4"> contained some new elements. To understand
  508. the meaning of these elements, pay attention to the line which reads
  509. MODULE = Mytest2 PACKAGE = Mytest2
  510. Anything before this line is plain C code which describes which headers
  511. to include, and defines some convenience functions. No translations are
  512. performed on this part, apart from having embedded POD documentation
  513. skipped over (see L<perlpod>) it goes into the generated output C file as is.
  514. Anything after this line is the description of XSUB functions.
  515. These descriptions are translated by B<xsubpp> into C code which
  516. implements these functions using Perl calling conventions, and which
  517. makes these functions visible from Perl interpreter.
  518. Pay a special attention to the function C<constant>. This name appears
  519. twice in the generated .xs file: once in the first part, as a static C
  520. function, the another time in the second part, when an XSUB interface to
  521. this static C function is defined.
  522. This is quite typical for .xs files: usually the .xs file provides
  523. an interface to an existing C function. Then this C function is defined
  524. somewhere (either in an external library, or in the first part of .xs file),
  525. and a Perl interface to this function (i.e. "Perl glue") is described in the
  526. second part of .xs file. The situation in L<"EXAMPLE 1">, L<"EXAMPLE 2">,
  527. and L<"EXAMPLE 3">, when all the work is done inside the "Perl glue", is
  528. somewhat of an exception rather than the rule.
  529. =head2 Getting the fat out of XSUBs
  530. In L<"EXAMPLE 4"> the second part of .xs file contained the following
  531. description of an XSUB:
  532. double
  533. foo(a,b,c)
  534. int a
  535. long b
  536. const char * c
  537. OUTPUT:
  538. RETVAL
  539. Note that in contrast with L<"EXAMPLE 1">, L<"EXAMPLE 2"> and L<"EXAMPLE 3">,
  540. this description does not contain the actual I<code> for what is done
  541. is done during a call to Perl function foo(). To understand what is going
  542. on here, one can add a CODE section to this XSUB:
  543. double
  544. foo(a,b,c)
  545. int a
  546. long b
  547. const char * c
  548. CODE:
  549. RETVAL = foo(a,b,c);
  550. OUTPUT:
  551. RETVAL
  552. However, these two XSUBs provide almost identical generated C code: B<xsubpp>
  553. compiler is smart enough to figure out the C<CODE:> section from the first
  554. two lines of the description of XSUB. What about C<OUTPUT:> section? In
  555. fact, that is absolutely the same! The C<OUTPUT:> section can be removed
  556. as well, I<as far as C<CODE:> section or C<PPCODE:> section> is not
  557. specified: B<xsubpp> can see that it needs to generate a function call
  558. section, and will autogenerate the OUTPUT section too. Thus one can
  559. shortcut the XSUB to become:
  560. double
  561. foo(a,b,c)
  562. int a
  563. long b
  564. const char * c
  565. Can we do the same with an XSUB
  566. int
  567. is_even(input)
  568. int input
  569. CODE:
  570. RETVAL = (input % 2 == 0);
  571. OUTPUT:
  572. RETVAL
  573. of L<"EXAMPLE 2">? To do this, one needs to define a C function C<int
  574. is_even(int input)>. As we saw in L<Anatomy of .xs file>, a proper place
  575. for this definition is in the first part of .xs file. In fact a C function
  576. int
  577. is_even(int arg)
  578. {
  579. return (arg % 2 == 0);
  580. }
  581. is probably overkill for this. Something as simple as a C<#define> will
  582. do too:
  583. #define is_even(arg) ((arg) % 2 == 0)
  584. After having this in the first part of .xs file, the "Perl glue" part becomes
  585. as simple as
  586. int
  587. is_even(input)
  588. int input
  589. This technique of separation of the glue part from the workhorse part has
  590. obvious tradeoffs: if you want to change a Perl interface, you need to
  591. change two places in your code. However, it removes a lot of clutter,
  592. and makes the workhorse part independent from idiosyncrasies of Perl calling
  593. convention. (In fact, there is nothing Perl-specific in the above description,
  594. a different version of B<xsubpp> might have translated this to TCL glue or
  595. Python glue as well.)
  596. =head2 More about XSUB arguments
  597. With the completion of Example 4, we now have an easy way to simulate some
  598. real-life libraries whose interfaces may not be the cleanest in the world.
  599. We shall now continue with a discussion of the arguments passed to the
  600. B<xsubpp> compiler.
  601. When you specify arguments to routines in the .xs file, you are really
  602. passing three pieces of information for each argument listed. The first
  603. piece is the order of that argument relative to the others (first, second,
  604. etc). The second is the type of argument, and consists of the type
  605. declaration of the argument (e.g., int, char*, etc). The third piece is
  606. the calling convention for the argument in the call to the library function.
  607. While Perl passes arguments to functions by reference,
  608. C passes arguments by value; to implement a C function which modifies data
  609. of one of the "arguments", the actual argument of this C function would be
  610. a pointer to the data. Thus two C functions with declarations
  611. int string_length(char *s);
  612. int upper_case_char(char *cp);
  613. may have completely different semantics: the first one may inspect an array
  614. of chars pointed by s, and the second one may immediately dereference C<cp>
  615. and manipulate C<*cp> only (using the return value as, say, a success
  616. indicator). From Perl one would use these functions in
  617. a completely different manner.
  618. One conveys this info to B<xsubpp> by replacing C<*> before the
  619. argument by C<&>. C<&> means that the argument should be passed to a library
  620. function by its address. The above two function may be XSUB-ified as
  621. int
  622. string_length(s)
  623. char * s
  624. int
  625. upper_case_char(cp)
  626. char &cp
  627. For example, consider:
  628. int
  629. foo(a,b)
  630. char &a
  631. char * b
  632. The first Perl argument to this function would be treated as a char and assigned
  633. to the variable a, and its address would be passed into the function foo.
  634. The second Perl argument would be treated as a string pointer and assigned to the
  635. variable b. The I<value> of b would be passed into the function foo. The
  636. actual call to the function foo that B<xsubpp> generates would look like this:
  637. foo(&a, b);
  638. B<xsubpp> will parse the following function argument lists identically:
  639. char &a
  640. char&a
  641. char & a
  642. However, to help ease understanding, it is suggested that you place a "&"
  643. next to the variable name and away from the variable type), and place a
  644. "*" near the variable type, but away from the variable name (as in the
  645. call to foo above). By doing so, it is easy to understand exactly what
  646. will be passed to the C function -- it will be whatever is in the "last
  647. column".
  648. You should take great pains to try to pass the function the type of variable
  649. it wants, when possible. It will save you a lot of trouble in the long run.
  650. =head2 The Argument Stack
  651. If we look at any of the C code generated by any of the examples except
  652. example 1, you will notice a number of references to ST(n), where n is
  653. usually 0. "ST" is actually a macro that points to the n'th argument
  654. on the argument stack. ST(0) is thus the first argument on the stack and
  655. therefore the first argument passed to the XSUB, ST(1) is the second
  656. argument, and so on.
  657. When you list the arguments to the XSUB in the .xs file, that tells B<xsubpp>
  658. which argument corresponds to which of the argument stack (i.e., the first
  659. one listed is the first argument, and so on). You invite disaster if you
  660. do not list them in the same order as the function expects them.
  661. The actual values on the argument stack are pointers to the values passed
  662. in. When an argument is listed as being an OUTPUT value, its corresponding
  663. value on the stack (i.e., ST(0) if it was the first argument) is changed.
  664. You can verify this by looking at the C code generated for Example 3.
  665. The code for the round() XSUB routine contains lines that look like this:
  666. double arg = (double)SvNV(ST(0));
  667. /* Round the contents of the variable arg */
  668. sv_setnv(ST(0), (double)arg);
  669. The arg variable is initially set by taking the value from ST(0), then is
  670. stored back into ST(0) at the end of the routine.
  671. XSUBs are also allowed to return lists, not just scalars. This must be
  672. done by manipulating stack values ST(0), ST(1), etc, in a subtly
  673. different way. See L<perlxs> for details.
  674. XSUBs are also allowed to avoid automatic conversion of Perl function arguments
  675. to C function arguments. See L<perlxs> for details. Some people prefer
  676. manual conversion by inspecting C<ST(i)> even in the cases when automatic
  677. conversion will do, arguing that this makes the logic of an XSUB call clearer.
  678. Compare with L<"Getting the fat out of XSUBs"> for a similar tradeoff of
  679. a complete separation of "Perl glue" and "workhorse" parts of an XSUB.
  680. While experts may argue about these idioms, a novice to Perl guts may
  681. prefer a way which is as little Perl-guts-specific as possible, meaning
  682. automatic conversion and automatic call generation, as in
  683. L<"Getting the fat out of XSUBs">. This approach has the additional
  684. benefit of protecting the XSUB writer from future changes to the Perl API.
  685. =head2 Extending your Extension
  686. Sometimes you might want to provide some extra methods or subroutines
  687. to assist in making the interface between Perl and your extension simpler
  688. or easier to understand. These routines should live in the .pm file.
  689. Whether they are automatically loaded when the extension itself is loaded
  690. or only loaded when called depends on where in the .pm file the subroutine
  691. definition is placed. You can also consult L<AutoLoader> for an alternate
  692. way to store and load your extra subroutines.
  693. =head2 Documenting your Extension
  694. There is absolutely no excuse for not documenting your extension.
  695. Documentation belongs in the .pm file. This file will be fed to pod2man,
  696. and the embedded documentation will be converted to the man page format,
  697. then placed in the blib directory. It will be copied to Perl's man
  698. page directory when the extension is installed.
  699. You may intersperse documentation and Perl code within the .pm file.
  700. In fact, if you want to use method autoloading, you must do this,
  701. as the comment inside the .pm file explains.
  702. See L<perlpod> for more information about the pod format.
  703. =head2 Installing your Extension
  704. Once your extension is complete and passes all its tests, installing it
  705. is quite simple: you simply run "make install". You will either need
  706. to have write permission into the directories where Perl is installed,
  707. or ask your system administrator to run the make for you.
  708. Alternately, you can specify the exact directory to place the extension's
  709. files by placing a "PREFIX=/destination/directory" after the make install.
  710. (or in between the make and install if you have a brain-dead version of make).
  711. This can be very useful if you are building an extension that will eventually
  712. be distributed to multiple systems. You can then just archive the files in
  713. the destination directory and distribute them to your destination systems.
  714. =head2 EXAMPLE 5
  715. In this example, we'll do some more work with the argument stack. The
  716. previous examples have all returned only a single value. We'll now
  717. create an extension that returns an array.
  718. This extension is very Unix-oriented (struct statfs and the statfs system
  719. call). If you are not running on a Unix system, you can substitute for
  720. statfs any other function that returns multiple values, you can hard-code
  721. values to be returned to the caller (although this will be a bit harder
  722. to test the error case), or you can simply not do this example. If you
  723. change the XSUB, be sure to fix the test cases to match the changes.
  724. Return to the Mytest directory and add the following code to the end of
  725. Mytest.xs:
  726. void
  727. statfs(path)
  728. char * path
  729. INIT:
  730. int i;
  731. struct statfs buf;
  732. PPCODE:
  733. i = statfs(path, &buf);
  734. if (i == 0) {
  735. XPUSHs(sv_2mortal(newSVnv(buf.f_bavail)));
  736. XPUSHs(sv_2mortal(newSVnv(buf.f_bfree)));
  737. XPUSHs(sv_2mortal(newSVnv(buf.f_blocks)));
  738. XPUSHs(sv_2mortal(newSVnv(buf.f_bsize)));
  739. XPUSHs(sv_2mortal(newSVnv(buf.f_ffree)));
  740. XPUSHs(sv_2mortal(newSVnv(buf.f_files)));
  741. XPUSHs(sv_2mortal(newSVnv(buf.f_type)));
  742. XPUSHs(sv_2mortal(newSVnv(buf.f_fsid[0])));
  743. XPUSHs(sv_2mortal(newSVnv(buf.f_fsid[1])));
  744. } else {
  745. XPUSHs(sv_2mortal(newSVnv(errno)));
  746. }
  747. You'll also need to add the following code to the top of the .xs file, just
  748. after the include of "XSUB.h":
  749. #include <sys/vfs.h>
  750. Also add the following code segment to test.pl while incrementing the "1..9"
  751. string in the BEGIN block to "1..11":
  752. @a = &Mytest::statfs("/blech");
  753. print ((scalar(@a) == 1 && $a[0] == 2) ? "ok 10\n" : "not ok 10\n");
  754. @a = &Mytest::statfs("/");
  755. print scalar(@a) == 9 ? "ok 11\n" : "not ok 11\n";
  756. =head2 New Things in this Example
  757. This example added quite a few new concepts. We'll take them one at a time.
  758. =over 4
  759. =item *
  760. The INIT: directive contains code that will be placed immediately after
  761. the argument stack is decoded. C does not allow variable declarations at
  762. arbitrary locations inside a function,
  763. so this is usually the best way to declare local variables needed by the XSUB.
  764. (Alternatively, one could put the whole C<PPCODE:> section into braces, and
  765. put these declarations on top.)
  766. =item *
  767. This routine also returns a different number of arguments depending on the
  768. success or failure of the call to statfs. If there is an error, the error
  769. number is returned as a single-element array. If the call is successful,
  770. then a 9-element array is returned. Since only one argument is passed into
  771. this function, we need room on the stack to hold the 9 values which may be
  772. returned.
  773. We do this by using the PPCODE: directive, rather than the CODE: directive.
  774. This tells B<xsubpp> that we will be managing the return values that will be
  775. put on the argument stack by ourselves.
  776. =item *
  777. When we want to place values to be returned to the caller onto the stack,
  778. we use the series of macros that begin with "XPUSH". There are five
  779. different versions, for placing integers, unsigned integers, doubles,
  780. strings, and Perl scalars on the stack. In our example, we placed a
  781. Perl scalar onto the stack. (In fact this is the only macro which
  782. can be used to return multiple values.)
  783. The XPUSH* macros will automatically extend the return stack to prevent
  784. it from being overrun. You push values onto the stack in the order you
  785. want them seen by the calling program.
  786. =item *
  787. The values pushed onto the return stack of the XSUB are actually mortal SV's.
  788. They are made mortal so that once the values are copied by the calling
  789. program, the SV's that held the returned values can be deallocated.
  790. If they were not mortal, then they would continue to exist after the XSUB
  791. routine returned, but would not be accessible. This is a memory leak.
  792. =item *
  793. If we were interested in performance, not in code compactness, in the success
  794. branch we would not use C<XPUSHs> macros, but C<PUSHs> macros, and would
  795. pre-extend the stack before pushing the return values:
  796. EXTEND(SP, 9);
  797. The tradeoff is that one needs to calculate the number of return values
  798. in advance (though overextending the stack will not typically hurt
  799. anything but memory consumption).
  800. Similarly, in the failure branch we could use C<PUSHs> I<without> extending
  801. the stack: the Perl function reference comes to an XSUB on the stack, thus
  802. the stack is I<always> large enough to take one return value.
  803. =back
  804. =head2 EXAMPLE 6
  805. In this example, we will accept a reference to an array as an input
  806. parameter, and return a reference to an array of hashes. This will
  807. demonstrate manipulation of complex Perl data types from an XSUB.
  808. This extension is somewhat contrived. It is based on the code in
  809. the previous example. It calls the statfs function multiple times,
  810. accepting a reference to an array of filenames as input, and returning
  811. a reference to an array of hashes containing the data for each of the
  812. filesystems.
  813. Return to the Mytest directory and add the following code to the end of
  814. Mytest.xs:
  815. SV *
  816. multi_statfs(paths)
  817. SV * paths
  818. INIT:
  819. AV * results;
  820. I32 numpaths = 0;
  821. int i, n;
  822. struct statfs buf;
  823. if ((!SvROK(paths))
  824. || (SvTYPE(SvRV(paths)) != SVt_PVAV)
  825. || ((numpaths = av_len((AV *)SvRV(paths))) < 0))
  826. {
  827. XSRETURN_UNDEF;
  828. }
  829. results = (AV *)sv_2mortal((SV *)newAV());
  830. CODE:
  831. for (n = 0; n <= numpaths; n++) {
  832. HV * rh;
  833. STRLEN l;
  834. char * fn = SvPV(*av_fetch((AV *)SvRV(paths), n, 0), l);
  835. i = statfs(fn, &buf);
  836. if (i != 0) {
  837. av_push(results, newSVnv(errno));
  838. continue;
  839. }
  840. rh = (HV *)sv_2mortal((SV *)newHV());
  841. hv_store(rh, "f_bavail", 8, newSVnv(buf.f_bavail), 0);
  842. hv_store(rh, "f_bfree", 7, newSVnv(buf.f_bfree), 0);
  843. hv_store(rh, "f_blocks", 8, newSVnv(buf.f_blocks), 0);
  844. hv_store(rh, "f_bsize", 7, newSVnv(buf.f_bsize), 0);
  845. hv_store(rh, "f_ffree", 7, newSVnv(buf.f_ffree), 0);
  846. hv_store(rh, "f_files", 7, newSVnv(buf.f_files), 0);
  847. hv_store(rh, "f_type", 6, newSVnv(buf.f_type), 0);
  848. av_push(results, newRV((SV *)rh));
  849. }
  850. RETVAL = newRV((SV *)results);
  851. OUTPUT:
  852. RETVAL
  853. And add the following code to test.pl, while incrementing the "1..11"
  854. string in the BEGIN block to "1..13":
  855. $results = Mytest::multi_statfs([ '/', '/blech' ]);
  856. print ((ref $results->[0]) ? "ok 12\n" : "not ok 12\n");
  857. print ((! ref $results->[1]) ? "ok 13\n" : "not ok 13\n");
  858. =head2 New Things in this Example
  859. There are a number of new concepts introduced here, described below:
  860. =over 4
  861. =item *
  862. This function does not use a typemap. Instead, we declare it as accepting
  863. one SV* (scalar) parameter, and returning an SV* value, and we take care of
  864. populating these scalars within the code. Because we are only returning
  865. one value, we don't need a C<PPCODE:> directive - instead, we use C<CODE:>
  866. and C<OUTPUT:> directives.
  867. =item *
  868. When dealing with references, it is important to handle them with caution.
  869. The C<INIT:> block first checks that
  870. C<SvROK> returns true, which indicates that paths is a valid reference. It
  871. then verifies that the object referenced by paths is an array, using C<SvRV>
  872. to dereference paths, and C<SvTYPE> to discover its type. As an added test,
  873. it checks that the array referenced by paths is non-empty, using the C<av_len>
  874. function (which returns -1 if the array is empty). The XSRETURN_UNDEF macro
  875. is used to abort the XSUB and return the undefined value whenever all three of
  876. these conditions are not met.
  877. =item *
  878. We manipulate several arrays in this XSUB. Note that an array is represented
  879. internally by an AV* pointer. The functions and macros for manipulating
  880. arrays are similar to the functions in Perl: C<av_len> returns the highest
  881. index in an AV*, much like $#array; C<av_fetch> fetches a single scalar value
  882. from an array, given its index; C<av_push> pushes a scalar value onto the
  883. end of the array, automatically extending the array as necessary.
  884. Specifically, we read pathnames one at a time from the input array, and
  885. store the results in an output array (results) in the same order. If
  886. statfs fails, the element pushed onto the return array is the value of
  887. errno after the failure. If statfs succeeds, though, the value pushed
  888. onto the return array is a reference to a hash containing some of the
  889. information in the statfs structure.
  890. As with the return stack, it would be possible (and a small performance win)
  891. to pre-extend the return array before pushing data into it, since we know
  892. how many elements we will return:
  893. av_extend(results, numpaths);
  894. =item *
  895. We are performing only one hash operation in this function, which is storing
  896. a new scalar under a key using C<hv_store>. A hash is represented by an HV*
  897. pointer. Like arrays, the functions for manipulating hashes from an XSUB
  898. mirror the functionality available from Perl. See L<perlguts> and L<perlapi>
  899. for details.
  900. =item *
  901. To create a reference, we use the C<newRV> function. Note that you can
  902. cast an AV* or an HV* to type SV* in this case (and many others). This
  903. allows you to take references to arrays, hashes and scalars with the same
  904. function. Conversely, the C<SvRV> function always returns an SV*, which may
  905. need to be be cast to the appropriate type if it is something other than a
  906. scalar (check with C<SvTYPE>).
  907. =item *
  908. At this point, xsubpp is doing very little work - the differences between
  909. Mytest.xs and Mytest.c are minimal.
  910. =back
  911. =head2 EXAMPLE 7 (Coming Soon)
  912. XPUSH args AND set RETVAL AND assign return value to array
  913. =head2 EXAMPLE 8 (Coming Soon)
  914. Setting $!
  915. =head2 EXAMPLE 9 (Coming Soon)
  916. Getting fd's from filehandles
  917. =head2 Troubleshooting these Examples
  918. As mentioned at the top of this document, if you are having problems with
  919. these example extensions, you might see if any of these help you.
  920. =over 4
  921. =item *
  922. In versions of 5.002 prior to the gamma version, the test script in Example
  923. 1 will not function properly. You need to change the "use lib" line to
  924. read:
  925. use lib './blib';
  926. =item *
  927. In versions of 5.002 prior to version 5.002b1h, the test.pl file was not
  928. automatically created by h2xs. This means that you cannot say "make test"
  929. to run the test script. You will need to add the following line before the
  930. "use extension" statement:
  931. use lib './blib';
  932. =item *
  933. In versions 5.000 and 5.001, instead of using the above line, you will need
  934. to use the following line:
  935. BEGIN { unshift(@INC, "./blib") }
  936. =item *
  937. This document assumes that the executable named "perl" is Perl version 5.
  938. Some systems may have installed Perl version 5 as "perl5".
  939. =back
  940. =head1 See also
  941. For more information, consult L<perlguts>, L<perlapi>, L<perlxs>, L<perlmod>,
  942. and L<perlpod>.
  943. =head1 Author
  944. Jeff Okamoto <F<[email protected]>>
  945. Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig,
  946. and Tim Bunce.
  947. =head2 Last Changed
  948. 1999/11/30