06b8230c88fd58265425c6cf69050bb937c33875
[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 an interface description file format used to create an extension
10 interface between Perl and C code (or a C library) which one wishes
11 to use with Perl.  The XS interface is combined with the library to
12 create a new library which can then be either dynamically loaded
13 or statically linked into perl.  The XS interface description is
14 written in the XS language and is the core component of the Perl
15 extension interface.
16
17 An B<XSUB> forms the basic unit of the XS interface.  After compilation
18 by the B<xsubpp> compiler, each XSUB amounts to a C function definition
19 which will provide the glue between Perl calling conventions and C
20 calling conventions.
21
22 The glue code pulls the arguments from the Perl stack, converts these
23 Perl values to the formats expected by a C function, call this C function,
24 transfers the return values of the C function back to Perl.
25 Return values here may be a conventional C return value or any C
26 function arguments that may serve as output parameters.  These return
27 values may be passed back to Perl either by putting them on the
28 Perl stack, or by modifying the arguments supplied from the Perl side.
29
30 The above is a somewhat simplified view of what really happens.  Since
31 Perl allows more flexible calling conventions than C, XSUBs may do much
32 more in practice, such as checking input parameters for validity,
33 throwing exceptions (or returning undef/empty list) if the return value
34 from the C function indicates failure, calling different C functions
35 based on numbers and types of the arguments, providing an object-oriented
36 interface, etc.
37
38 Of course, one could write such glue code directly in C.  However, this
39 would be a tedious task, especially if one needs to write glue for
40 multiple C functions, and/or one is not familiar enough with the Perl
41 stack discipline and other such arcana.  XS comes to the rescue here:
42 instead of writing this glue C code in long-hand, one can write
43 a more concise short-hand I<description> of what should be done by
44 the glue, and let the XS compiler B<xsubpp> handle the rest.
45
46 The XS language allows one to describe the mapping between how the C
47 routine is used, and how the corresponding Perl routine is used.  It
48 also allows creation of Perl routines which are directly translated to
49 C code and which are not related to a pre-existing C function.  In cases
50 when the C interface coincides with the Perl interface, the XSUB
51 declaration is almost identical to a declaration of a C function (in K&R
52 style).  In such circumstances, there is another tool called C<h2xs>
53 that is able to translate an entire C header file into a corresponding
54 XS file that will provide glue to the functions/macros described in
55 the header file.
56
57 The XS compiler is called B<xsubpp>.  This compiler creates
58 the constructs necessary to let an XSUB manipulate Perl values, and
59 creates the glue necessary to let Perl call the XSUB.  The compiler
60 uses B<typemaps> to determine how to map C function parameters
61 and output values to Perl values and back.  The default typemap
62 (which comes with Perl) handles many common C types.  A supplementary
63 typemap may also be needed to handle any special structures and types
64 for the library being linked.
65
66 A file in XS format starts with a C language section which goes until the
67 first C<MODULE =Z<>> directive.  Other XS directives and XSUB definitions
68 may follow this line.  The "language" used in this part of the file
69 is usually referred to as the XS language.
70
71 See L<perlxstut> for a tutorial on the whole extension creation process.
72
73 Note: For some extensions, Dave Beazley's SWIG system may provide a
74 significantly more convenient mechanism for creating the extension
75 glue code.  See http://www.swig.org/ for more information.
76
77 =head2 On The Road
78
79 Many of the examples which follow will concentrate on creating an interface
80 between Perl and the ONC+ RPC bind library functions.  The rpcb_gettime()
81 function is used to demonstrate many features of the XS language.  This
82 function has two parameters; the first is an input parameter and the second
83 is an output parameter.  The function also returns a status value.
84
85         bool_t rpcb_gettime(const char *host, time_t *timep);
86
87 From C this function will be called with the following
88 statements.
89
90      #include <rpc/rpc.h>
91      bool_t status;
92      time_t timep;
93      status = rpcb_gettime( "localhost", &timep );
94
95 If an XSUB is created to offer a direct translation between this function
96 and Perl, then this XSUB will be used from Perl with the following code.
97 The $status and $timep variables will contain the output of the function.
98
99      use RPC;
100      $status = rpcb_gettime( "localhost", $timep );
101
102 The following XS file shows an XS subroutine, or XSUB, which
103 demonstrates one possible interface to the rpcb_gettime()
104 function.  This XSUB represents a direct translation between
105 C and Perl and so preserves the interface even from Perl.
106 This XSUB will be invoked from Perl with the usage shown
107 above.  Note that the first three #include statements, for
108 C<EXTERN.h>, C<perl.h>, and C<XSUB.h>, will always be present at the
109 beginning of an XS file.  This approach and others will be
110 expanded later in this document.
111
112      #include "EXTERN.h"
113      #include "perl.h"
114      #include "XSUB.h"
115      #include <rpc/rpc.h>
116
117      MODULE = RPC  PACKAGE = RPC
118
119      bool_t
120      rpcb_gettime(host,timep)
121           char *host
122           time_t &timep
123         OUTPUT:
124           timep
125
126 Any extension to Perl, including those containing XSUBs,
127 should have a Perl module to serve as the bootstrap which
128 pulls the extension into Perl.  This module will export the
129 extension's functions and variables to the Perl program and
130 will cause the extension's XSUBs to be linked into Perl.
131 The following module will be used for most of the examples
132 in this document and should be used from Perl with the C<use>
133 command as shown earlier.  Perl modules are explained in
134 more detail later in this document.
135
136      package RPC;
137
138      require Exporter;
139      require DynaLoader;
140      @ISA = qw(Exporter DynaLoader);
141      @EXPORT = qw( rpcb_gettime );
142
143      bootstrap RPC;
144      1;
145
146 Throughout this document a variety of interfaces to the rpcb_gettime()
147 XSUB will be explored.  The XSUBs will take their parameters in different
148 orders or will take different numbers of parameters.  In each case the
149 XSUB is an abstraction between Perl and the real C rpcb_gettime()
150 function, and the XSUB must always ensure that the real rpcb_gettime()
151 function is called with the correct parameters.  This abstraction will
152 allow the programmer to create a more Perl-like interface to the C
153 function.
154
155 =head2 The Anatomy of an XSUB
156
157 The simplest XSUBs consist of 3 parts: a description of the return
158 value, the name of the XSUB routine and the names of its arguments,
159 and a description of types or formats of the arguments.
160
161 The following XSUB allows a Perl program to access a C library function
162 called sin().  The XSUB will imitate the C function which takes a single
163 argument and returns a single value.
164
165      double
166      sin(x)
167        double x
168
169 When using parameters with C pointer types, as in
170
171      double string_to_double(char *s);
172
173 there may be two ways to describe this argument to B<xsubpp>:
174
175      char *  s
176      char    &s
177
178 Both these XS declarations correspond to the C<char*> C type, but they have
179 different semantics.  It is convenient to think that the indirection operator
180 C<*> should be considered as a part of the type and the address operator C<&>
181 should be considered part of the variable.  See L<"The Typemap"> and
182 L<"The & Unary Operator"> for more info about handling qualifiers and unary
183 operators in C types.
184
185 The function name and the return type must be placed on
186 separate lines and should be flush left-adjusted.
187
188   INCORRECT                        CORRECT
189
190   double sin(x)                    double
191     double x                       sin(x)
192                                      double x
193
194 The function body may be indented or left-adjusted.  The following example
195 shows a function with its body left-adjusted.  Most examples in this
196 document will indent the body for better readability.
197
198   CORRECT
199
200   double
201   sin(x)
202   double x
203
204 More complicated XSUBs may contain many other sections.  Each section of
205 an XSUB starts with the corresponding keyword, such as INIT: or CLEANUP:.
206 However, the first two lines of an XSUB always contain the same data:
207 descriptions of the return type and the names of the function and its
208 parameters.  Whatever immediately follows these is considered to be
209 an INPUT: section unless explicitly marked with another keyword.
210 (See L<The INPUT: Keyword>.)
211
212 An XSUB section continues until another section-start keyword is found.
213
214 =head2 The Argument Stack
215
216 The Perl argument stack is used to store the values which are
217 sent as parameters to the XSUB and to store the XSUB's
218 return value(s).  In reality all Perl functions (including non-XSUB
219 ones) keep their values on this stack all the same time, each limited
220 to its own range of positions on the stack.  In this document the
221 first position on that stack which belongs to the active
222 function will be referred to as position 0 for that function.
223
224 XSUBs refer to their stack arguments with the macro B<ST(x)>, where I<x>
225 refers to a position in this XSUB's part of the stack.  Position 0 for that
226 function would be known to the XSUB as ST(0).  The XSUB's incoming
227 parameters and outgoing return values always begin at ST(0).  For many
228 simple cases the B<xsubpp> compiler will generate the code necessary to
229 handle the argument stack by embedding code fragments found in the
230 typemaps.  In more complex cases the programmer must supply the code.
231
232 =head2 The RETVAL Variable
233
234 The RETVAL variable is a special C variable that is declared automatically
235 for you.  The C type of RETVAL matches the return type of the C library
236 function.  The B<xsubpp> compiler will declare this variable in each XSUB
237 with non-C<void> return type.  By default the generated C function
238 will use RETVAL to hold the return value of the C library function being
239 called.  In simple cases the value of RETVAL will be placed in ST(0) of
240 the argument stack where it can be received by Perl as the return value
241 of the XSUB.
242
243 If the XSUB has a return type of C<void> then the compiler will
244 not declare a RETVAL variable for that function.  When using
245 a PPCODE: section no manipulation of the RETVAL variable is required, the
246 section may use direct stack manipulation to place output values on the stack.
247
248 If PPCODE: directive is not used, C<void> return value should be used
249 only for subroutines which do not return a value, I<even if> CODE:
250 directive is used which sets ST(0) explicitly.
251
252 Older versions of this document recommended to use C<void> return
253 value in such cases. It was discovered that this could lead to
254 segfaults in cases when XSUB was I<truly> C<void>. This practice is
255 now deprecated, and may be not supported at some future version. Use
256 the return value C<SV *> in such cases. (Currently C<xsubpp> contains
257 some heuristic code which tries to disambiguate between "truly-void"
258 and "old-practice-declared-as-void" functions. Hence your code is at
259 mercy of this heuristics unless you use C<SV *> as return value.)
260
261 =head2 The MODULE Keyword
262
263 The MODULE keyword is used to start the XS code and to
264 specify the package of the functions which are being
265 defined.  All text preceding the first MODULE keyword is
266 considered C code and is passed through to the output
267 untouched.  Every XS module will have a bootstrap function
268 which is used to hook the XSUBs into Perl.  The package name
269 of this bootstrap function will match the value of the last
270 MODULE statement in the XS source files.  The value of
271 MODULE should always remain constant within the same XS
272 file, though this is not required.
273
274 The following example will start the XS code and will place
275 all functions in a package named RPC.
276
277      MODULE = RPC
278
279 =head2 The PACKAGE Keyword
280
281 When functions within an XS source file must be separated into packages
282 the PACKAGE keyword should be used.  This keyword is used with the MODULE
283 keyword and must follow immediately after it when used.
284
285      MODULE = RPC  PACKAGE = RPC
286
287      [ XS code in package RPC ]
288
289      MODULE = RPC  PACKAGE = RPCB
290
291      [ XS code in package RPCB ]
292
293      MODULE = RPC  PACKAGE = RPC
294
295      [ XS code in package RPC ]
296
297 Although this keyword is optional and in some cases provides redundant
298 information it should always be used.  This keyword will ensure that the
299 XSUBs appear in the desired package.
300
301 =head2 The PREFIX Keyword
302
303 The PREFIX keyword designates prefixes which should be
304 removed from the Perl function names.  If the C function is
305 C<rpcb_gettime()> and the PREFIX value is C<rpcb_> then Perl will
306 see this function as C<gettime()>.
307
308 This keyword should follow the PACKAGE keyword when used.
309 If PACKAGE is not used then PREFIX should follow the MODULE
310 keyword.
311
312      MODULE = RPC  PREFIX = rpc_
313
314      MODULE = RPC  PACKAGE = RPCB  PREFIX = rpcb_
315
316 =head2 The OUTPUT: Keyword
317
318 The OUTPUT: keyword indicates that certain function parameters should be
319 updated (new values made visible to Perl) when the XSUB terminates or that
320 certain values should be returned to the calling Perl function.  For
321 simple functions which have no CODE: or PPCODE: section,
322 such as the sin() function above, the RETVAL variable is
323 automatically designated as an output value.  For more complex functions
324 the B<xsubpp> compiler will need help to determine which variables are output
325 variables.
326
327 This keyword will normally be used to complement the CODE:  keyword.
328 The RETVAL variable is not recognized as an output variable when the
329 CODE: keyword is present.  The OUTPUT:  keyword is used in this
330 situation to tell the compiler that RETVAL really is an output
331 variable.
332
333 The OUTPUT: keyword can also be used to indicate that function parameters
334 are output variables.  This may be necessary when a parameter has been
335 modified within the function and the programmer would like the update to
336 be seen by Perl.
337
338      bool_t
339      rpcb_gettime(host,timep)
340           char *host
341           time_t &timep
342         OUTPUT:
343           timep
344
345 The OUTPUT: keyword will also allow an output parameter to
346 be mapped to a matching piece of code rather than to a
347 typemap.
348
349      bool_t
350      rpcb_gettime(host,timep)
351           char *host
352           time_t &timep
353         OUTPUT:
354           timep sv_setnv(ST(1), (double)timep);
355
356 B<xsubpp> emits an automatic C<SvSETMAGIC()> for all parameters in the
357 OUTPUT section of the XSUB, except RETVAL.  This is the usually desired
358 behavior, as it takes care of properly invoking 'set' magic on output
359 parameters (needed for hash or array element parameters that must be
360 created if they didn't exist).  If for some reason, this behavior is
361 not desired, the OUTPUT section may contain a C<SETMAGIC: DISABLE> line
362 to disable it for the remainder of the parameters in the OUTPUT section.
363 Likewise,  C<SETMAGIC: ENABLE> can be used to reenable it for the
364 remainder of the OUTPUT section.  See L<perlguts> for more details
365 about 'set' magic.
366
367 =head2 The CODE: Keyword
368
369 This keyword is used in more complicated XSUBs which require
370 special handling for the C function.  The RETVAL variable is
371 still declared, but it will not be returned unless it is specified
372 in the OUTPUT: section.
373
374 The following XSUB is for a C function which requires special handling of
375 its parameters.  The Perl usage is given first.
376
377      $status = rpcb_gettime( "localhost", $timep );
378
379 The XSUB follows.
380
381      bool_t
382      rpcb_gettime(host,timep)
383           char *host
384           time_t timep
385         CODE:
386                RETVAL = rpcb_gettime( host, &timep );
387         OUTPUT:
388           timep
389           RETVAL
390
391 =head2 The INIT: Keyword
392
393 The INIT: keyword allows initialization to be inserted into the XSUB before
394 the compiler generates the call to the C function.  Unlike the CODE: keyword
395 above, this keyword does not affect the way the compiler handles RETVAL.
396
397     bool_t
398     rpcb_gettime(host,timep)
399           char *host
400           time_t &timep
401         INIT:
402           printf("# Host is %s\n", host );
403         OUTPUT:
404           timep
405
406 Another use for the INIT: section is to check for preconditions before
407 making a call to the C function:
408
409     long long
410     lldiv(a,b)
411         long long a
412         long long b
413       INIT:
414         if (a == 0 && b == 0)
415             XSRETURN_UNDEF;
416         if (b == 0)
417             croak("lldiv: cannot divide by 0");
418
419 =head2 The NO_INIT Keyword
420
421 The NO_INIT keyword is used to indicate that a function
422 parameter is being used only as an output value.  The B<xsubpp>
423 compiler will normally generate code to read the values of
424 all function parameters from the argument stack and assign
425 them to C variables upon entry to the function.  NO_INIT
426 will tell the compiler that some parameters will be used for
427 output rather than for input and that they will be handled
428 before the function terminates.
429
430 The following example shows a variation of the rpcb_gettime() function.
431 This function uses the timep variable only as an output variable and does
432 not care about its initial contents.
433
434      bool_t
435      rpcb_gettime(host,timep)
436           char *host
437           time_t &timep = NO_INIT
438         OUTPUT:
439           timep
440
441 =head2 Initializing Function Parameters
442
443 C function parameters are normally initialized with their values from
444 the argument stack (which in turn contains the parameters that were
445 passed to the XSUB from Perl).  The typemaps contain the
446 code segments which are used to translate the Perl values to
447 the C parameters.  The programmer, however, is allowed to
448 override the typemaps and supply alternate (or additional)
449 initialization code.  Initialization code starts with the first
450 C<=>, C<;> or C<+> on a line in the INPUT: section.  The only
451 exception happens if this C<;> terminates the line, then this C<;>
452 is quietly ignored.
453
454 The following code demonstrates how to supply initialization code for
455 function parameters.  The initialization code is eval'd within double
456 quotes by the compiler before it is added to the output so anything
457 which should be interpreted literally [mainly C<$>, C<@>, or C<\\>]
458 must be protected with backslashes.  The variables $var, $arg,
459 and $type can be used as in typemaps.
460
461      bool_t
462      rpcb_gettime(host,timep)
463           char *host = (char *)SvPV($arg,PL_na);
464           time_t &timep = 0;
465         OUTPUT:
466           timep
467
468 This should not be used to supply default values for parameters.  One
469 would normally use this when a function parameter must be processed by
470 another library function before it can be used.  Default parameters are
471 covered in the next section.
472
473 If the initialization begins with C<=>, then it is output in
474 the declaration for the input variable, replacing the initialization
475 supplied by the typemap.  If the initialization
476 begins with C<;> or C<+>, then it is performed after
477 all of the input variables have been declared.  In the C<;>
478 case the initialization normally supplied by the typemap is not performed.
479 For the C<+> case, the declaration for the variable will include the
480 initialization from the typemap.  A global
481 variable, C<%v>, is available for the truly rare case where
482 information from one initialization is needed in another
483 initialization.
484
485 Here's a truly obscure example:
486
487      bool_t
488      rpcb_gettime(host,timep)
489           time_t &timep ; /* \$v{timep}=@{[$v{timep}=$arg]} */
490           char *host + SvOK($v{timep}) ? SvPV($arg,PL_na) : NULL;
491         OUTPUT:
492           timep
493
494 The construct C<\$v{timep}=@{[$v{timep}=$arg]}> used in the above
495 example has a two-fold purpose: first, when this line is processed by
496 B<xsubpp>, the Perl snippet C<$v{timep}=$arg> is evaluated.  Second,
497 the text of the evaluated snippet is output into the generated C file
498 (inside a C comment)!  During the processing of C<char *host> line,
499 $arg will evaluate to C<ST(0)>, and C<$v{timep}> will evaluate to
500 C<ST(1)>.
501
502 =head2 Default Parameter Values
503
504 Default values for XSUB arguments can be specified by placing an
505 assignment statement in the parameter list.  The default value may
506 be a number, a string or the special string C<NO_INIT>.  Defaults should
507 always be used on the right-most parameters only.
508
509 To allow the XSUB for rpcb_gettime() to have a default host
510 value the parameters to the XSUB could be rearranged.  The
511 XSUB will then call the real rpcb_gettime() function with
512 the parameters in the correct order.  This XSUB can be called
513 from Perl with either of the following statements:
514
515      $status = rpcb_gettime( $timep, $host );
516
517      $status = rpcb_gettime( $timep );
518
519 The XSUB will look like the code  which  follows.   A  CODE:
520 block  is used to call the real rpcb_gettime() function with
521 the parameters in the correct order for that function.
522
523      bool_t
524      rpcb_gettime(timep,host="localhost")
525           char *host
526           time_t timep = NO_INIT
527         CODE:
528                RETVAL = rpcb_gettime( host, &timep );
529         OUTPUT:
530           timep
531           RETVAL
532
533 =head2 The PREINIT: Keyword
534
535 The PREINIT: keyword allows extra variables to be declared immediately
536 before or after the declarations of the parameters from the INPUT: section
537 are emitted.
538
539 If a variable is declared inside a CODE: section it will follow any typemap
540 code that is emitted for the input parameters.  This may result in the
541 declaration ending up after C code, which is C syntax error.  Similar
542 errors may happen with an explicit C<;>-type or C<+>-type initialization of
543 parameters is used (see L<"Initializing Function Parameters">).  Declaring
544 these variables in an INIT: section will not help.
545
546 In such cases, to force an additional variable to be declared together
547 with declarations of other variables, place the declaration into a
548 PREINIT: section.  The PREINIT: keyword may be used one or more times
549 within an XSUB.
550
551 The following examples are equivalent, but if the code is using complex
552 typemaps then the first example is safer.
553
554      bool_t
555      rpcb_gettime(timep)
556           time_t timep = NO_INIT
557         PREINIT:
558           char *host = "localhost";
559         CODE:
560           RETVAL = rpcb_gettime( host, &timep );
561         OUTPUT:
562           timep
563           RETVAL
564
565 For this particular case an INIT: keyword would generate the
566 same C code as the PREINIT: keyword.  Another correct, but error-prone example:
567
568      bool_t
569      rpcb_gettime(timep)
570           time_t timep = NO_INIT
571         CODE:
572           char *host = "localhost";
573           RETVAL = rpcb_gettime( host, &timep );
574         OUTPUT:
575           timep
576           RETVAL
577
578 Another way to declare C<host> is to use a C block in the CODE: section:
579
580      bool_t
581      rpcb_gettime(timep)
582           time_t timep = NO_INIT
583         CODE:
584           {
585             char *host = "localhost";
586             RETVAL = rpcb_gettime( host, &timep );
587           }
588         OUTPUT:
589           timep
590           RETVAL
591
592 The ability to put additional declarations before the typemap entries are
593 processed is very handy in the cases when typemap conversions manipulate
594 some global state:
595
596     MyObject
597     mutate(o)
598         PREINIT:
599             MyState st = global_state;
600         INPUT:
601             MyObject o;
602         CLEANUP:
603             reset_to(global_state, st);
604
605 Here we suppose that conversion to C<MyObject> in the INPUT: section and from
606 MyObject when processing RETVAL will modify a global variable C<global_state>.
607 After these conversions are performed, we restore the old value of
608 C<global_state> (to avoid memory leaks, for example).
609
610 There is another way to trade clarity for compactness: INPUT sections allow
611 declaration of C variables which do not appear in the parameter list of
612 a subroutine.  Thus the above code for mutate() can be rewritten as
613
614     MyObject
615     mutate(o)
616           MyState st = global_state;
617           MyObject o;
618         CLEANUP:
619           reset_to(global_state, st);
620
621 and the code for rpcb_gettime() can be rewritten as
622
623      bool_t
624      rpcb_gettime(timep)
625           time_t timep = NO_INIT
626           char *host = "localhost";
627         C_ARGS:
628           host, &timep
629         OUTPUT:
630           timep
631           RETVAL
632
633 =head2 The SCOPE: Keyword
634
635 The SCOPE: keyword allows scoping to be enabled for a particular XSUB. If
636 enabled, the XSUB will invoke ENTER and LEAVE automatically.
637
638 To support potentially complex type mappings, if a typemap entry used
639 by an XSUB contains a comment like C</*scope*/> then scoping will
640 be automatically enabled for that XSUB.
641
642 To enable scoping:
643
644     SCOPE: ENABLE
645
646 To disable scoping:
647
648     SCOPE: DISABLE
649
650 =head2 The INPUT: Keyword
651
652 The XSUB's parameters are usually evaluated immediately after entering the
653 XSUB.  The INPUT: keyword can be used to force those parameters to be
654 evaluated a little later.  The INPUT: keyword can be used multiple times
655 within an XSUB and can be used to list one or more input variables.  This
656 keyword is used with the PREINIT: keyword.
657
658 The following example shows how the input parameter C<timep> can be
659 evaluated late, after a PREINIT.
660
661     bool_t
662     rpcb_gettime(host,timep)
663           char *host
664         PREINIT:
665           time_t tt;
666         INPUT:
667           time_t timep
668         CODE:
669                RETVAL = rpcb_gettime( host, &tt );
670                timep = tt;
671         OUTPUT:
672           timep
673           RETVAL
674
675 The next example shows each input parameter evaluated late.
676
677     bool_t
678     rpcb_gettime(host,timep)
679         PREINIT:
680           time_t tt;
681         INPUT:
682           char *host
683         PREINIT:
684           char *h;
685         INPUT:
686           time_t timep
687         CODE:
688                h = host;
689                RETVAL = rpcb_gettime( h, &tt );
690                timep = tt;
691         OUTPUT:
692           timep
693           RETVAL
694
695 Since INPUT sections allow declaration of C variables which do not appear
696 in the parameter list of a subroutine, this may be shortened to:
697
698     bool_t
699     rpcb_gettime(host,timep)
700           time_t tt;
701           char *host;
702           char *h = host;
703           time_t timep;
704         CODE:
705           RETVAL = rpcb_gettime( h, &tt );
706           timep = tt;
707         OUTPUT:
708           timep
709           RETVAL
710
711 (We used our knowledge that input conversion for C<char *> is a "simple" one,
712 thus C<host> is initialized on the declaration line, and our assignment
713 C<h = host> is not performed too early.  Otherwise one would need to have the
714 assignment C<h = host> in a CODE: or INIT: section.)
715
716 =head2 Variable-length Parameter Lists
717
718 XSUBs can have variable-length parameter lists by specifying an ellipsis
719 C<(...)> in the parameter list.  This use of the ellipsis is similar to that
720 found in ANSI C.  The programmer is able to determine the number of
721 arguments passed to the XSUB by examining the C<items> variable which the
722 B<xsubpp> compiler supplies for all XSUBs.  By using this mechanism one can
723 create an XSUB which accepts a list of parameters of unknown length.
724
725 The I<host> parameter for the rpcb_gettime() XSUB can be
726 optional so the ellipsis can be used to indicate that the
727 XSUB will take a variable number of parameters.  Perl should
728 be able to call this XSUB with either of the following statements.
729
730      $status = rpcb_gettime( $timep, $host );
731
732      $status = rpcb_gettime( $timep );
733
734 The XS code, with ellipsis, follows.
735
736      bool_t
737      rpcb_gettime(timep, ...)
738           time_t timep = NO_INIT
739         PREINIT:
740           char *host = "localhost";
741           STRLEN n_a;
742         CODE:
743           if( items > 1 )
744                host = (char *)SvPV(ST(1), n_a);
745           RETVAL = rpcb_gettime( host, &timep );
746         OUTPUT:
747           timep
748           RETVAL
749
750 =head2 The C_ARGS: Keyword
751
752 The C_ARGS: keyword allows creating of XSUBS which have different
753 calling sequence from Perl than from C, without a need to write
754 CODE: or PPCODE: section.  The contents of the C_ARGS: paragraph is
755 put as the argument to the called C function without any change.
756
757 For example, suppose that a C function is declared as
758
759     symbolic nth_derivative(int n, symbolic function, int flags);
760
761 and that the default flags are kept in a global C variable
762 C<default_flags>.  Suppose that you want to create an interface which
763 is called as
764
765     $second_deriv = $function->nth_derivative(2);
766
767 To do this, declare the XSUB as
768
769     symbolic
770     nth_derivative(function, n)
771         symbolic        function
772         int             n
773       C_ARGS:
774         n, function, default_flags
775
776 =head2 The PPCODE: Keyword
777
778 The PPCODE: keyword is an alternate form of the CODE: keyword and is used
779 to tell the B<xsubpp> compiler that the programmer is supplying the code to
780 control the argument stack for the XSUBs return values.  Occasionally one
781 will want an XSUB to return a list of values rather than a single value.
782 In these cases one must use PPCODE: and then explicitly push the list of
783 values on the stack.  The PPCODE: and CODE:  keywords should not be used
784 together within the same XSUB.
785
786 The actual difference between PPCODE: and CODE: sections is in the
787 initialization of C<SP> macro (which stands for the I<current> Perl
788 stack pointer), and in the handling of data on the stack when returning
789 from an XSUB.  In CODE: sections SP preserves the value which was on
790 entry to the XSUB: SP is on the function pointer (which follows the
791 last parameter).  In PPCODE: sections SP is moved backward to the
792 beginning of the parameter list, which allows C<PUSH*()> macros
793 to place output values in the place Perl expects them to be when
794 the XSUB returns back to Perl.
795
796 The generated trailer for a CODE: section ensures that the number of return
797 values Perl will see is either 0 or 1 (depending on the C<void>ness of the
798 return value of the C function, and heuristics mentioned in
799 L<"The RETVAL Variable">).  The trailer generated for a PPCODE: section
800 is based on the number of return values and on the number of times
801 C<SP> was updated by C<[X]PUSH*()> macros.
802
803 Note that macros C<ST(i)>, C<XST_m*()> and C<XSRETURN*()> work equally
804 well in CODE: sections and PPCODE: sections.
805
806 The following XSUB will call the C rpcb_gettime() function
807 and will return its two output values, timep and status, to
808 Perl as a single list.
809
810      void
811      rpcb_gettime(host)
812           char *host
813         PREINIT:
814           time_t  timep;
815           bool_t  status;
816         PPCODE:
817           status = rpcb_gettime( host, &timep );
818           EXTEND(SP, 2);
819           PUSHs(sv_2mortal(newSViv(status)));
820           PUSHs(sv_2mortal(newSViv(timep)));
821
822 Notice that the programmer must supply the C code necessary
823 to have the real rpcb_gettime() function called and to have
824 the return values properly placed on the argument stack.
825
826 The C<void> return type for this function tells the B<xsubpp> compiler that
827 the RETVAL variable is not needed or used and that it should not be created.
828 In most scenarios the void return type should be used with the PPCODE:
829 directive.
830
831 The EXTEND() macro is used to make room on the argument
832 stack for 2 return values.  The PPCODE: directive causes the
833 B<xsubpp> compiler to create a stack pointer available as C<SP>, and it
834 is this pointer which is being used in the EXTEND() macro.
835 The values are then pushed onto the stack with the PUSHs()
836 macro.
837
838 Now the rpcb_gettime() function can be used from Perl with
839 the following statement.
840
841      ($status, $timep) = rpcb_gettime("localhost");
842
843 When handling output parameters with a PPCODE section, be sure to handle
844 'set' magic properly.  See L<perlguts> for details about 'set' magic.
845
846 =head2 Returning Undef And Empty Lists
847
848 Occasionally the programmer will want to return simply
849 C<undef> or an empty list if a function fails rather than a
850 separate status value.  The rpcb_gettime() function offers
851 just this situation.  If the function succeeds we would like
852 to have it return the time and if it fails we would like to
853 have undef returned.  In the following Perl code the value
854 of $timep will either be undef or it will be a valid time.
855
856      $timep = rpcb_gettime( "localhost" );
857
858 The following XSUB uses the C<SV *> return type as a mnemonic only,
859 and uses a CODE: block to indicate to the compiler
860 that the programmer has supplied all the necessary code.  The
861 sv_newmortal() call will initialize the return value to undef, making that
862 the default return value.
863
864      SV *
865      rpcb_gettime(host)
866           char *  host
867         PREINIT:
868           time_t  timep;
869           bool_t x;
870         CODE:
871           ST(0) = sv_newmortal();
872           if( rpcb_gettime( host, &timep ) )
873                sv_setnv( ST(0), (double)timep);
874
875 The next example demonstrates how one would place an explicit undef in the
876 return value, should the need arise.
877
878      SV *
879      rpcb_gettime(host)
880           char *  host
881         PREINIT:
882           time_t  timep;
883           bool_t x;
884         CODE:
885           ST(0) = sv_newmortal();
886           if( rpcb_gettime( host, &timep ) ){
887                sv_setnv( ST(0), (double)timep);
888           }
889           else{
890                ST(0) = &PL_sv_undef;
891           }
892
893 To return an empty list one must use a PPCODE: block and
894 then not push return values on the stack.
895
896      void
897      rpcb_gettime(host)
898           char *host
899         PREINIT:
900           time_t  timep;
901         PPCODE:
902           if( rpcb_gettime( host, &timep ) )
903                PUSHs(sv_2mortal(newSViv(timep)));
904           else{
905               /* Nothing pushed on stack, so an empty
906                * list is implicitly returned. */
907           }
908
909 Some people may be inclined to include an explicit C<return> in the above
910 XSUB, rather than letting control fall through to the end.  In those
911 situations C<XSRETURN_EMPTY> should be used, instead.  This will ensure that
912 the XSUB stack is properly adjusted.  Consult L<perlguts/"API LISTING"> for
913 other C<XSRETURN> macros.
914
915 Since C<XSRETURN_*> macros can be used with CODE blocks as well, one can
916 rewrite this example as:
917
918      int
919      rpcb_gettime(host)
920           char *host
921         PREINIT:
922           time_t  timep;
923         CODE:
924           RETVAL = rpcb_gettime( host, &timep );
925           if (RETVAL == 0)
926                 XSRETURN_UNDEF;
927         OUTPUT:
928           RETVAL
929
930 In fact, one can put this check into a CLEANUP: section as well.  Together
931 with PREINIT: simplifications, this leads to:
932
933      int
934      rpcb_gettime(host)
935           char *host
936           time_t  timep;
937         CLEANUP:
938           if (RETVAL == 0)
939                 XSRETURN_UNDEF;
940
941 =head2 The REQUIRE: Keyword
942
943 The REQUIRE: keyword is used to indicate the minimum version of the
944 B<xsubpp> compiler needed to compile the XS module.  An XS module which
945 contains the following statement will compile with only B<xsubpp> version
946 1.922 or greater:
947
948         REQUIRE: 1.922
949
950 =head2 The CLEANUP: Keyword
951
952 This keyword can be used when an XSUB requires special cleanup procedures
953 before it terminates.  When the CLEANUP:  keyword is used it must follow
954 any CODE:, PPCODE:, or OUTPUT: blocks which are present in the XSUB.  The
955 code specified for the cleanup block will be added as the last statements
956 in the XSUB.
957
958 =head2 The BOOT: Keyword
959
960 The BOOT: keyword is used to add code to the extension's bootstrap
961 function.  The bootstrap function is generated by the B<xsubpp> compiler and
962 normally holds the statements necessary to register any XSUBs with Perl.
963 With the BOOT: keyword the programmer can tell the compiler to add extra
964 statements to the bootstrap function.
965
966 This keyword may be used any time after the first MODULE keyword and should
967 appear on a line by itself.  The first blank line after the keyword will
968 terminate the code block.
969
970      BOOT:
971      # The following message will be printed when the
972      # bootstrap function executes.
973      printf("Hello from the bootstrap!\n");
974
975 =head2 The VERSIONCHECK: Keyword
976
977 The VERSIONCHECK: keyword corresponds to B<xsubpp>'s C<-versioncheck> and
978 C<-noversioncheck> options.  This keyword overrides the command line
979 options.  Version checking is enabled by default.  When version checking is
980 enabled the XS module will attempt to verify that its version matches the
981 version of the PM module.
982
983 To enable version checking:
984
985     VERSIONCHECK: ENABLE
986
987 To disable version checking:
988
989     VERSIONCHECK: DISABLE
990
991 =head2 The PROTOTYPES: Keyword
992
993 The PROTOTYPES: keyword corresponds to B<xsubpp>'s C<-prototypes> and
994 C<-noprototypes> options.  This keyword overrides the command line options.
995 Prototypes are enabled by default.  When prototypes are enabled XSUBs will
996 be given Perl prototypes.  This keyword may be used multiple times in an XS
997 module to enable and disable prototypes for different parts of the module.
998
999 To enable prototypes:
1000
1001     PROTOTYPES: ENABLE
1002
1003 To disable prototypes:
1004
1005     PROTOTYPES: DISABLE
1006
1007 =head2 The PROTOTYPE: Keyword
1008
1009 This keyword is similar to the PROTOTYPES: keyword above but can be used to
1010 force B<xsubpp> to use a specific prototype for the XSUB.  This keyword
1011 overrides all other prototype options and keywords but affects only the
1012 current XSUB.  Consult L<perlsub/Prototypes> for information about Perl
1013 prototypes.
1014
1015     bool_t
1016     rpcb_gettime(timep, ...)
1017           time_t timep = NO_INIT
1018         PROTOTYPE: $;$
1019         PREINIT:
1020           char *host = "localhost";
1021           STRLEN n_a;
1022         CODE:
1023                   if( items > 1 )
1024                        host = (char *)SvPV(ST(1), n_a);
1025                   RETVAL = rpcb_gettime( host, &timep );
1026         OUTPUT:
1027           timep
1028           RETVAL
1029
1030 =head2 The ALIAS: Keyword
1031
1032 The ALIAS: keyword allows an XSUB to have two or more unique Perl names
1033 and to know which of those names was used when it was invoked.  The Perl
1034 names may be fully-qualified with package names.  Each alias is given an
1035 index.  The compiler will setup a variable called C<ix> which contain the
1036 index of the alias which was used.  When the XSUB is called with its
1037 declared name C<ix> will be 0.
1038
1039 The following example will create aliases C<FOO::gettime()> and
1040 C<BAR::getit()> for this function.
1041
1042     bool_t
1043     rpcb_gettime(host,timep)
1044           char *host
1045           time_t &timep
1046         ALIAS:
1047             FOO::gettime = 1
1048             BAR::getit = 2
1049         INIT:
1050           printf("# ix = %d\n", ix );
1051         OUTPUT:
1052           timep
1053
1054 =head2 The INTERFACE: Keyword
1055
1056 This keyword declares the current XSUB as a keeper of the given
1057 calling signature.  If some text follows this keyword, it is
1058 considered as a list of functions which have this signature, and
1059 should be attached to the current XSUB.
1060
1061 For example, if you have 4 C functions multiply(), divide(), add(),
1062 subtract() all having the signature:
1063
1064     symbolic f(symbolic, symbolic);
1065
1066 you can make them all to use the same XSUB using this:
1067
1068     symbolic
1069     interface_s_ss(arg1, arg2)  
1070         symbolic        arg1
1071         symbolic        arg2
1072     INTERFACE:
1073         multiply divide 
1074         add subtract
1075
1076 (This is the complete XSUB code for 4 Perl functions!)  Four generated
1077 Perl function share names with corresponding C functions.
1078
1079 The advantage of this approach comparing to ALIAS: keyword is that there
1080 is no need to code a switch statement, each Perl function (which shares
1081 the same XSUB) knows which C function it should call.  Additionally, one
1082 can attach an extra function remainder() at runtime by using
1083
1084     CV *mycv = newXSproto("Symbolic::remainder", 
1085                           XS_Symbolic_interface_s_ss, __FILE__, "$$");
1086     XSINTERFACE_FUNC_SET(mycv, remainder);
1087
1088 say, from another XSUB.  (This example supposes that there was no
1089 INTERFACE_MACRO: section, otherwise one needs to use something else instead of
1090 C<XSINTERFACE_FUNC_SET>, see the next section.)
1091
1092 =head2 The INTERFACE_MACRO: Keyword
1093
1094 This keyword allows one to define an INTERFACE using a different way
1095 to extract a function pointer from an XSUB.  The text which follows
1096 this keyword should give the name of macros which would extract/set a
1097 function pointer.  The extractor macro is given return type, C<CV*>,
1098 and C<XSANY.any_dptr> for this C<CV*>.  The setter macro is given cv,
1099 and the function pointer.
1100
1101 The default value is C<XSINTERFACE_FUNC> and C<XSINTERFACE_FUNC_SET>.
1102 An INTERFACE keyword with an empty list of functions can be omitted if
1103 INTERFACE_MACRO keyword is used.
1104
1105 Suppose that in the previous example functions pointers for 
1106 multiply(), divide(), add(), subtract() are kept in a global C array
1107 C<fp[]> with offsets being C<multiply_off>, C<divide_off>, C<add_off>,
1108 C<subtract_off>.  Then one can use 
1109
1110     #define XSINTERFACE_FUNC_BYOFFSET(ret,cv,f) \
1111         ((XSINTERFACE_CVT(ret,))fp[CvXSUBANY(cv).any_i32])
1112     #define XSINTERFACE_FUNC_BYOFFSET_set(cv,f) \
1113         CvXSUBANY(cv).any_i32 = CAT2( f, _off )
1114
1115 in C section,
1116
1117     symbolic
1118     interface_s_ss(arg1, arg2)  
1119         symbolic        arg1
1120         symbolic        arg2
1121       INTERFACE_MACRO: 
1122         XSINTERFACE_FUNC_BYOFFSET
1123         XSINTERFACE_FUNC_BYOFFSET_set
1124       INTERFACE:
1125         multiply divide 
1126         add subtract
1127
1128 in XSUB section.
1129
1130 =head2 The INCLUDE: Keyword
1131
1132 This keyword can be used to pull other files into the XS module.  The other
1133 files may have XS code.  INCLUDE: can also be used to run a command to
1134 generate the XS code to be pulled into the module.
1135
1136 The file F<Rpcb1.xsh> contains our C<rpcb_gettime()> function:
1137
1138     bool_t
1139     rpcb_gettime(host,timep)
1140           char *host
1141           time_t &timep
1142         OUTPUT:
1143           timep
1144
1145 The XS module can use INCLUDE: to pull that file into it.
1146
1147     INCLUDE: Rpcb1.xsh
1148
1149 If the parameters to the INCLUDE: keyword are followed by a pipe (C<|>) then
1150 the compiler will interpret the parameters as a command.
1151
1152     INCLUDE: cat Rpcb1.xsh |
1153
1154 =head2 The CASE: Keyword
1155
1156 The CASE: keyword allows an XSUB to have multiple distinct parts with each
1157 part acting as a virtual XSUB.  CASE: is greedy and if it is used then all
1158 other XS keywords must be contained within a CASE:.  This means nothing may
1159 precede the first CASE: in the XSUB and anything following the last CASE: is
1160 included in that case.
1161
1162 A CASE: might switch via a parameter of the XSUB, via the C<ix> ALIAS:
1163 variable (see L<"The ALIAS: Keyword">), or maybe via the C<items> variable
1164 (see L<"Variable-length Parameter Lists">).  The last CASE: becomes the
1165 B<default> case if it is not associated with a conditional.  The following
1166 example shows CASE switched via C<ix> with a function C<rpcb_gettime()>
1167 having an alias C<x_gettime()>.  When the function is called as
1168 C<rpcb_gettime()> its parameters are the usual C<(char *host, time_t *timep)>,
1169 but when the function is called as C<x_gettime()> its parameters are
1170 reversed, C<(time_t *timep, char *host)>.
1171
1172     long
1173     rpcb_gettime(a,b)
1174       CASE: ix == 1
1175         ALIAS:
1176           x_gettime = 1
1177         INPUT:
1178           # 'a' is timep, 'b' is host
1179           char *b
1180           time_t a = NO_INIT
1181         CODE:
1182                RETVAL = rpcb_gettime( b, &a );
1183         OUTPUT:
1184           a
1185           RETVAL
1186       CASE:
1187           # 'a' is host, 'b' is timep
1188           char *a
1189           time_t &b = NO_INIT
1190         OUTPUT:
1191           b
1192           RETVAL
1193
1194 That function can be called with either of the following statements.  Note
1195 the different argument lists.
1196
1197         $status = rpcb_gettime( $host, $timep );
1198
1199         $status = x_gettime( $timep, $host );
1200
1201 =head2 The & Unary Operator
1202
1203 The C<&> unary operator in the INPUT: section is used to tell B<xsubpp>
1204 that it should convert a Perl value to/from C using the C type to the left
1205 of C<&>, but provide a pointer to this value when the C function is called.
1206
1207 This is useful to avoid a CODE: block for a C function which takes a parameter
1208 by reference.  Typically, the parameter should be not a pointer type (an
1209 C<int> or C<long> but not a C<int*> or C<long*>).
1210
1211 The following XSUB will generate incorrect C code.  The B<xsubpp> compiler will
1212 turn this into code which calls C<rpcb_gettime()> with parameters C<(char
1213 *host, time_t timep)>, but the real C<rpcb_gettime()> wants the C<timep>
1214 parameter to be of type C<time_t*> rather than C<time_t>.
1215
1216     bool_t
1217     rpcb_gettime(host,timep)
1218           char *host
1219           time_t timep
1220         OUTPUT:
1221           timep
1222
1223 That problem is corrected by using the C<&> operator.  The B<xsubpp> compiler
1224 will now turn this into code which calls C<rpcb_gettime()> correctly with
1225 parameters C<(char *host, time_t *timep)>.  It does this by carrying the
1226 C<&> through, so the function call looks like C<rpcb_gettime(host, &timep)>.
1227
1228     bool_t
1229     rpcb_gettime(host,timep)
1230           char *host
1231           time_t &timep
1232         OUTPUT:
1233           timep
1234
1235 =head2 Inserting Comments and C Preprocessor Directives
1236
1237 C preprocessor directives are allowed within BOOT:, PREINIT: INIT:,
1238 CODE:, PPCODE:, and CLEANUP: blocks, as well as outside the functions.
1239 Comments are allowed anywhere after the MODULE keyword.  The compiler
1240 will pass the preprocessor directives through untouched and will remove
1241 the commented lines.
1242
1243 Comments can be added to XSUBs by placing a C<#> as the first
1244 non-whitespace of a line.  Care should be taken to avoid making the
1245 comment look like a C preprocessor directive, lest it be interpreted as
1246 such.  The simplest way to prevent this is to put whitespace in front of
1247 the C<#>.
1248
1249 If you use preprocessor directives to choose one of two
1250 versions of a function, use
1251
1252     #if ... version1
1253     #else /* ... version2  */
1254     #endif
1255
1256 and not
1257
1258     #if ... version1
1259     #endif
1260     #if ... version2
1261     #endif
1262
1263 because otherwise B<xsubpp> will believe that you made a duplicate
1264 definition of the function.  Also, put a blank line before the
1265 #else/#endif so it will not be seen as part of the function body.
1266
1267 =head2 Using XS With C++
1268
1269 If an XSUB name contains C<::>, it is considered to be a C++ method.
1270 The generated Perl function will assume that
1271 its first argument is an object pointer.  The object pointer
1272 will be stored in a variable called THIS.  The object should
1273 have been created by C++ with the new() function and should
1274 be blessed by Perl with the sv_setref_pv() macro.  The
1275 blessing of the object by Perl can be handled by a typemap.  An example
1276 typemap is shown at the end of this section.
1277
1278 If the return type of the XSUB includes C<static>, the method is considered
1279 to be a static method.  It will call the C++
1280 function using the class::method() syntax.  If the method is not static
1281 the function will be called using the THIS-E<gt>method() syntax.
1282
1283 The next examples will use the following C++ class.
1284
1285      class color {
1286           public:
1287           color();
1288           ~color();
1289           int blue();
1290           void set_blue( int );
1291
1292           private:
1293           int c_blue;
1294      };
1295
1296 The XSUBs for the blue() and set_blue() methods are defined with the class
1297 name but the parameter for the object (THIS, or "self") is implicit and is
1298 not listed.
1299
1300      int
1301      color::blue()
1302
1303      void
1304      color::set_blue( val )
1305           int val
1306
1307 Both Perl functions will expect an object as the first parameter.  In the 
1308 generated C++ code the object is called C<THIS>, and the method call will
1309 be performed on this object.  So in the C++ code the blue() and set_blue()
1310 methods will be called as this:
1311
1312      RETVAL = THIS->blue();
1313
1314      THIS->set_blue( val );
1315
1316 You could also write a single get/set method using an optional argument:
1317
1318      int
1319      color::blue( val = NO_INIT )
1320          int val
1321          PROTOTYPE $;$
1322          CODE:
1323              if (items > 1)
1324                  THIS->set_blue( val );
1325              RETVAL = THIS->blue();
1326          OUTPUT:
1327              RETVAL
1328
1329 If the function's name is B<DESTROY> then the C++ C<delete> function will be
1330 called and C<THIS> will be given as its parameter.  The generated C++ code for
1331
1332      void
1333      color::DESTROY()
1334
1335 will look like this:
1336
1337      color *THIS = ...; // Initialized as in typemap
1338
1339      delete THIS;
1340
1341 If the function's name is B<new> then the C++ C<new> function will be called
1342 to create a dynamic C++ object.  The XSUB will expect the class name, which
1343 will be kept in a variable called C<CLASS>, to be given as the first
1344 argument.
1345
1346      color *
1347      color::new()
1348
1349 The generated C++ code will call C<new>.
1350
1351      RETVAL = new color();
1352
1353 The following is an example of a typemap that could be used for this C++
1354 example.
1355
1356     TYPEMAP
1357     color *             O_OBJECT
1358
1359     OUTPUT
1360     # The Perl object is blessed into 'CLASS', which should be a
1361     # char* having the name of the package for the blessing.
1362     O_OBJECT
1363         sv_setref_pv( $arg, CLASS, (void*)$var );
1364
1365     INPUT
1366     O_OBJECT
1367         if( sv_isobject($arg) && (SvTYPE(SvRV($arg)) == SVt_PVMG) )
1368                 $var = ($type)SvIV((SV*)SvRV( $arg ));
1369         else{
1370                 warn( \"${Package}::$func_name() -- $var is not a blessed SV reference\" );
1371                 XSRETURN_UNDEF;
1372         }
1373
1374 =head2 Interface Strategy
1375
1376 When designing an interface between Perl and a C library a straight
1377 translation from C to XS (such as created by C<h2xs -x>) is often sufficient.
1378 However, sometimes the interface will look
1379 very C-like and occasionally nonintuitive, especially when the C function
1380 modifies one of its parameters, or returns failure inband (as in "negative
1381 return values mean failure").  In cases where the programmer wishes to
1382 create a more Perl-like interface the following strategy may help to
1383 identify the more critical parts of the interface.
1384
1385 Identify the C functions with input/output or output parameters.  The XSUBs for
1386 these functions may be able to return lists to Perl.
1387
1388 Identify the C functions which use some inband info as an indication
1389 of failure.  They may be
1390 candidates to return undef or an empty list in case of failure.  If the
1391 failure may be detected without a call to the C function, you may want to use
1392 an INIT: section to report the failure.  For failures detectable after the C
1393 function returns one may want to use a CLEANUP: section to process the
1394 failure.  In more complicated cases use CODE: or PPCODE: sections.
1395
1396 If many functions use the same failure indication based on the return value,
1397 you may want to create a special typedef to handle this situation.  Put
1398
1399   typedef int negative_is_failure;
1400
1401 near the beginning of XS file, and create an OUTPUT typemap entry
1402 for C<negative_is_failure> which converts negative values to C<undef>, or
1403 maybe croak()s.  After this the return value of type C<negative_is_failure>
1404 will create more Perl-like interface.
1405
1406 Identify which values are used by only the C and XSUB functions
1407 themselves, say, when a parameter to a function should be a contents of a
1408 global variable.  If Perl does not need to access the contents of the value
1409 then it may not be necessary to provide a translation for that value
1410 from C to Perl.
1411
1412 Identify the pointers in the C function parameter lists and return
1413 values.  Some pointers may be used to implement input/output or
1414 output parameters, they can be handled in XS with the C<&> unary operator,
1415 and, possibly, using the NO_INIT keyword.
1416 Some others will require handling of types like C<int *>, and one needs
1417 to decide what a useful Perl translation will do in such a case.  When
1418 the semantic is clear, it is advisable to put the translation into a typemap
1419 file.
1420
1421 Identify the structures used by the C functions.  In many
1422 cases it may be helpful to use the T_PTROBJ typemap for
1423 these structures so they can be manipulated by Perl as
1424 blessed objects.  (This is handled automatically by C<h2xs -x>.)
1425
1426 If the same C type is used in several different contexts which require
1427 different translations, C<typedef> several new types mapped to this C type,
1428 and create separate F<typemap> entries for these new types.  Use these
1429 types in declarations of return type and parameters to XSUBs.
1430
1431 =head2 Perl Objects And C Structures
1432
1433 When dealing with C structures one should select either
1434 B<T_PTROBJ> or B<T_PTRREF> for the XS type.  Both types are
1435 designed to handle pointers to complex objects.  The
1436 T_PTRREF type will allow the Perl object to be unblessed
1437 while the T_PTROBJ type requires that the object be blessed.
1438 By using T_PTROBJ one can achieve a form of type-checking
1439 because the XSUB will attempt to verify that the Perl object
1440 is of the expected type.
1441
1442 The following XS code shows the getnetconfigent() function which is used
1443 with ONC+ TIRPC.  The getnetconfigent() function will return a pointer to a
1444 C structure and has the C prototype shown below.  The example will
1445 demonstrate how the C pointer will become a Perl reference.  Perl will
1446 consider this reference to be a pointer to a blessed object and will
1447 attempt to call a destructor for the object.  A destructor will be
1448 provided in the XS source to free the memory used by getnetconfigent().
1449 Destructors in XS can be created by specifying an XSUB function whose name
1450 ends with the word B<DESTROY>.  XS destructors can be used to free memory
1451 which may have been malloc'd by another XSUB.
1452
1453      struct netconfig *getnetconfigent(const char *netid);
1454
1455 A C<typedef> will be created for C<struct netconfig>.  The Perl
1456 object will be blessed in a class matching the name of the C
1457 type, with the tag C<Ptr> appended, and the name should not
1458 have embedded spaces if it will be a Perl package name.  The
1459 destructor will be placed in a class corresponding to the
1460 class of the object and the PREFIX keyword will be used to
1461 trim the name to the word DESTROY as Perl will expect.
1462
1463      typedef struct netconfig Netconfig;
1464
1465      MODULE = RPC  PACKAGE = RPC
1466
1467      Netconfig *
1468      getnetconfigent(netid)
1469           char *netid
1470
1471      MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_
1472
1473      void
1474      rpcb_DESTROY(netconf)
1475           Netconfig *netconf
1476         CODE:
1477           printf("Now in NetconfigPtr::DESTROY\n");
1478           free( netconf );
1479
1480 This example requires the following typemap entry.  Consult the typemap
1481 section for more information about adding new typemaps for an extension.
1482
1483      TYPEMAP
1484      Netconfig *  T_PTROBJ
1485
1486 This example will be used with the following Perl statements.
1487
1488      use RPC;
1489      $netconf = getnetconfigent("udp");
1490
1491 When Perl destroys the object referenced by $netconf it will send the
1492 object to the supplied XSUB DESTROY function.  Perl cannot determine, and
1493 does not care, that this object is a C struct and not a Perl object.  In
1494 this sense, there is no difference between the object created by the
1495 getnetconfigent() XSUB and an object created by a normal Perl subroutine.
1496
1497 =head2 The Typemap
1498
1499 The typemap is a collection of code fragments which are used by the B<xsubpp>
1500 compiler to map C function parameters and values to Perl values.  The
1501 typemap file may consist of three sections labeled C<TYPEMAP>, C<INPUT>, and
1502 C<OUTPUT>.  An unlabelled initial section is assumed to be a C<TYPEMAP>
1503 section.  The INPUT section tells
1504 the compiler how to translate Perl values
1505 into variables of certain C types.  The OUTPUT section tells the compiler
1506 how to translate the values from certain C types into values Perl can
1507 understand.  The TYPEMAP section tells the compiler which of the INPUT and
1508 OUTPUT code fragments should be used to map a given C type to a Perl value.
1509 The section labels C<TYPEMAP>, C<INPUT>, or C<OUTPUT> must begin
1510 in the first column on a line by themselves, and must be in uppercase.
1511
1512 The default typemap in the C<ext> directory of the Perl source contains many
1513 useful types which can be used by Perl extensions.  Some extensions define
1514 additional typemaps which they keep in their own directory.  These
1515 additional typemaps may reference INPUT and OUTPUT maps in the main
1516 typemap.  The B<xsubpp> compiler will allow the extension's own typemap to
1517 override any mappings which are in the default typemap.
1518
1519 Most extensions which require a custom typemap will need only the TYPEMAP
1520 section of the typemap file.  The custom typemap used in the
1521 getnetconfigent() example shown earlier demonstrates what may be the typical
1522 use of extension typemaps.  That typemap is used to equate a C structure
1523 with the T_PTROBJ typemap.  The typemap used by getnetconfigent() is shown
1524 here.  Note that the C type is separated from the XS type with a tab and
1525 that the C unary operator C<*> is considered to be a part of the C type name.
1526
1527         TYPEMAP
1528         Netconfig *<tab>T_PTROBJ
1529
1530 Here's a more complicated example: suppose that you wanted C<struct
1531 netconfig> to be blessed into the class C<Net::Config>.  One way to do
1532 this is to use underscores (_) to separate package names, as follows:
1533
1534         typedef struct netconfig * Net_Config;
1535
1536 And then provide a typemap entry C<T_PTROBJ_SPECIAL> that maps underscores to
1537 double-colons (::), and declare C<Net_Config> to be of that type:
1538
1539
1540         TYPEMAP
1541         Net_Config      T_PTROBJ_SPECIAL
1542
1543         INPUT
1544         T_PTROBJ_SPECIAL
1545                 if (sv_derived_from($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")) {
1546                         IV tmp = SvIV((SV*)SvRV($arg));
1547                 $var = ($type) tmp;
1548                 }
1549                 else
1550                         croak(\"$var is not of type ${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")
1551
1552         OUTPUT
1553         T_PTROBJ_SPECIAL
1554                 sv_setref_pv($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\",
1555                 (void*)$var);
1556
1557 The INPUT and OUTPUT sections substitute underscores for double-colons
1558 on the fly, giving the desired effect.  This example demonstrates some
1559 of the power and versatility of the typemap facility.
1560
1561 =head1 EXAMPLES
1562
1563 File C<RPC.xs>: Interface to some ONC+ RPC bind library functions.
1564
1565      #include "EXTERN.h"
1566      #include "perl.h"
1567      #include "XSUB.h"
1568
1569      #include <rpc/rpc.h>
1570
1571      typedef struct netconfig Netconfig;
1572
1573      MODULE = RPC  PACKAGE = RPC
1574
1575      SV *
1576      rpcb_gettime(host="localhost")
1577           char *host
1578         PREINIT:
1579           time_t  timep;
1580         CODE:
1581           ST(0) = sv_newmortal();
1582           if( rpcb_gettime( host, &timep ) )
1583                sv_setnv( ST(0), (double)timep );
1584
1585      Netconfig *
1586      getnetconfigent(netid="udp")
1587           char *netid
1588
1589      MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_
1590
1591      void
1592      rpcb_DESTROY(netconf)
1593           Netconfig *netconf
1594         CODE:
1595           printf("NetconfigPtr::DESTROY\n");
1596           free( netconf );
1597
1598 File C<typemap>: Custom typemap for RPC.xs.
1599
1600      TYPEMAP
1601      Netconfig *  T_PTROBJ
1602
1603 File C<RPC.pm>: Perl module for the RPC extension.
1604
1605      package RPC;
1606
1607      require Exporter;
1608      require DynaLoader;
1609      @ISA = qw(Exporter DynaLoader);
1610      @EXPORT = qw(rpcb_gettime getnetconfigent);
1611
1612      bootstrap RPC;
1613      1;
1614
1615 File C<rpctest.pl>: Perl test program for the RPC extension.
1616
1617      use RPC;
1618
1619      $netconf = getnetconfigent();
1620      $a = rpcb_gettime();
1621      print "time = $a\n";
1622      print "netconf = $netconf\n";
1623
1624      $netconf = getnetconfigent("tcp");
1625      $a = rpcb_gettime("poplar");
1626      print "time = $a\n";
1627      print "netconf = $netconf\n";
1628
1629
1630 =head1 XS VERSION
1631
1632 This document covers features supported by C<xsubpp> 1.935.
1633
1634 =head1 AUTHOR
1635
1636 Originally written by Dean Roehrich <F<roehrich@cray.com>>.
1637
1638 Maintained since 1996 by The Perl Porters <F<perlbug@perl.org>>.