0c376047ba57d75e516e4e7a686be0de635fad60
[p5sagit/p5-mst-13.2.git] / pod / perlxs.pod
1 =head1 NAME
2
3 perlxs - XS language reference manual
4
5 =head1 DESCRIPTION
6
7 =head2 Introduction
8
9 XS is a language used to create an extension interface
10 between Perl and some C library which one wishes to use with
11 Perl.  The XS interface is combined with the library to
12 create a new library which can be linked to Perl.  An B<XSUB>
13 is a function in the XS language and is the core component
14 of the Perl application interface.
15
16 The XS compiler is called B<xsubpp>.  This compiler will embed
17 the constructs necessary to let an XSUB, which is really a C
18 function in disguise, manipulate Perl values and creates the
19 glue necessary to let Perl access the XSUB.  The compiler
20 uses B<typemaps> to determine how to map C function parameters
21 and variables to Perl values.  The default typemap handles
22 many common C types.  A supplement typemap must be created
23 to handle special structures and types for the library being
24 linked.
25
26 See L<perlxstut> for a tutorial on the whole extension creation process.
27
28 =head2 On The Road
29
30 Many of the examples which follow will concentrate on creating an
31 interface between Perl and the ONC+ RPC bind library functions.
32 Specifically, the rpcb_gettime() function will be used to demonstrate many
33 features of the XS language.  This function has two parameters; the first
34 is an input parameter and the second is an output parameter.  The function
35 also returns a status value.
36
37         bool_t rpcb_gettime(const char *host, time_t *timep);
38
39 From C this function will be called with the following
40 statements.
41
42      #include <rpc/rpc.h>
43      bool_t status;
44      time_t timep;
45      status = rpcb_gettime( "localhost", &timep );
46
47 If an XSUB is created to offer a direct translation between this function
48 and Perl, then this XSUB will be used from Perl with the following code.
49 The $status and $timep variables will contain the output of the function.
50
51      use RPC;
52      $status = rpcb_gettime( "localhost", $timep );
53
54 The following XS file shows an XS subroutine, or XSUB, which
55 demonstrates one possible interface to the rpcb_gettime()
56 function.  This XSUB represents a direct translation between
57 C and Perl and so preserves the interface even from Perl.
58 This XSUB will be invoked from Perl with the usage shown
59 above.  Note that the first three #include statements, for
60 C<EXTERN.h>, C<perl.h>, and C<XSUB.h>, will always be present at the
61 beginning of an XS file.  This approach and others will be
62 expanded later in this document.
63
64      #include "EXTERN.h"
65      #include "perl.h"
66      #include "XSUB.h"
67      #include <rpc/rpc.h>
68
69      MODULE = RPC  PACKAGE = RPC
70
71      bool_t
72      rpcb_gettime(host,timep)
73           char *host
74           time_t &timep
75           OUTPUT:
76           timep
77
78 Any extension to Perl, including those containing XSUBs,
79 should have a Perl module to serve as the bootstrap which
80 pulls the extension into Perl.  This module will export the
81 extension's functions and variables to the Perl program and
82 will cause the extension's XSUBs to be linked into Perl.
83 The following module will be used for most of the examples
84 in this document and should be used from Perl with the C<use>
85 command as shown earlier.  Perl modules are explained in
86 more detail later in this document.
87
88      package RPC;
89
90      require Exporter;
91      require DynaLoader;
92      @ISA = qw(Exporter DynaLoader);
93      @EXPORT = qw( rpcb_gettime );
94
95      bootstrap RPC;
96      1;
97
98 Throughout this document a variety of interfaces to the rpcb_gettime()
99 XSUB will be explored.  The XSUBs will take their parameters in different
100 orders or will take different numbers of parameters.  In each case the
101 XSUB is an abstraction between Perl and the real C rpcb_gettime()
102 function, and the XSUB must always ensure that the real rpcb_gettime()
103 function is called with the correct parameters.  This abstraction will
104 allow the programmer to create a more Perl-like interface to the C
105 function.
106
107 =head2 The Anatomy of an XSUB
108
109 The following XSUB allows a Perl program to access a C library function
110 called sin().  The XSUB will imitate the C function which takes a single
111 argument and returns a single value.
112
113      double
114      sin(x)
115        double x
116
117 When using C pointers the indirection operator C<*> should be considered
118 part of the type and the address operator C<&> should be considered part of
119 the variable, as is demonstrated in the rpcb_gettime() function above.  See
120 the section on typemaps for more about handling qualifiers and unary
121 operators in C types.
122
123 The function name and the return type must be placed on
124 separate lines.
125
126   INCORRECT                        CORRECT
127
128   double sin(x)                    double
129     double x                       sin(x)
130                                      double x
131
132 The function body may be indented or left-adjusted.  The following example
133 shows a function with its body left-adjusted.  Most examples in this
134 document will indent the body.
135
136   CORRECT
137
138   double
139   sin(x)
140   double x
141
142 =head2 The Argument Stack
143
144 The argument stack is used to store the values which are
145 sent as parameters to the XSUB and to store the XSUB's
146 return value.  In reality all Perl functions keep their
147 values on this stack at the same time, each limited to its
148 own range of positions on the stack.  In this document the
149 first position on that stack which belongs to the active
150 function will be referred to as position 0 for that function.
151
152 XSUBs refer to their stack arguments with the macro B<ST(x)>, where I<x>
153 refers to a position in this XSUB's part of the stack.  Position 0 for that
154 function would be known to the XSUB as ST(0).  The XSUB's incoming
155 parameters and outgoing return values always begin at ST(0).  For many
156 simple cases the B<xsubpp> compiler will generate the code necessary to
157 handle the argument stack by embedding code fragments found in the
158 typemaps.  In more complex cases the programmer must supply the code.
159
160 =head2 The RETVAL Variable
161
162 The RETVAL variable is a magic variable which always matches
163 the return type of the C library function.  The B<xsubpp> compiler will
164 supply this variable in each XSUB and by default will use it to hold the
165 return value of the C library function being called.  In simple cases the
166 value of RETVAL will be placed in ST(0) of the argument stack where it can
167 be received by Perl as the return value of the XSUB.
168
169 If the XSUB has a return type of C<void> then the compiler will
170 not supply a RETVAL variable for that function.  When using
171 the PPCODE: directive the RETVAL variable may not be needed.
172
173 =head2 The MODULE Keyword
174
175 The MODULE keyword is used to start the XS code and to
176 specify the package of the functions which are being
177 defined.  All text preceding the first MODULE keyword is
178 considered C code and is passed through to the output
179 untouched.  Every XS module will have a bootstrap function
180 which is used to hook the XSUBs into Perl.  The package name
181 of this bootstrap function will match the value of the last
182 MODULE statement in the XS source files.  The value of
183 MODULE should always remain constant within the same XS
184 file, though this is not required.
185
186 The following example will start the XS code and will place
187 all functions in a package named RPC.
188
189      MODULE = RPC
190
191 =head2 The PACKAGE Keyword
192
193 When functions within an XS source file must be separated into packages
194 the PACKAGE keyword should be used.  This keyword is used with the MODULE
195 keyword and must follow immediately after it when used.
196
197      MODULE = RPC  PACKAGE = RPC
198
199      [ XS code in package RPC ]
200
201      MODULE = RPC  PACKAGE = RPCB
202
203      [ XS code in package RPCB ]
204
205      MODULE = RPC  PACKAGE = RPC
206
207      [ XS code in package RPC ]
208
209 Although this keyword is optional and in some cases provides redundant
210 information it should always be used.  This keyword will ensure that the
211 XSUBs appear in the desired package.
212
213 =head2 The PREFIX Keyword
214
215 The PREFIX keyword designates prefixes which should be
216 removed from the Perl function names.  If the C function is
217 C<rpcb_gettime()> and the PREFIX value is C<rpcb_> then Perl will
218 see this function as C<gettime()>.
219
220 This keyword should follow the PACKAGE keyword when used.
221 If PACKAGE is not used then PREFIX should follow the MODULE
222 keyword.
223
224      MODULE = RPC  PREFIX = rpc_
225
226      MODULE = RPC  PACKAGE = RPCB  PREFIX = rpcb_
227
228 =head2 The OUTPUT: Keyword
229
230 The OUTPUT: keyword indicates that certain function parameters should be
231 updated (new values made visible to Perl) when the XSUB terminates or that
232 certain values should be returned to the calling Perl function.  For
233 simple functions, such as the sin() function above, the RETVAL variable is
234 automatically designated as an output value.  In more complex functions
235 the B<xsubpp> compiler will need help to determine which variables are output
236 variables.
237
238 This keyword will normally be used to complement the CODE:  keyword.
239 The RETVAL variable is not recognized as an output variable when the
240 CODE: keyword is present.  The OUTPUT:  keyword is used in this
241 situation to tell the compiler that RETVAL really is an output
242 variable.
243
244 The OUTPUT: keyword can also be used to indicate that function parameters
245 are output variables.  This may be necessary when a parameter has been
246 modified within the function and the programmer would like the update to
247 be seen by Perl.
248
249      bool_t
250      rpcb_gettime(host,timep)
251           char *host
252           time_t &timep
253           OUTPUT:
254           timep
255
256 The OUTPUT: keyword will also allow an output parameter to
257 be mapped to a matching piece of code rather than to a
258 typemap.
259
260      bool_t
261      rpcb_gettime(host,timep)
262           char *host
263           time_t &timep
264           OUTPUT:
265           timep sv_setnv(ST(1), (double)timep);
266
267 =head2 The CODE: Keyword
268
269 This keyword is used in more complicated XSUBs which require
270 special handling for the C function.  The RETVAL variable is
271 available but will not be returned unless it is specified
272 under the OUTPUT: keyword.
273
274 The following XSUB is for a C function which requires special handling of
275 its parameters.  The Perl usage is given first.
276
277      $status = rpcb_gettime( "localhost", $timep );
278
279 The XSUB follows. 
280
281      bool_t
282      rpcb_gettime(host,timep)
283           char *host
284           time_t timep
285           CODE:
286                RETVAL = rpcb_gettime( host, &timep );
287           OUTPUT:
288           timep
289           RETVAL
290
291 =head2 The INIT: Keyword
292
293 The INIT: keyword allows initialization to be inserted into the XSUB before
294 the compiler generates the call to the C function.  Unlike the CODE: keyword
295 above, this keyword does not affect the way the compiler handles RETVAL.
296
297     bool_t
298     rpcb_gettime(host,timep)
299           char *host
300           time_t &timep
301           INIT:
302           printf("# Host is %s\n", host );
303           OUTPUT:
304           timep
305
306 =head2 The NO_INIT Keyword
307
308 The NO_INIT keyword is used to indicate that a function
309 parameter is being used as only an output value.  The B<xsubpp>
310 compiler will normally generate code to read the values of
311 all function parameters from the argument stack and assign
312 them to C variables upon entry to the function.  NO_INIT
313 will tell the compiler that some parameters will be used for
314 output rather than for input and that they will be handled
315 before the function terminates.
316
317 The following example shows a variation of the rpcb_gettime() function.
318 This function uses the timep variable as only an output variable and does
319 not care about its initial contents.
320
321      bool_t
322      rpcb_gettime(host,timep)
323           char *host
324           time_t &timep = NO_INIT
325           OUTPUT:
326           timep
327
328 =head2 Initializing Function Parameters
329
330 Function parameters are normally initialized with their
331 values from the argument stack.  The typemaps contain the
332 code segments which are used to transfer the Perl values to
333 the C parameters.  The programmer, however, is allowed to
334 override the typemaps and supply alternate initialization
335 code.
336
337 The following code demonstrates how to supply initialization code for
338 function parameters.  The initialization code is eval'd by the compiler
339 before it is added to the output so anything which should be interpreted
340 literally, such as double quotes, must be protected with backslashes.
341
342      bool_t
343      rpcb_gettime(host,timep)
344           char *host = (char *)SvPV(ST(0),na);
345           time_t &timep = 0;
346           OUTPUT:
347           timep
348
349 This should not be used to supply default values for parameters.  One
350 would normally use this when a function parameter must be processed by
351 another library function before it can be used.  Default parameters are
352 covered in the next section.
353
354 =head2 Default Parameter Values
355
356 Default values can be specified for function parameters by
357 placing an assignment statement in the parameter list.  The
358 default value may be a number or a string.  Defaults should
359 always be used on the right-most parameters only.
360
361 To allow the XSUB for rpcb_gettime() to have a default host
362 value the parameters to the XSUB could be rearranged.  The
363 XSUB will then call the real rpcb_gettime() function with
364 the parameters in the correct order.  Perl will call this
365 XSUB with either of the following statements.
366
367      $status = rpcb_gettime( $timep, $host );
368
369      $status = rpcb_gettime( $timep );
370
371 The XSUB will look like the code  which  follows.   A  CODE:
372 block  is used to call the real rpcb_gettime() function with
373 the parameters in the correct order for that function.
374
375      bool_t
376      rpcb_gettime(timep,host="localhost")
377           char *host
378           time_t timep = NO_INIT
379           CODE:
380                RETVAL = rpcb_gettime( host, &timep );
381           OUTPUT:
382           timep
383           RETVAL
384
385 =head2 The PREINIT: Keyword
386
387 The PREINIT: keyword allows extra variables to be declared before the
388 typemaps are expanded.  If a variable is declared in a CODE: block then that
389 variable will follow any typemap code.  This may result in a C syntax
390 error.  To force the variable to be declared before the typemap code, place
391 it into a PREINIT: block.  The PREINIT: keyword may be used one or more
392 times within an XSUB.
393
394 The following examples are equivalent, but if the code is using complex
395 typemaps then the first example is safer.
396
397      bool_t
398      rpcb_gettime(timep)
399           time_t timep = NO_INIT
400           PREINIT:
401           char *host = "localhost";
402           CODE:
403           RETVAL = rpcb_gettime( host, &timep );
404           OUTPUT:
405           timep
406           RETVAL
407
408 A correct, but error-prone example.
409
410      bool_t
411      rpcb_gettime(timep)
412           time_t timep = NO_INIT
413           CODE:
414           char *host = "localhost";
415           RETVAL = rpcb_gettime( host, &timep );
416           OUTPUT:
417           timep
418           RETVAL
419
420 =head2 The INPUT: Keyword
421
422 The XSUB's parameters are usually evaluated immediately after entering the
423 XSUB.  The INPUT: keyword can be used to force those parameters to be
424 evaluated a little later.  The INPUT: keyword can be used multiple times
425 within an XSUB and can be used to list one or more input variables.  This
426 keyword is used with the PREINIT: keyword.
427
428 The following example shows how the input parameter C<timep> can be
429 evaluated late, after a PREINIT.
430
431     bool_t
432     rpcb_gettime(host,timep)
433           char *host
434           PREINIT:
435           time_t tt;
436           INPUT:
437           time_t timep
438           CODE:
439                RETVAL = rpcb_gettime( host, &tt );
440                timep = tt;
441           OUTPUT:
442           timep
443           RETVAL
444
445 The next example shows each input parameter evaluated late.
446
447     bool_t
448     rpcb_gettime(host,timep)
449           PREINIT:
450           time_t tt;
451           INPUT:
452           char *host
453           PREINIT:
454           char *h;
455           INPUT:
456           time_t timep
457           CODE:
458                h = host;
459                RETVAL = rpcb_gettime( h, &tt );
460                timep = tt;
461           OUTPUT:
462           timep
463           RETVAL
464
465 =head2 Variable-length Parameter Lists
466
467 XSUBs can have variable-length parameter lists by specifying an ellipsis
468 C<(...)> in the parameter list.  This use of the ellipsis is similar to that
469 found in ANSI C.  The programmer is able to determine the number of
470 arguments passed to the XSUB by examining the C<items> variable which the
471 B<xsubpp> compiler supplies for all XSUBs.  By using this mechanism one can
472 create an XSUB which accepts a list of parameters of unknown length.
473
474 The I<host> parameter for the rpcb_gettime() XSUB can be
475 optional so the ellipsis can be used to indicate that the
476 XSUB will take a variable number of parameters.  Perl should
477 be able to call this XSUB with either of the following statements.
478
479      $status = rpcb_gettime( $timep, $host );
480
481      $status = rpcb_gettime( $timep );
482
483 The XS code, with ellipsis, follows.
484
485      bool_t
486      rpcb_gettime(timep, ...)
487           time_t timep = NO_INIT
488           PREINIT:
489           char *host = "localhost";
490           CODE:
491                   if( items > 1 )
492                        host = (char *)SvPV(ST(1), na);
493                   RETVAL = rpcb_gettime( host, &timep );
494           OUTPUT:
495           timep
496           RETVAL
497
498 =head2 The PPCODE: Keyword
499
500 The PPCODE: keyword is an alternate form of the CODE: keyword and is used
501 to tell the B<xsubpp> compiler that the programmer is supplying the code to
502 control the argument stack for the XSUBs return values.  Occasionally one
503 will want an XSUB to return a list of values rather than a single value.
504 In these cases one must use PPCODE: and then explicitly push the list of
505 values on the stack.  The PPCODE: and CODE:  keywords are not used
506 together within the same XSUB.
507
508 The following XSUB will call the C rpcb_gettime() function
509 and will return its two output values, timep and status, to
510 Perl as a single list.
511
512      void
513      rpcb_gettime(host)
514           char *host
515           PREINIT:
516           time_t  timep;
517           bool_t  status;
518           PPCODE:
519           status = rpcb_gettime( host, &timep );
520           EXTEND(sp, 2);
521           PUSHs(sv_2mortal(newSViv(status)));
522           PUSHs(sv_2mortal(newSViv(timep)));
523
524 Notice that the programmer must supply the C code necessary
525 to have the real rpcb_gettime() function called and to have
526 the return values properly placed on the argument stack.
527
528 The C<void> return type for this function tells the B<xsubpp> compiler that
529 the RETVAL variable is not needed or used and that it should not be created.
530 In most scenarios the void return type should be used with the PPCODE:
531 directive.
532
533 The EXTEND() macro is used to make room on the argument
534 stack for 2 return values.  The PPCODE: directive causes the
535 B<xsubpp> compiler to create a stack pointer called C<sp>, and it
536 is this pointer which is being used in the EXTEND() macro.
537 The values are then pushed onto the stack with the PUSHs()
538 macro.
539
540 Now the rpcb_gettime() function can be used from Perl with
541 the following statement.
542
543      ($status, $timep) = rpcb_gettime("localhost");
544
545 =head2 Returning Undef And Empty Lists
546
547 Occasionally the programmer will want to simply return
548 C<undef> or an empty list if a function fails rather than a
549 separate status value.  The rpcb_gettime() function offers
550 just this situation.  If the function succeeds we would like
551 to have it return the time and if it fails we would like to
552 have undef returned.  In the following Perl code the value
553 of $timep will either be undef or it will be a valid time.
554
555      $timep = rpcb_gettime( "localhost" );
556
557 The following XSUB uses the C<void> return type to disable the generation of
558 the RETVAL variable and uses a CODE: block to indicate to the compiler
559 that the programmer has supplied all the necessary code.  The
560 sv_newmortal() call will initialize the return value to undef, making that
561 the default return value.
562
563      void
564      rpcb_gettime(host)
565           char *  host
566           PREINIT:
567           time_t  timep;
568           bool_t x;
569           CODE:
570           ST(0) = sv_newmortal();
571           if( rpcb_gettime( host, &timep ) )
572                sv_setnv( ST(0), (double)timep);
573
574 The next example demonstrates how one would place an explicit undef in the
575 return value, should the need arise.
576
577      void
578      rpcb_gettime(host)
579           char *  host
580           PREINIT:
581           time_t  timep;
582           bool_t x;
583           CODE:
584           ST(0) = sv_newmortal();
585           if( rpcb_gettime( host, &timep ) ){
586                sv_setnv( ST(0), (double)timep);
587           }
588           else{
589                ST(0) = &sv_undef;
590           }
591
592 To return an empty list one must use a PPCODE: block and
593 then not push return values on the stack.
594
595      void
596      rpcb_gettime(host)
597           char *host
598           PREINIT:
599           time_t  timep;
600           PPCODE:
601           if( rpcb_gettime( host, &timep ) )
602                PUSHs(sv_2mortal(newSViv(timep)));
603           else{
604           /* Nothing pushed on stack, so an empty */
605           /* list is implicitly returned. */
606           }
607
608 =head2 The REQUIRE: Keyword
609
610 The REQUIRE: keyword is used to indicate the minimum version of the
611 B<xsubpp> compiler needed to compile the XS module.  An XS module which
612 contains the following statement will only compile with B<xsubpp> version
613 1.922 or greater:
614
615         REQUIRE: 1.922
616
617 =head2 The CLEANUP: Keyword
618
619 This keyword can be used when an XSUB requires special cleanup procedures
620 before it terminates.  When the CLEANUP:  keyword is used it must follow
621 any CODE:, PPCODE:, or OUTPUT: blocks which are present in the XSUB.  The
622 code specified for the cleanup block will be added as the last statements
623 in the XSUB.
624
625 =head2 The BOOT: Keyword
626
627 The BOOT: keyword is used to add code to the extension's bootstrap
628 function.  The bootstrap function is generated by the B<xsubpp> compiler and
629 normally holds the statements necessary to register any XSUBs with Perl.
630 With the BOOT: keyword the programmer can tell the compiler to add extra
631 statements to the bootstrap function.
632
633 This keyword may be used any time after the first MODULE keyword and should
634 appear on a line by itself.  The first blank line after the keyword will
635 terminate the code block.
636
637      BOOT:
638      # The following message will be printed when the
639      # bootstrap function executes.
640      printf("Hello from the bootstrap!\n");
641
642 =head2 The VERSIONCHECK: Keyword
643
644 The VERSIONCHECK: keyword corresponds to B<xsubpp>'s C<-versioncheck> and
645 C<-noversioncheck> options.  This keyword overrides the commandline
646 options.  Version checking is enabled by default.  When version checking is
647 enabled the XS module will attempt to verify that its version matches the
648 version of the PM module.
649
650 To enable version checking:
651
652     VERSIONCHECK: ENABLE
653
654 To disable version checking:
655
656     VERSIONCHECK: DISABLE
657
658 =head2 The PROTOTYPES: Keyword
659
660 The PROTOTYPES: keyword corresponds to B<xsubpp>'s C<-prototypes> and
661 C<-noprototypes> options.  This keyword overrides the commandline options.
662 Prototypes are enabled by default.  When prototypes are enabled XSUBs will
663 be given Perl prototypes.  This keyword may be used multiple times in an XS
664 module to enable and disable prototypes for different parts of the module.
665
666 To enable prototypes:
667
668     PROTOTYPES: ENABLE
669
670 To disable prototypes:
671
672     PROTOTYPES: DISABLE
673
674 =head2 The PROTOTYPE: Keyword
675
676 This keyword is similar to the PROTOTYPES: keyword above but can be used to
677 force B<xsubpp> to use a specific prototype for the XSUB.  This keyword
678 overrides all other prototype options and keywords but affects only the
679 current XSUB.  Consult L<perlsub/Prototypes> for information about Perl
680 prototypes.
681
682     bool_t
683     rpcb_gettime(timep, ...)
684           time_t timep = NO_INIT
685           PROTOTYPE: $;$
686           PREINIT:
687           char *host = "localhost";
688           CODE:
689                   if( items > 1 )
690                        host = (char *)SvPV(ST(1), na);
691                   RETVAL = rpcb_gettime( host, &timep );
692           OUTPUT:
693           timep
694           RETVAL
695
696 =head2 The ALIAS: Keyword
697
698 The ALIAS: keyword allows an XSUB to have two more more unique Perl names
699 and to know which of those names was used when it was invoked.  The Perl
700 names may be fully-qualified with package names.  Each alias is given an
701 index.  The compiler will setup a variable called C<ix> which contain the
702 index of the alias which was used.  When the XSUB is called with its
703 declared name C<ix> will be 0.
704
705 The following example will create aliases C<FOO::gettime()> and
706 C<BAR::getit()> for this function.
707
708     bool_t
709     rpcb_gettime(host,timep)
710           char *host
711           time_t &timep
712           ALIAS:
713             FOO::gettime = 1
714             BAR::getit = 2
715           INIT:
716           printf("# ix = %d\n", ix );
717           OUTPUT:
718           timep
719
720 =head2 The INCLUDE: Keyword
721
722 This keyword can be used to pull other files into the XS module.  The other
723 files may have XS code.  INCLUDE: can also be used to run a command to
724 generate the XS code to be pulled into the module.
725
726 The file F<Rpcb1.xsh> contains our C<rpcb_gettime()> function:
727
728     bool_t
729     rpcb_gettime(host,timep)
730           char *host
731           time_t &timep
732           OUTPUT:
733           timep
734
735 The XS module can use INCLUDE: to pull that file into it.
736
737     INCLUDE: Rpcb1.xsh
738
739 If the parameters to the INCLUDE: keyword are followed by a pipe (C<|>) then
740 the compiler will interpret the parameters as a command.
741
742     INCLUDE: cat Rpcb1.xsh |
743
744 =head2 The CASE: Keyword
745
746 The CASE: keyword allows an XSUB to have multiple distinct parts with each
747 part acting as a virtual XSUB.  CASE: is greedy and if it is used then all
748 other XS keywords must be contained within a CASE:.  This means nothing may
749 precede the first CASE: in the XSUB and anything following the last CASE: is
750 included in that case.
751
752 A CASE: might switch via a parameter of the XSUB, via the C<ix> ALIAS:
753 variable (see L<"The ALIAS: Keyword">), or maybe via the C<items> variable
754 (see L<"Variable-length Parameter Lists">).  The last CASE: becomes the
755 B<default> case if it is not associated with a conditional.  The following
756 example shows CASE switched via C<ix> with a function C<rpcb_gettime()>
757 having an alias C<x_gettime()>.  When the function is called as
758 C<rpcb_gettime()> it's parameters are the usual C<(char *host, time_t
759 *timep)>, but when the function is called as C<x_gettime()> is parameters are
760 reversed, C<(time_t *timep, char *host)>.
761
762     long
763     rpcb_gettime(a,b)
764       CASE: ix == 1
765           ALIAS:
766           x_gettime = 1
767           INPUT:
768           # 'a' is timep, 'b' is host
769           char *b
770           time_t a = NO_INIT
771           CODE:
772                RETVAL = rpcb_gettime( b, &a );
773           OUTPUT:
774           a
775           RETVAL
776       CASE:
777           # 'a' is host, 'b' is timep
778           char *a
779           time_t &b = NO_INIT
780           OUTPUT:
781           b
782           RETVAL
783
784 That function can be called with either of the following statements.  Note
785 the different argument lists.
786
787         $status = rpcb_gettime( $host, $timep );
788
789         $status = x_gettime( $timep, $host );
790
791 =head2 The & Unary Operator
792
793 The & unary operator is used to tell the compiler that it should dereference
794 the object when it calls the C function.  This is used when a CODE: block is
795 not used and the object is a not a pointer type (the object is an C<int> or
796 C<long> but not a C<int*> or C<long*>).
797
798 The following XSUB will generate incorrect C code.  The xsubpp compiler will
799 turn this into code which calls C<rpcb_gettime()> with parameters C<(char
800 *host, time_t timep)>, but the real C<rpcb_gettime()> wants the C<timep>
801 parameter to be of type C<time_t*> rather than C<time_t>.
802
803     bool_t
804     rpcb_gettime(host,timep)
805           char *host
806           time_t timep
807           OUTPUT:
808           timep
809
810 That problem is corrected by using the C<&> operator.  The xsubpp compiler
811 will now turn this into code which calls C<rpcb_gettime()> correctly with
812 parameters C<(char *host, time_t *timep)>.  It does this by carrying the
813 C<&> through, so the function call looks like C<rpcb_gettime(host, &timep)>.
814
815     bool_t
816     rpcb_gettime(host,timep)
817           char *host
818           time_t &timep
819           OUTPUT:
820           timep
821
822 =head2 Inserting Comments and C Preprocessor Directives
823
824 Comments and C preprocessor directives are allowed within
825 CODE:, PPCODE:, BOOT:, and CLEANUP: blocks.  The compiler
826 will pass the preprocessor directives through untouched and
827 will remove the commented lines.  Comments can be added to
828 XSUBs by placing a C<#> at the beginning of the line.  Care
829 should be taken to avoid making the comment look like a C
830 preprocessor directive, lest it be interpreted as such.
831
832 =head2 Using XS With C++
833
834 If a function is defined as a C++ method then it will assume
835 its first argument is an object pointer.  The object pointer
836 will be stored in a variable called THIS.  The object should
837 have been created by C++ with the new() function and should
838 be blessed by Perl with the sv_setref_pv() macro.  The
839 blessing of the object by Perl can be handled by a typemap.  An example
840 typemap is shown at the end of this section.
841
842 If the method is defined as static it will call the C++
843 function using the class::method() syntax.  If the method is not static
844 the function will be called using the THIS->method() syntax.
845
846 The next examples will use the following C++ class.
847
848      class colors {
849           public:
850           colors();
851           ~colors();
852           int blue();
853           void set_blue( int );
854
855           private:
856           int c_blue;
857      };
858
859 The XSUBs for the blue() and set_blue() methods are defined with the class
860 name but the parameter for the object (THIS, or "self") is implicit and is
861 not listed.
862
863      int
864      color::blue()
865
866      void
867      color::set_blue( val )
868           int val
869
870 Both functions will expect an object as the first parameter.  The xsubpp
871 compiler will call that object C<THIS> and will use it to call the specified
872 method.  So in the C++ code the blue() and set_blue() methods will be called
873 in the following manner.
874
875      RETVAL = THIS->blue();
876
877      THIS->set_blue( val );
878
879 If the function's name is B<DESTROY> then the C++ C<delete> function will be
880 called and C<THIS> will be given as its parameter.
881
882      void
883      color::DESTROY()
884
885 The C++ code will call C<delete>.
886
887      delete THIS;
888
889 If the function's name is B<new> then the C++ C<new> function will be called
890 to create a dynamic C++ object.  The XSUB will expect the class name, which
891 will be kept in a variable called C<CLASS>, to be given as the first
892 argument.
893
894      color *
895      color::new()
896
897 The C++ code will call C<new>.
898
899         RETVAL = new color();
900
901 The following is an example of a typemap that could be used for this C++
902 example.
903
904     TYPEMAP
905     color *             O_OBJECT
906
907     OUTPUT
908     # The Perl object is blessed into 'CLASS', which should be a
909     # char* having the name of the package for the blessing.
910     O_OBJECT
911         sv_setref_pv( $arg, CLASS, (void*)$var );
912     
913     INPUT
914     O_OBJECT
915         if( sv_isobject($arg) && (SvTYPE(SvRV($arg)) == SVt_PVMG) )
916                 $var = ($type)SvIV((SV*)SvRV( $arg ));
917         else{
918                 warn( \"${Package}::$func_name() -- $var is not a blessed SV reference\" );
919                 XSRETURN_UNDEF;
920         }
921
922 =head2 Interface Strategy
923
924 When designing an interface between Perl and a C library a straight
925 translation from C to XS is often sufficient.  The interface will often be
926 very C-like and occasionally nonintuitive, especially when the C function
927 modifies one of its parameters.  In cases where the programmer wishes to
928 create a more Perl-like interface the following strategy may help to
929 identify the more critical parts of the interface.
930
931 Identify the C functions which modify their parameters.  The XSUBs for
932 these functions may be able to return lists to Perl, or may be
933 candidates to return undef or an empty list in case of failure.
934
935 Identify which values are used by only the C and XSUB functions
936 themselves.  If Perl does not need to access the contents of the value
937 then it may not be necessary to provide a translation for that value
938 from C to Perl.
939
940 Identify the pointers in the C function parameter lists and return
941 values.  Some pointers can be handled in XS with the & unary operator on
942 the variable name while others will require the use of the * operator on
943 the type name.  In general it is easier to work with the & operator.
944
945 Identify the structures used by the C functions.  In many
946 cases it may be helpful to use the T_PTROBJ typemap for
947 these structures so they can be manipulated by Perl as
948 blessed objects.
949
950 =head2 Perl Objects And C Structures
951
952 When dealing with C structures one should select either
953 B<T_PTROBJ> or B<T_PTRREF> for the XS type.  Both types are
954 designed to handle pointers to complex objects.  The
955 T_PTRREF type will allow the Perl object to be unblessed
956 while the T_PTROBJ type requires that the object be blessed.
957 By using T_PTROBJ one can achieve a form of type-checking
958 because the XSUB will attempt to verify that the Perl object
959 is of the expected type.
960
961 The following XS code shows the getnetconfigent() function which is used
962 with ONC+ TIRPC.  The getnetconfigent() function will return a pointer to a
963 C structure and has the C prototype shown below.  The example will
964 demonstrate how the C pointer will become a Perl reference.  Perl will
965 consider this reference to be a pointer to a blessed object and will
966 attempt to call a destructor for the object.  A destructor will be
967 provided in the XS source to free the memory used by getnetconfigent().
968 Destructors in XS can be created by specifying an XSUB function whose name
969 ends with the word B<DESTROY>.  XS destructors can be used to free memory
970 which may have been malloc'd by another XSUB.
971
972      struct netconfig *getnetconfigent(const char *netid);
973
974 A C<typedef> will be created for C<struct netconfig>.  The Perl
975 object will be blessed in a class matching the name of the C
976 type, with the tag C<Ptr> appended, and the name should not
977 have embedded spaces if it will be a Perl package name.  The
978 destructor will be placed in a class corresponding to the
979 class of the object and the PREFIX keyword will be used to
980 trim the name to the word DESTROY as Perl will expect.
981
982      typedef struct netconfig Netconfig;
983
984      MODULE = RPC  PACKAGE = RPC
985
986      Netconfig *
987      getnetconfigent(netid)
988           char *netid
989
990      MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_
991
992      void
993      rpcb_DESTROY(netconf)
994           Netconfig *netconf
995           CODE:
996           printf("Now in NetconfigPtr::DESTROY\n");
997           free( netconf );
998
999 This example requires the following typemap entry.  Consult the typemap
1000 section for more information about adding new typemaps for an extension.
1001
1002      TYPEMAP
1003      Netconfig *  T_PTROBJ
1004
1005 This example will be used with the following Perl statements.
1006
1007      use RPC;
1008      $netconf = getnetconfigent("udp");
1009
1010 When Perl destroys the object referenced by $netconf it will send the
1011 object to the supplied XSUB DESTROY function.  Perl cannot determine, and
1012 does not care, that this object is a C struct and not a Perl object.  In
1013 this sense, there is no difference between the object created by the
1014 getnetconfigent() XSUB and an object created by a normal Perl subroutine.
1015
1016 =head2 The Typemap
1017
1018 The typemap is a collection of code fragments which are used by the B<xsubpp>
1019 compiler to map C function parameters and values to Perl values.  The
1020 typemap file may consist of three sections labeled C<TYPEMAP>, C<INPUT>, and
1021 C<OUTPUT>.  The INPUT section tells the compiler how to translate Perl values
1022 into variables of certain C types.  The OUTPUT section tells the compiler
1023 how to translate the values from certain C types into values Perl can
1024 understand.  The TYPEMAP section tells the compiler which of the INPUT and
1025 OUTPUT code fragments should be used to map a given C type to a Perl value.
1026 Each of the sections of the typemap must be preceded by one of the TYPEMAP,
1027 INPUT, or OUTPUT keywords.
1028
1029 The default typemap in the C<ext> directory of the Perl source contains many
1030 useful types which can be used by Perl extensions.  Some extensions define
1031 additional typemaps which they keep in their own directory.  These
1032 additional typemaps may reference INPUT and OUTPUT maps in the main
1033 typemap.  The B<xsubpp> compiler will allow the extension's own typemap to
1034 override any mappings which are in the default typemap.
1035
1036 Most extensions which require a custom typemap will need only the TYPEMAP
1037 section of the typemap file.  The custom typemap used in the
1038 getnetconfigent() example shown earlier demonstrates what may be the typical
1039 use of extension typemaps.  That typemap is used to equate a C structure
1040 with the T_PTROBJ typemap.  The typemap used by getnetconfigent() is shown
1041 here.  Note that the C type is separated from the XS type with a tab and
1042 that the C unary operator C<*> is considered to be a part of the C type name.
1043
1044      TYPEMAP
1045      Netconfig *<tab>T_PTROBJ
1046
1047 =head1 EXAMPLES
1048
1049 File C<RPC.xs>: Interface to some ONC+ RPC bind library functions.
1050
1051      #include "EXTERN.h"
1052      #include "perl.h"
1053      #include "XSUB.h"
1054
1055      #include <rpc/rpc.h>
1056
1057      typedef struct netconfig Netconfig;
1058
1059      MODULE = RPC  PACKAGE = RPC
1060
1061      void
1062      rpcb_gettime(host="localhost")
1063           char *host
1064           PREINIT:
1065           time_t  timep;
1066           CODE:
1067           ST(0) = sv_newmortal();
1068           if( rpcb_gettime( host, &timep ) )
1069                sv_setnv( ST(0), (double)timep );
1070
1071      Netconfig *
1072      getnetconfigent(netid="udp")
1073           char *netid
1074
1075      MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_
1076
1077      void
1078      rpcb_DESTROY(netconf)
1079           Netconfig *netconf
1080           CODE:
1081           printf("NetconfigPtr::DESTROY\n");
1082           free( netconf );
1083
1084 File C<typemap>: Custom typemap for RPC.xs.
1085
1086      TYPEMAP
1087      Netconfig *  T_PTROBJ
1088
1089 File C<RPC.pm>: Perl module for the RPC extension.
1090
1091      package RPC;
1092
1093      require Exporter;
1094      require DynaLoader;
1095      @ISA = qw(Exporter DynaLoader);
1096      @EXPORT = qw(rpcb_gettime getnetconfigent);
1097
1098      bootstrap RPC;
1099      1;
1100
1101 File C<rpctest.pl>: Perl test program for the RPC extension.
1102
1103      use RPC;
1104
1105      $netconf = getnetconfigent();
1106      $a = rpcb_gettime();
1107      print "time = $a\n";
1108      print "netconf = $netconf\n";
1109
1110      $netconf = getnetconfigent("tcp");
1111      $a = rpcb_gettime("poplar");
1112      print "time = $a\n";
1113      print "netconf = $netconf\n";
1114
1115
1116 =head1 XS VERSION
1117
1118 This document covers features supported by C<xsubpp> 1.931.
1119
1120 =head1 AUTHOR
1121
1122 Dean Roehrich F<E<lt>roehrich@cray.comE<gt>>
1123 Jan 25, 1996