| 1 | =head1 NAME |
| 2 | |
| 3 | perlXStut - Tutorial for XSUBs |
| 4 | |
| 5 | =head1 DESCRIPTION |
| 6 | |
| 7 | This tutorial will educate the reader on the steps involved in creating |
| 8 | a Perl extension. The reader is assumed to have access to L<perlguts> and |
| 9 | L<perlxs>. |
| 10 | |
| 11 | This tutorial starts with very simple examples and becomes more complex, |
| 12 | with each new example adding new features. Certain concepts may not be |
| 13 | completely explained until later in the tutorial in order to slowly ease |
| 14 | the reader into building extensions. |
| 15 | |
| 16 | =head2 VERSION CAVEAT |
| 17 | |
| 18 | This tutorial tries hard to keep up with the latest development versions |
| 19 | of Perl. This often means that it is sometimes in advance of the latest |
| 20 | released version of Perl, and that certain features described here might |
| 21 | not work on earlier versions. This section will keep track of when various |
| 22 | features were added to Perl 5. |
| 23 | |
| 24 | =over 4 |
| 25 | |
| 26 | =item * |
| 27 | |
| 28 | In versions of 5.002 prior to the gamma version, the test script in Example |
| 29 | 1 will not function properly. You need to change the "use lib" line to |
| 30 | read: |
| 31 | |
| 32 | use lib './blib'; |
| 33 | |
| 34 | =item * |
| 35 | |
| 36 | In versions of 5.002 prior to version beta 3, the line in the .xs file |
| 37 | about "PROTOTYPES: DISABLE" will cause a compiler error. Simply remove that |
| 38 | line from the file. |
| 39 | |
| 40 | =item * |
| 41 | |
| 42 | In versions of 5.002 prior to version 5.002b1h, the test.pl file was not |
| 43 | automatically created by h2xs. This means that you cannot say "make test" |
| 44 | to run the test script. You will need to add the following line before the |
| 45 | "use extension" statement: |
| 46 | |
| 47 | use lib './blib'; |
| 48 | |
| 49 | =item * |
| 50 | |
| 51 | In versions 5.000 and 5.001, instead of using the above line, you will need |
| 52 | to use the following line: |
| 53 | |
| 54 | BEGIN { unshift(@INC, "./blib") } |
| 55 | |
| 56 | =item * |
| 57 | |
| 58 | This document assumes that the executable named "perl" is Perl version 5. |
| 59 | Some systems may have installed Perl version 5 as "perl5". |
| 60 | |
| 61 | =back |
| 62 | |
| 63 | =head2 DYNAMIC VERSUS STATIC |
| 64 | |
| 65 | It is commonly thought that if a system does not have the capability to |
| 66 | dynamically load a library, you cannot build XSUBs. This is incorrect. |
| 67 | You I<can> build them, but you must link the XSUB's subroutines with the |
| 68 | rest of Perl, creating a new executable. This situation is similar to |
| 69 | Perl 4. |
| 70 | |
| 71 | This tutorial can still be used on such a system. The XSUB build mechanism |
| 72 | will check the system and build a dynamically-loadable library if possible, |
| 73 | or else a static library and then, optionally, a new statically-linked |
| 74 | executable with that static library linked in. |
| 75 | |
| 76 | Should you wish to build a statically-linked executable on a system which |
| 77 | can dynamically load libraries, you may, in all the following examples, |
| 78 | where the command "make" with no arguments is executed, run the command |
| 79 | "make perl" instead. |
| 80 | |
| 81 | If you have generated such a statically-linked executable by choice, then |
| 82 | instead of saying "make test", you should say "make test_static". On systems |
| 83 | that cannot build dynamically-loadable libraries at all, simply saying "make |
| 84 | test" is sufficient. |
| 85 | |
| 86 | =head2 EXAMPLE 1 |
| 87 | |
| 88 | Our first extension will be very simple. When we call the routine in the |
| 89 | extension, it will print out a well-known message and return. |
| 90 | |
| 91 | Run C<h2xs -A -n Mytest>. This creates a directory named Mytest, possibly under |
| 92 | ext/ if that directory exists in the current working directory. Several files |
| 93 | will be created in the Mytest dir, including MANIFEST, Makefile.PL, Mytest.pm, |
| 94 | Mytest.xs, test.pl, and Changes. |
| 95 | |
| 96 | The MANIFEST file contains the names of all the files created. |
| 97 | |
| 98 | The file Makefile.PL should look something like this: |
| 99 | |
| 100 | use ExtUtils::MakeMaker; |
| 101 | # See lib/ExtUtils/MakeMaker.pm for details of how to influence |
| 102 | # the contents of the Makefile that is written. |
| 103 | WriteMakefile( |
| 104 | 'NAME' => 'Mytest', |
| 105 | 'VERSION_FROM' => 'Mytest.pm', # finds $VERSION |
| 106 | 'LIBS' => [''], # e.g., '-lm' |
| 107 | 'DEFINE' => '', # e.g., '-DHAVE_SOMETHING' |
| 108 | 'INC' => '', # e.g., '-I/usr/include/other' |
| 109 | ); |
| 110 | |
| 111 | The file Mytest.pm should start with something like this: |
| 112 | |
| 113 | package Mytest; |
| 114 | |
| 115 | require Exporter; |
| 116 | require DynaLoader; |
| 117 | |
| 118 | @ISA = qw(Exporter DynaLoader); |
| 119 | # Items to export into callers namespace by default. Note: do not export |
| 120 | # names by default without a very good reason. Use EXPORT_OK instead. |
| 121 | # Do not simply export all your public functions/methods/constants. |
| 122 | @EXPORT = qw( |
| 123 | |
| 124 | ); |
| 125 | $VERSION = '0.01'; |
| 126 | |
| 127 | bootstrap Mytest $VERSION; |
| 128 | |
| 129 | # Preloaded methods go here. |
| 130 | |
| 131 | # Autoload methods go after __END__, and are processed by the autosplit program. |
| 132 | |
| 133 | 1; |
| 134 | __END__ |
| 135 | # Below is the stub of documentation for your module. You better edit it! |
| 136 | |
| 137 | And the Mytest.xs file should look something like this: |
| 138 | |
| 139 | #ifdef __cplusplus |
| 140 | extern "C" { |
| 141 | #endif |
| 142 | #include "EXTERN.h" |
| 143 | #include "perl.h" |
| 144 | #include "XSUB.h" |
| 145 | #ifdef __cplusplus |
| 146 | } |
| 147 | #endif |
| 148 | |
| 149 | PROTOTYPES: DISABLE |
| 150 | |
| 151 | MODULE = Mytest PACKAGE = Mytest |
| 152 | |
| 153 | Let's edit the .xs file by adding this to the end of the file: |
| 154 | |
| 155 | void |
| 156 | hello() |
| 157 | CODE: |
| 158 | printf("Hello, world!\n"); |
| 159 | |
| 160 | Now we'll run "perl Makefile.PL". This will create a real Makefile, |
| 161 | which make needs. Its output looks something like: |
| 162 | |
| 163 | % perl Makefile.PL |
| 164 | Checking if your kit is complete... |
| 165 | Looks good |
| 166 | Writing Makefile for Mytest |
| 167 | % |
| 168 | |
| 169 | Now, running make will produce output that looks something like this |
| 170 | (some long lines shortened for clarity): |
| 171 | |
| 172 | % make |
| 173 | umask 0 && cp Mytest.pm ./blib/Mytest.pm |
| 174 | perl xsubpp -typemap typemap Mytest.xs >Mytest.tc && mv Mytest.tc Mytest.c |
| 175 | cc -c Mytest.c |
| 176 | Running Mkbootstrap for Mytest () |
| 177 | chmod 644 Mytest.bs |
| 178 | LD_RUN_PATH="" ld -o ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl -b Mytest.o |
| 179 | chmod 755 ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl |
| 180 | cp Mytest.bs ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs |
| 181 | chmod 644 ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs |
| 182 | |
| 183 | Now, although there is already a test.pl template ready for us, for this |
| 184 | example only, we'll create a special test script. Create a file called hello |
| 185 | that looks like this: |
| 186 | |
| 187 | #! /opt/perl5/bin/perl |
| 188 | |
| 189 | use ExtUtils::testlib; |
| 190 | |
| 191 | use Mytest; |
| 192 | |
| 193 | Mytest::hello(); |
| 194 | |
| 195 | Now we run the script and we should see the following output: |
| 196 | |
| 197 | % perl hello |
| 198 | Hello, world! |
| 199 | % |
| 200 | |
| 201 | =head2 EXAMPLE 2 |
| 202 | |
| 203 | Now let's add to our extension a subroutine that will take a single argument |
| 204 | and return 1 if the argument is even, 0 if the argument is odd. |
| 205 | |
| 206 | Add the following to the end of Mytest.xs: |
| 207 | |
| 208 | int |
| 209 | is_even(input) |
| 210 | int input |
| 211 | CODE: |
| 212 | RETVAL = (input % 2 == 0); |
| 213 | OUTPUT: |
| 214 | RETVAL |
| 215 | |
| 216 | There does not need to be white space at the start of the "int input" line, |
| 217 | but it is useful for improving readability. The semi-colon at the end of |
| 218 | that line is also optional. |
| 219 | |
| 220 | Any white space may be between the "int" and "input". It is also okay for |
| 221 | the four lines starting at the "CODE:" line to not be indented. However, |
| 222 | for readability purposes, it is suggested that you indent them 8 spaces |
| 223 | (or one normal tab stop). |
| 224 | |
| 225 | Now re-run make to rebuild our new shared library. |
| 226 | |
| 227 | Now perform the same steps as before, generating a Makefile from the |
| 228 | Makefile.PL file, and running make. |
| 229 | |
| 230 | In order to test that our extension works, we now need to look at the |
| 231 | file test.pl. This file is set up to imitate the same kind of testing |
| 232 | structure that Perl itself has. Within the test script, you perform a |
| 233 | number of tests to confirm the behavior of the extension, printing "ok" |
| 234 | when the test is correct, "not ok" when it is not. Change the print |
| 235 | statement in the BEGIN block to print "1..4", and add the following code |
| 236 | to the end of the file: |
| 237 | |
| 238 | print &Mytest::is_even(0) == 1 ? "ok 2" : "not ok 2", "\n"; |
| 239 | print &Mytest::is_even(1) == 0 ? "ok 3" : "not ok 3", "\n"; |
| 240 | print &Mytest::is_even(2) == 1 ? "ok 4" : "not ok 4", "\n"; |
| 241 | |
| 242 | We will be calling the test script through the command "make test". You |
| 243 | should see output that looks something like this: |
| 244 | |
| 245 | % make test |
| 246 | PERL_DL_NONLAZY=1 /opt/perl5.002b2/bin/perl (lots of -I arguments) test.pl |
| 247 | 1..4 |
| 248 | ok 1 |
| 249 | ok 2 |
| 250 | ok 3 |
| 251 | ok 4 |
| 252 | % |
| 253 | |
| 254 | =head2 WHAT HAS GONE ON? |
| 255 | |
| 256 | The program h2xs is the starting point for creating extensions. In later |
| 257 | examples we'll see how we can use h2xs to read header files and generate |
| 258 | templates to connect to C routines. |
| 259 | |
| 260 | h2xs creates a number of files in the extension directory. The file |
| 261 | Makefile.PL is a perl script which will generate a true Makefile to build |
| 262 | the extension. We'll take a closer look at it later. |
| 263 | |
| 264 | The files E<lt>extensionE<gt>.pm and E<lt>extensionE<gt>.xs contain the meat |
| 265 | of the extension. |
| 266 | The .xs file holds the C routines that make up the extension. The .pm file |
| 267 | contains routines that tell Perl how to load your extension. |
| 268 | |
| 269 | Generating and invoking the Makefile created a directory blib (which stands |
| 270 | for "build library") in the current working directory. This directory will |
| 271 | contain the shared library that we will build. Once we have tested it, we |
| 272 | can install it into its final location. |
| 273 | |
| 274 | Invoking the test script via "make test" did something very important. It |
| 275 | invoked perl with all those C<-I> arguments so that it could find the various |
| 276 | files that are part of the extension. |
| 277 | |
| 278 | It is I<very> important that while you are still testing extensions that |
| 279 | you use "make test". If you try to run the test script all by itself, you |
| 280 | will get a fatal error. |
| 281 | |
| 282 | Another reason it is important to use "make test" to run your test script |
| 283 | is that if you are testing an upgrade to an already-existing version, using |
| 284 | "make test" insures that you use your new extension, not the already-existing |
| 285 | version. |
| 286 | |
| 287 | When Perl sees a C<use extension;>, it searches for a file with the same name |
| 288 | as the use'd extension that has a .pm suffix. If that file cannot be found, |
| 289 | Perl dies with a fatal error. The default search path is contained in the |
| 290 | @INC array. |
| 291 | |
| 292 | In our case, Mytest.pm tells perl that it will need the Exporter and Dynamic |
| 293 | Loader extensions. It then sets the @ISA and @EXPORT arrays and the $VERSION |
| 294 | scalar; finally it tells perl to bootstrap the module. Perl will call its |
| 295 | dynamic loader routine (if there is one) and load the shared library. |
| 296 | |
| 297 | The two arrays that are set in the .pm file are very important. The @ISA |
| 298 | array contains a list of other packages in which to search for methods (or |
| 299 | subroutines) that do not exist in the current package. The @EXPORT array |
| 300 | tells Perl which of the extension's routines should be placed into the |
| 301 | calling package's namespace. |
| 302 | |
| 303 | It's important to select what to export carefully. Do NOT export method names |
| 304 | and do NOT export anything else I<by default> without a good reason. |
| 305 | |
| 306 | As a general rule, if the module is trying to be object-oriented then don't |
| 307 | export anything. If it's just a collection of functions then you can export |
| 308 | any of the functions via another array, called @EXPORT_OK. |
| 309 | |
| 310 | See L<perlmod> for more information. |
| 311 | |
| 312 | The $VERSION variable is used to ensure that the .pm file and the shared |
| 313 | library are "in sync" with each other. Any time you make changes to |
| 314 | the .pm or .xs files, you should increment the value of this variable. |
| 315 | |
| 316 | =head2 WRITING GOOD TEST SCRIPTS |
| 317 | |
| 318 | The importance of writing good test scripts cannot be overemphasized. You |
| 319 | should closely follow the "ok/not ok" style that Perl itself uses, so that |
| 320 | it is very easy and unambiguous to determine the outcome of each test case. |
| 321 | When you find and fix a bug, make sure you add a test case for it. |
| 322 | |
| 323 | By running "make test", you ensure that your test.pl script runs and uses |
| 324 | the correct version of your extension. If you have many test cases, you |
| 325 | might want to copy Perl's test style. Create a directory named "t", and |
| 326 | ensure all your test files end with the suffix ".t". The Makefile will |
| 327 | properly run all these test files. |
| 328 | |
| 329 | |
| 330 | =head2 EXAMPLE 3 |
| 331 | |
| 332 | Our third extension will take one argument as its input, round off that |
| 333 | value, and set the I<argument> to the rounded value. |
| 334 | |
| 335 | Add the following to the end of Mytest.xs: |
| 336 | |
| 337 | void |
| 338 | round(arg) |
| 339 | double arg |
| 340 | CODE: |
| 341 | if (arg > 0.0) { |
| 342 | arg = floor(arg + 0.5); |
| 343 | } else if (arg < 0.0) { |
| 344 | arg = ceil(arg - 0.5); |
| 345 | } else { |
| 346 | arg = 0.0; |
| 347 | } |
| 348 | OUTPUT: |
| 349 | arg |
| 350 | |
| 351 | Edit the Makefile.PL file so that the corresponding line looks like this: |
| 352 | |
| 353 | 'LIBS' => ['-lm'], # e.g., '-lm' |
| 354 | |
| 355 | Generate the Makefile and run make. Change the BEGIN block to print out |
| 356 | "1..9" and add the following to test.pl: |
| 357 | |
| 358 | $i = -1.5; &Mytest::round($i); print $i == -2.0 ? "ok 5" : "not ok 5", "\n"; |
| 359 | $i = -1.1; &Mytest::round($i); print $i == -1.0 ? "ok 6" : "not ok 6", "\n"; |
| 360 | $i = 0.0; &Mytest::round($i); print $i == 0.0 ? "ok 7" : "not ok 7", "\n"; |
| 361 | $i = 0.5; &Mytest::round($i); print $i == 1.0 ? "ok 8" : "not ok 8", "\n"; |
| 362 | $i = 1.2; &Mytest::round($i); print $i == 1.0 ? "ok 9" : "not ok 9", "\n"; |
| 363 | |
| 364 | Running "make test" should now print out that all nine tests are okay. |
| 365 | |
| 366 | You might be wondering if you can round a constant. To see what happens, add |
| 367 | the following line to test.pl temporarily: |
| 368 | |
| 369 | &Mytest::round(3); |
| 370 | |
| 371 | Run "make test" and notice that Perl dies with a fatal error. Perl won't let |
| 372 | you change the value of constants! |
| 373 | |
| 374 | =head2 WHAT'S NEW HERE? |
| 375 | |
| 376 | Two things are new here. First, we've made some changes to Makefile.PL. |
| 377 | In this case, we've specified an extra library to link in, the math library |
| 378 | libm. We'll talk later about how to write XSUBs that can call every routine |
| 379 | in a library. |
| 380 | |
| 381 | Second, the value of the function is being passed back not as the function's |
| 382 | return value, but through the same variable that was passed into the function. |
| 383 | |
| 384 | =head2 INPUT AND OUTPUT PARAMETERS |
| 385 | |
| 386 | You specify the parameters that will be passed into the XSUB just after you |
| 387 | declare the function return value and name. Each parameter line starts with |
| 388 | optional white space, and may have an optional terminating semicolon. |
| 389 | |
| 390 | The list of output parameters occurs after the OUTPUT: directive. The use |
| 391 | of RETVAL tells Perl that you wish to send this value back as the return |
| 392 | value of the XSUB function. In Example 3, the value we wanted returned was |
| 393 | contained in the same variable we passed in, so we listed it (and not RETVAL) |
| 394 | in the OUTPUT: section. |
| 395 | |
| 396 | =head2 THE XSUBPP COMPILER |
| 397 | |
| 398 | The compiler xsubpp takes the XS code in the .xs file and converts it into |
| 399 | C code, placing it in a file whose suffix is .c. The C code created makes |
| 400 | heavy use of the C functions within Perl. |
| 401 | |
| 402 | =head2 THE TYPEMAP FILE |
| 403 | |
| 404 | The xsubpp compiler uses rules to convert from Perl's data types (scalar, |
| 405 | array, etc.) to C's data types (int, char *, etc.). These rules are stored |
| 406 | in the typemap file ($PERLLIB/ExtUtils/typemap). This file is split into |
| 407 | three parts. |
| 408 | |
| 409 | The first part attempts to map various C data types to a coded flag, which |
| 410 | has some correspondence with the various Perl types. The second part contains |
| 411 | C code which xsubpp uses for input parameters. The third part contains C |
| 412 | code which xsubpp uses for output parameters. We'll talk more about the |
| 413 | C code later. |
| 414 | |
| 415 | Let's now take a look at a portion of the .c file created for our extension. |
| 416 | |
| 417 | XS(XS_Mytest_round) |
| 418 | { |
| 419 | dXSARGS; |
| 420 | if (items != 1) |
| 421 | croak("Usage: Mytest::round(arg)"); |
| 422 | { |
| 423 | double arg = (double)SvNV(ST(0)); /* XXXXX */ |
| 424 | if (arg > 0.0) { |
| 425 | arg = floor(arg + 0.5); |
| 426 | } else if (arg < 0.0) { |
| 427 | arg = ceil(arg - 0.5); |
| 428 | } else { |
| 429 | arg = 0.0; |
| 430 | } |
| 431 | sv_setnv(ST(0), (double)arg); /* XXXXX */ |
| 432 | } |
| 433 | XSRETURN(1); |
| 434 | } |
| 435 | |
| 436 | Notice the two lines marked with "XXXXX". If you check the first section of |
| 437 | the typemap file, you'll see that doubles are of type T_DOUBLE. In the |
| 438 | INPUT section, an argument that is T_DOUBLE is assigned to the variable |
| 439 | arg by calling the routine SvNV on something, then casting it to double, |
| 440 | then assigned to the variable arg. Similarly, in the OUTPUT section, |
| 441 | once arg has its final value, it is passed to the sv_setnv function to |
| 442 | be passed back to the calling subroutine. These two functions are explained |
| 443 | in L<perlguts>; we'll talk more later about what that "ST(0)" means in the |
| 444 | section on the argument stack. |
| 445 | |
| 446 | =head2 WARNING |
| 447 | |
| 448 | In general, it's not a good idea to write extensions that modify their input |
| 449 | parameters, as in Example 3. However, in order to better accommodate calling |
| 450 | pre-existing C routines, which often do modify their input parameters, |
| 451 | this behavior is tolerated. The next example will show how to do this. |
| 452 | |
| 453 | =head2 EXAMPLE 4 |
| 454 | |
| 455 | In this example, we'll now begin to write XSUB's that will interact with |
| 456 | pre-defined C libraries. To begin with, we will build a small library of |
| 457 | our own, then let h2xs write our .pm and .xs files for us. |
| 458 | |
| 459 | Create a new directory called Mytest2 at the same level as the directory |
| 460 | Mytest. In the Mytest2 directory, create another directory called mylib, |
| 461 | and cd into that directory. |
| 462 | |
| 463 | Here we'll create some files that will generate a test library. These will |
| 464 | include a C source file and a header file. We'll also create a Makefile.PL |
| 465 | in this directory. Then we'll make sure that running make at the Mytest2 |
| 466 | level will automatically run this Makefile.PL file and the resulting Makefile. |
| 467 | |
| 468 | In the testlib directory, create a file mylib.h that looks like this: |
| 469 | |
| 470 | #define TESTVAL 4 |
| 471 | |
| 472 | extern double foo(int, long, const char*); |
| 473 | |
| 474 | Also create a file mylib.c that looks like this: |
| 475 | |
| 476 | #include <stdlib.h> |
| 477 | #include "./mylib.h" |
| 478 | |
| 479 | double |
| 480 | foo(a, b, c) |
| 481 | int a; |
| 482 | long b; |
| 483 | const char * c; |
| 484 | { |
| 485 | return (a + b + atof(c) + TESTVAL); |
| 486 | } |
| 487 | |
| 488 | And finally create a file Makefile.PL that looks like this: |
| 489 | |
| 490 | use ExtUtils::MakeMaker; |
| 491 | $Verbose = 1; |
| 492 | WriteMakefile( |
| 493 | 'NAME' => 'Mytest2::mylib', |
| 494 | 'clean' => {'FILES' => 'libmylib.a'}, |
| 495 | ); |
| 496 | |
| 497 | |
| 498 | sub MY::postamble { |
| 499 | ' |
| 500 | all :: static |
| 501 | |
| 502 | static :: libmylib$(LIB_EXT) |
| 503 | |
| 504 | libmylib$(LIB_EXT): $(O_FILES) |
| 505 | $(AR) cr libmylib$(LIB_EXT) $(O_FILES) |
| 506 | $(RANLIB) libmylib$(LIB_EXT) |
| 507 | |
| 508 | '; |
| 509 | } |
| 510 | |
| 511 | We will now create the main top-level Mytest2 files. Change to the directory |
| 512 | above Mytest2 and run the following command: |
| 513 | |
| 514 | % h2xs -O -n Mytest2 ./Mytest2/mylib/mylib.h |
| 515 | |
| 516 | This will print out a warning about overwriting Mytest2, but that's okay. |
| 517 | Our files are stored in Mytest2/mylib, and will be untouched. |
| 518 | |
| 519 | The normal Makefile.PL that h2xs generates doesn't know about the mylib |
| 520 | directory. We need to tell it that there is a subdirectory and that we |
| 521 | will be generating a library in it. Let's add the following key-value |
| 522 | pair to the WriteMakefile call: |
| 523 | |
| 524 | 'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)', |
| 525 | |
| 526 | and a new replacement subroutine too: |
| 527 | |
| 528 | sub MY::postamble { |
| 529 | ' |
| 530 | $(MYEXTLIB): mylib/Makefile |
| 531 | cd mylib && $(MAKE) |
| 532 | '; |
| 533 | } |
| 534 | |
| 535 | (Note: Most makes will require that there be a tab character that indents |
| 536 | the line "cd mylib && $(MAKE)".) |
| 537 | |
| 538 | Let's also fix the MANIFEST file so that it accurately reflects the contents |
| 539 | of our extension. The single line that says "mylib" should be replaced by |
| 540 | the following three lines: |
| 541 | |
| 542 | mylib/Makefile.PL |
| 543 | mylib/mylib.c |
| 544 | mylib/mylib.h |
| 545 | |
| 546 | To keep our namespace nice and unpolluted, edit the .pm file and change |
| 547 | the lines setting @EXPORT to @EXPORT_OK (there are two: one in the line |
| 548 | beginning "use vars" and one setting the array itself). Finally, in the |
| 549 | .xs file, edit the #include line to read: |
| 550 | |
| 551 | #include "mylib/mylib.h" |
| 552 | |
| 553 | And also add the following function definition to the end of the .xs file: |
| 554 | |
| 555 | double |
| 556 | foo(a,b,c) |
| 557 | int a |
| 558 | long b |
| 559 | const char * c |
| 560 | OUTPUT: |
| 561 | RETVAL |
| 562 | |
| 563 | Now we also need to create a typemap file because the default Perl doesn't |
| 564 | currently support the const char * type. Create a file called typemap and |
| 565 | place the following in it: |
| 566 | |
| 567 | const char * T_PV |
| 568 | |
| 569 | Now run perl on the top-level Makefile.PL. Notice that it also created a |
| 570 | Makefile in the mylib directory. Run make and see that it does cd into |
| 571 | the mylib directory and run make in there as well. |
| 572 | |
| 573 | Now edit the test.pl script and change the BEGIN block to print "1..4", |
| 574 | and add the following lines to the end of the script: |
| 575 | |
| 576 | print &Mytest2::foo(1, 2, "Hello, world!") == 7 ? "ok 2\n" : "not ok 2\n"; |
| 577 | print &Mytest2::foo(1, 2, "0.0") == 7 ? "ok 3\n" : "not ok 3\n"; |
| 578 | print abs(&Mytest2::foo(0, 0, "-3.4") - 0.6) <= 0.01 ? "ok 4\n" : "not ok 4\n"; |
| 579 | |
| 580 | (When dealing with floating-point comparisons, it is often useful to not check |
| 581 | for equality, but rather the difference being below a certain epsilon factor, |
| 582 | 0.01 in this case) |
| 583 | |
| 584 | Run "make test" and all should be well. |
| 585 | |
| 586 | =head2 WHAT HAS HAPPENED HERE? |
| 587 | |
| 588 | Unlike previous examples, we've now run h2xs on a real include file. This |
| 589 | has caused some extra goodies to appear in both the .pm and .xs files. |
| 590 | |
| 591 | =over 4 |
| 592 | |
| 593 | =item * |
| 594 | |
| 595 | In the .xs file, there's now a #include declaration with the full path to |
| 596 | the mylib.h header file. |
| 597 | |
| 598 | =item * |
| 599 | |
| 600 | There's now some new C code that's been added to the .xs file. The purpose |
| 601 | of the C<constant> routine is to make the values that are #define'd in the |
| 602 | header file available to the Perl script (in this case, by calling |
| 603 | C<&main::TESTVAL>). There's also some XS code to allow calls to the |
| 604 | C<constant> routine. |
| 605 | |
| 606 | =item * |
| 607 | |
| 608 | The .pm file has exported the name TESTVAL in the @EXPORT array. This |
| 609 | could lead to name clashes. A good rule of thumb is that if the #define |
| 610 | is only going to be used by the C routines themselves, and not by the user, |
| 611 | they should be removed from the @EXPORT array. Alternately, if you don't |
| 612 | mind using the "fully qualified name" of a variable, you could remove most |
| 613 | or all of the items in the @EXPORT array. |
| 614 | |
| 615 | =item * |
| 616 | |
| 617 | If our include file contained #include directives, these would not be |
| 618 | processed at all by h2xs. There is no good solution to this right now. |
| 619 | |
| 620 | =back |
| 621 | |
| 622 | We've also told Perl about the library that we built in the mylib |
| 623 | subdirectory. That required only the addition of the MYEXTLIB variable |
| 624 | to the WriteMakefile call and the replacement of the postamble subroutine |
| 625 | to cd into the subdirectory and run make. The Makefile.PL for the |
| 626 | library is a bit more complicated, but not excessively so. Again we |
| 627 | replaced the postamble subroutine to insert our own code. This code |
| 628 | simply specified that the library to be created here was a static |
| 629 | archive (as opposed to a dynamically loadable library) and provided the |
| 630 | commands to build it. |
| 631 | |
| 632 | =head2 SPECIFYING ARGUMENTS TO XSUBPP |
| 633 | |
| 634 | With the completion of Example 4, we now have an easy way to simulate some |
| 635 | real-life libraries whose interfaces may not be the cleanest in the world. |
| 636 | We shall now continue with a discussion of the arguments passed to the |
| 637 | xsubpp compiler. |
| 638 | |
| 639 | When you specify arguments in the .xs file, you are really passing three |
| 640 | pieces of information for each one listed. The first piece is the order |
| 641 | of that argument relative to the others (first, second, etc). The second |
| 642 | is the type of argument, and consists of the type declaration of the |
| 643 | argument (e.g., int, char*, etc). The third piece is the exact way in |
| 644 | which the argument should be used in the call to the library function |
| 645 | from this XSUB. This would mean whether or not to place a "&" before |
| 646 | the argument or not, meaning the argument expects to be passed the address |
| 647 | of the specified data type. |
| 648 | |
| 649 | There is a difference between the two arguments in this hypothetical function: |
| 650 | |
| 651 | int |
| 652 | foo(a,b) |
| 653 | char &a |
| 654 | char * b |
| 655 | |
| 656 | The first argument to this function would be treated as a char and assigned |
| 657 | to the variable a, and its address would be passed into the function foo. |
| 658 | The second argument would be treated as a string pointer and assigned to the |
| 659 | variable b. The I<value> of b would be passed into the function foo. The |
| 660 | actual call to the function foo that xsubpp generates would look like this: |
| 661 | |
| 662 | foo(&a, b); |
| 663 | |
| 664 | Xsubpp will identically parse the following function argument lists: |
| 665 | |
| 666 | char &a |
| 667 | char&a |
| 668 | char & a |
| 669 | |
| 670 | However, to help ease understanding, it is suggested that you place a "&" |
| 671 | next to the variable name and away from the variable type), and place a |
| 672 | "*" near the variable type, but away from the variable name (as in the |
| 673 | complete example above). By doing so, it is easy to understand exactly |
| 674 | what will be passed to the C function -- it will be whatever is in the |
| 675 | "last column". |
| 676 | |
| 677 | You should take great pains to try to pass the function the type of variable |
| 678 | it wants, when possible. It will save you a lot of trouble in the long run. |
| 679 | |
| 680 | =head2 THE ARGUMENT STACK |
| 681 | |
| 682 | If we look at any of the C code generated by any of the examples except |
| 683 | example 1, you will notice a number of references to ST(n), where n is |
| 684 | usually 0. The "ST" is actually a macro that points to the n'th argument |
| 685 | on the argument stack. ST(0) is thus the first argument passed to the |
| 686 | XSUB, ST(1) is the second argument, and so on. |
| 687 | |
| 688 | When you list the arguments to the XSUB in the .xs file, that tells xsubpp |
| 689 | which argument corresponds to which of the argument stack (i.e., the first |
| 690 | one listed is the first argument, and so on). You invite disaster if you |
| 691 | do not list them in the same order as the function expects them. |
| 692 | |
| 693 | =head2 EXTENDING YOUR EXTENSION |
| 694 | |
| 695 | Sometimes you might want to provide some extra methods or subroutines |
| 696 | to assist in making the interface between Perl and your extension simpler |
| 697 | or easier to understand. These routines should live in the .pm file. |
| 698 | Whether they are automatically loaded when the extension itself is loaded |
| 699 | or only loaded when called depends on where in the .pm file the subroutine |
| 700 | definition is placed. |
| 701 | |
| 702 | =head2 DOCUMENTING YOUR EXTENSION |
| 703 | |
| 704 | There is absolutely no excuse for not documenting your extension. |
| 705 | Documentation belongs in the .pm file. This file will be fed to pod2man, |
| 706 | and the embedded documentation will be converted to the man page format, |
| 707 | then placed in the blib directory. It will be copied to Perl's man |
| 708 | page directory when the extension is installed. |
| 709 | |
| 710 | You may intersperse documentation and Perl code within the .pm file. |
| 711 | In fact, if you want to use method autoloading, you must do this, |
| 712 | as the comment inside the .pm file explains. |
| 713 | |
| 714 | See L<perlpod> for more information about the pod format. |
| 715 | |
| 716 | =head2 INSTALLING YOUR EXTENSION |
| 717 | |
| 718 | Once your extension is complete and passes all its tests, installing it |
| 719 | is quite simple: you simply run "make install". You will either need |
| 720 | to have write permission into the directories where Perl is installed, |
| 721 | or ask your system administrator to run the make for you. |
| 722 | |
| 723 | =head2 SEE ALSO |
| 724 | |
| 725 | For more information, consult L<perlguts>, L<perlxs>, L<perlmod>, |
| 726 | and L<perlpod>. |
| 727 | |
| 728 | =head2 Author |
| 729 | |
| 730 | Jeff Okamoto E<lt>F<okamoto@corp.hp.com>E<gt> |
| 731 | |
| 732 | Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig, |
| 733 | and Tim Bunce. |
| 734 | |
| 735 | =head2 Last Changed |
| 736 | |
| 737 | 1996/7/10 |