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