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