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