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