patch for LWP 5.05 to make it play with both 5.003 and 5.003_20 + overload patch
[p5sagit/p5-mst-13.2.git] / pod / perlxs.pod
CommitLineData
a0d0e21e 1=head1 NAME
2
8e07c86e 3perlxs - XS language reference manual
a0d0e21e 4
5=head1 DESCRIPTION
6
7=head2 Introduction
8
9XS is a language used to create an extension interface
10between Perl and some C library which one wishes to use with
11Perl. The XS interface is combined with the library to
12create a new library which can be linked to Perl. An B<XSUB>
13is a function in the XS language and is the core component
14of the Perl application interface.
15
16The XS compiler is called B<xsubpp>. This compiler will embed
17the constructs necessary to let an XSUB, which is really a C
18function in disguise, manipulate Perl values and creates the
19glue necessary to let Perl access the XSUB. The compiler
20uses B<typemaps> to determine how to map C function parameters
21and variables to Perl values. The default typemap handles
22many common C types. A supplement typemap must be created
23to handle special structures and types for the library being
24linked.
25
cb1a09d0 26See L<perlxstut> for a tutorial on the whole extension creation process.
8e07c86e 27
28=head2 On The Road
29
a5f75d66 30Many of the examples which follow will concentrate on creating an interface
31between Perl and the ONC+ RPC bind library functions. The rpcb_gettime()
32function is used to demonstrate many features of the XS language. This
33function has two parameters; the first is an input parameter and the second
34is an output parameter. The function also returns a status value.
a0d0e21e 35
36 bool_t rpcb_gettime(const char *host, time_t *timep);
37
38From C this function will be called with the following
39statements.
40
41 #include <rpc/rpc.h>
42 bool_t status;
43 time_t timep;
44 status = rpcb_gettime( "localhost", &timep );
45
46If an XSUB is created to offer a direct translation between this function
47and Perl, then this XSUB will be used from Perl with the following code.
48The $status and $timep variables will contain the output of the function.
49
50 use RPC;
51 $status = rpcb_gettime( "localhost", $timep );
52
53The following XS file shows an XS subroutine, or XSUB, which
54demonstrates one possible interface to the rpcb_gettime()
55function. This XSUB represents a direct translation between
56C and Perl and so preserves the interface even from Perl.
57This XSUB will be invoked from Perl with the usage shown
58above. Note that the first three #include statements, for
59C<EXTERN.h>, C<perl.h>, and C<XSUB.h>, will always be present at the
60beginning of an XS file. This approach and others will be
61expanded later in this document.
62
63 #include "EXTERN.h"
64 #include "perl.h"
65 #include "XSUB.h"
66 #include <rpc/rpc.h>
67
68 MODULE = RPC PACKAGE = RPC
69
70 bool_t
71 rpcb_gettime(host,timep)
8e07c86e 72 char *host
73 time_t &timep
a0d0e21e 74 OUTPUT:
75 timep
76
77Any extension to Perl, including those containing XSUBs,
78should have a Perl module to serve as the bootstrap which
79pulls the extension into Perl. This module will export the
80extension's functions and variables to the Perl program and
81will cause the extension's XSUBs to be linked into Perl.
82The following module will be used for most of the examples
83in this document and should be used from Perl with the C<use>
84command as shown earlier. Perl modules are explained in
85more detail later in this document.
86
87 package RPC;
88
89 require Exporter;
90 require DynaLoader;
91 @ISA = qw(Exporter DynaLoader);
92 @EXPORT = qw( rpcb_gettime );
93
94 bootstrap RPC;
95 1;
96
97Throughout this document a variety of interfaces to the rpcb_gettime()
98XSUB will be explored. The XSUBs will take their parameters in different
99orders or will take different numbers of parameters. In each case the
100XSUB is an abstraction between Perl and the real C rpcb_gettime()
101function, and the XSUB must always ensure that the real rpcb_gettime()
102function is called with the correct parameters. This abstraction will
103allow the programmer to create a more Perl-like interface to the C
104function.
105
106=head2 The Anatomy of an XSUB
107
8e07c86e 108The following XSUB allows a Perl program to access a C library function
109called sin(). The XSUB will imitate the C function which takes a single
110argument and returns a single value.
a0d0e21e 111
112 double
113 sin(x)
8e07c86e 114 double x
a0d0e21e 115
8e07c86e 116When using C pointers the indirection operator C<*> should be considered
117part of the type and the address operator C<&> should be considered part of
118the variable, as is demonstrated in the rpcb_gettime() function above. See
119the section on typemaps for more about handling qualifiers and unary
120operators in C types.
a0d0e21e 121
a0d0e21e 122The function name and the return type must be placed on
123separate lines.
124
125 INCORRECT CORRECT
126
127 double sin(x) double
8e07c86e 128 double x sin(x)
129 double x
a0d0e21e 130
c07a80fd 131The function body may be indented or left-adjusted. The following example
132shows a function with its body left-adjusted. Most examples in this
133document will indent the body.
134
135 CORRECT
136
137 double
138 sin(x)
139 double x
140
a0d0e21e 141=head2 The Argument Stack
142
143The argument stack is used to store the values which are
144sent as parameters to the XSUB and to store the XSUB's
145return value. In reality all Perl functions keep their
146values on this stack at the same time, each limited to its
147own range of positions on the stack. In this document the
148first position on that stack which belongs to the active
149function will be referred to as position 0 for that function.
150
8e07c86e 151XSUBs refer to their stack arguments with the macro B<ST(x)>, where I<x>
152refers to a position in this XSUB's part of the stack. Position 0 for that
a0d0e21e 153function would be known to the XSUB as ST(0). The XSUB's incoming
154parameters and outgoing return values always begin at ST(0). For many
155simple cases the B<xsubpp> compiler will generate the code necessary to
156handle the argument stack by embedding code fragments found in the
157typemaps. In more complex cases the programmer must supply the code.
158
159=head2 The RETVAL Variable
160
161The RETVAL variable is a magic variable which always matches
162the return type of the C library function. The B<xsubpp> compiler will
163supply this variable in each XSUB and by default will use it to hold the
164return value of the C library function being called. In simple cases the
165value of RETVAL will be placed in ST(0) of the argument stack where it can
166be received by Perl as the return value of the XSUB.
167
168If the XSUB has a return type of C<void> then the compiler will
169not supply a RETVAL variable for that function. When using
e7ea3e70 170the PPCODE: directive the RETVAL variable is not needed, unless used
171explicitly.
172
173If PPCODE: directive is not used, C<void> return value should be used
174only for subroutines which do not return a value, I<even if> CODE:
175directive is used which sets ST(0) explicitly.
176
177Older versions of this document recommended to use C<void> return
178value in such cases. It was discovered that this could lead to
179segfaults in cases when XSUB was I<truely> C<void>. This practice is
180now deprecated, and may be not supported at some future version. Use
181the return value C<SV *> in such cases. (Currently C<xsubpp> contains
182some heuristic code which tries to disambiguate between "truely-void"
183and "old-practice-declared-as-void" functions. Hence your code is at
184mercy of this heuristics unless you use C<SV *> as return value.)
a0d0e21e 185
186=head2 The MODULE Keyword
187
188The MODULE keyword is used to start the XS code and to
189specify the package of the functions which are being
190defined. All text preceding the first MODULE keyword is
191considered C code and is passed through to the output
192untouched. Every XS module will have a bootstrap function
193which is used to hook the XSUBs into Perl. The package name
194of this bootstrap function will match the value of the last
195MODULE statement in the XS source files. The value of
196MODULE should always remain constant within the same XS
197file, though this is not required.
198
199The following example will start the XS code and will place
200all functions in a package named RPC.
201
202 MODULE = RPC
203
204=head2 The PACKAGE Keyword
205
206When functions within an XS source file must be separated into packages
207the PACKAGE keyword should be used. This keyword is used with the MODULE
208keyword and must follow immediately after it when used.
209
210 MODULE = RPC PACKAGE = RPC
211
212 [ XS code in package RPC ]
213
214 MODULE = RPC PACKAGE = RPCB
215
216 [ XS code in package RPCB ]
217
218 MODULE = RPC PACKAGE = RPC
219
220 [ XS code in package RPC ]
221
222Although this keyword is optional and in some cases provides redundant
223information it should always be used. This keyword will ensure that the
224XSUBs appear in the desired package.
225
226=head2 The PREFIX Keyword
227
228The PREFIX keyword designates prefixes which should be
229removed from the Perl function names. If the C function is
230C<rpcb_gettime()> and the PREFIX value is C<rpcb_> then Perl will
231see this function as C<gettime()>.
232
233This keyword should follow the PACKAGE keyword when used.
234If PACKAGE is not used then PREFIX should follow the MODULE
235keyword.
236
237 MODULE = RPC PREFIX = rpc_
238
239 MODULE = RPC PACKAGE = RPCB PREFIX = rpcb_
240
241=head2 The OUTPUT: Keyword
242
243The OUTPUT: keyword indicates that certain function parameters should be
244updated (new values made visible to Perl) when the XSUB terminates or that
245certain values should be returned to the calling Perl function. For
246simple functions, such as the sin() function above, the RETVAL variable is
247automatically designated as an output value. In more complex functions
248the B<xsubpp> compiler will need help to determine which variables are output
249variables.
250
251This keyword will normally be used to complement the CODE: keyword.
252The RETVAL variable is not recognized as an output variable when the
253CODE: keyword is present. The OUTPUT: keyword is used in this
254situation to tell the compiler that RETVAL really is an output
255variable.
256
257The OUTPUT: keyword can also be used to indicate that function parameters
258are output variables. This may be necessary when a parameter has been
259modified within the function and the programmer would like the update to
8e07c86e 260be seen by Perl.
a0d0e21e 261
262 bool_t
263 rpcb_gettime(host,timep)
8e07c86e 264 char *host
265 time_t &timep
a0d0e21e 266 OUTPUT:
267 timep
268
269The OUTPUT: keyword will also allow an output parameter to
270be mapped to a matching piece of code rather than to a
271typemap.
272
273 bool_t
274 rpcb_gettime(host,timep)
8e07c86e 275 char *host
276 time_t &timep
a0d0e21e 277 OUTPUT:
8e07c86e 278 timep sv_setnv(ST(1), (double)timep);
a0d0e21e 279
280=head2 The CODE: Keyword
281
282This keyword is used in more complicated XSUBs which require
283special handling for the C function. The RETVAL variable is
284available but will not be returned unless it is specified
285under the OUTPUT: keyword.
286
287The following XSUB is for a C function which requires special handling of
288its parameters. The Perl usage is given first.
289
290 $status = rpcb_gettime( "localhost", $timep );
291
292The XSUB follows.
293
d1b91892 294 bool_t
295 rpcb_gettime(host,timep)
8e07c86e 296 char *host
297 time_t timep
a0d0e21e 298 CODE:
299 RETVAL = rpcb_gettime( host, &timep );
300 OUTPUT:
301 timep
302 RETVAL
303
c07a80fd 304=head2 The INIT: Keyword
305
306The INIT: keyword allows initialization to be inserted into the XSUB before
307the compiler generates the call to the C function. Unlike the CODE: keyword
308above, this keyword does not affect the way the compiler handles RETVAL.
309
310 bool_t
311 rpcb_gettime(host,timep)
312 char *host
313 time_t &timep
314 INIT:
315 printf("# Host is %s\n", host );
316 OUTPUT:
317 timep
a0d0e21e 318
319=head2 The NO_INIT Keyword
320
321The NO_INIT keyword is used to indicate that a function
d1b91892 322parameter is being used as only an output value. The B<xsubpp>
a0d0e21e 323compiler will normally generate code to read the values of
324all function parameters from the argument stack and assign
325them to C variables upon entry to the function. NO_INIT
326will tell the compiler that some parameters will be used for
327output rather than for input and that they will be handled
328before the function terminates.
329
330The following example shows a variation of the rpcb_gettime() function.
d1b91892 331This function uses the timep variable as only an output variable and does
a0d0e21e 332not care about its initial contents.
333
334 bool_t
335 rpcb_gettime(host,timep)
8e07c86e 336 char *host
337 time_t &timep = NO_INIT
a0d0e21e 338 OUTPUT:
339 timep
340
341=head2 Initializing Function Parameters
342
343Function parameters are normally initialized with their
344values from the argument stack. The typemaps contain the
345code segments which are used to transfer the Perl values to
346the C parameters. The programmer, however, is allowed to
347override the typemaps and supply alternate initialization
348code.
349
350The following code demonstrates how to supply initialization code for
351function parameters. The initialization code is eval'd by the compiler
352before it is added to the output so anything which should be interpreted
353literally, such as double quotes, must be protected with backslashes.
354
355 bool_t
356 rpcb_gettime(host,timep)
8e07c86e 357 char *host = (char *)SvPV(ST(0),na);
358 time_t &timep = 0;
a0d0e21e 359 OUTPUT:
360 timep
361
362This should not be used to supply default values for parameters. One
363would normally use this when a function parameter must be processed by
364another library function before it can be used. Default parameters are
365covered in the next section.
366
367=head2 Default Parameter Values
368
369Default values can be specified for function parameters by
370placing an assignment statement in the parameter list. The
371default value may be a number or a string. Defaults should
372always be used on the right-most parameters only.
373
374To allow the XSUB for rpcb_gettime() to have a default host
375value the parameters to the XSUB could be rearranged. The
376XSUB will then call the real rpcb_gettime() function with
377the parameters in the correct order. Perl will call this
378XSUB with either of the following statements.
379
380 $status = rpcb_gettime( $timep, $host );
381
382 $status = rpcb_gettime( $timep );
383
384The XSUB will look like the code which follows. A CODE:
385block is used to call the real rpcb_gettime() function with
386the parameters in the correct order for that function.
387
388 bool_t
389 rpcb_gettime(timep,host="localhost")
8e07c86e 390 char *host
391 time_t timep = NO_INIT
a0d0e21e 392 CODE:
393 RETVAL = rpcb_gettime( host, &timep );
394 OUTPUT:
395 timep
396 RETVAL
397
c07a80fd 398=head2 The PREINIT: Keyword
399
400The PREINIT: keyword allows extra variables to be declared before the
401typemaps are expanded. If a variable is declared in a CODE: block then that
402variable will follow any typemap code. This may result in a C syntax
403error. To force the variable to be declared before the typemap code, place
404it into a PREINIT: block. The PREINIT: keyword may be used one or more
405times within an XSUB.
406
407The following examples are equivalent, but if the code is using complex
408typemaps then the first example is safer.
409
410 bool_t
411 rpcb_gettime(timep)
412 time_t timep = NO_INIT
413 PREINIT:
414 char *host = "localhost";
415 CODE:
416 RETVAL = rpcb_gettime( host, &timep );
417 OUTPUT:
418 timep
419 RETVAL
420
421A correct, but error-prone example.
422
423 bool_t
424 rpcb_gettime(timep)
425 time_t timep = NO_INIT
426 CODE:
427 char *host = "localhost";
428 RETVAL = rpcb_gettime( host, &timep );
429 OUTPUT:
430 timep
431 RETVAL
432
84287afe 433=head2 The SCOPE: Keyword
434
435The SCOPE: keyword allows scoping to be enabled for a particular XSUB. If
436enabled, the XSUB will invoke ENTER and LEAVE automatically.
437
438To support potentially complex type mappings, if a typemap entry used
439by this XSUB contains a comment like C</*scope*/> then scoping will
440automatically be enabled for that XSUB.
441
442To enable scoping:
443
444 SCOPE: ENABLE
445
446To disable scoping:
447
448 SCOPE: DISABLE
449
c07a80fd 450=head2 The INPUT: Keyword
451
452The XSUB's parameters are usually evaluated immediately after entering the
453XSUB. The INPUT: keyword can be used to force those parameters to be
454evaluated a little later. The INPUT: keyword can be used multiple times
455within an XSUB and can be used to list one or more input variables. This
456keyword is used with the PREINIT: keyword.
457
458The following example shows how the input parameter C<timep> can be
459evaluated late, after a PREINIT.
460
461 bool_t
462 rpcb_gettime(host,timep)
463 char *host
464 PREINIT:
465 time_t tt;
466 INPUT:
467 time_t timep
468 CODE:
469 RETVAL = rpcb_gettime( host, &tt );
470 timep = tt;
471 OUTPUT:
472 timep
473 RETVAL
474
475The next example shows each input parameter evaluated late.
476
477 bool_t
478 rpcb_gettime(host,timep)
479 PREINIT:
480 time_t tt;
481 INPUT:
482 char *host
483 PREINIT:
484 char *h;
485 INPUT:
486 time_t timep
487 CODE:
488 h = host;
489 RETVAL = rpcb_gettime( h, &tt );
490 timep = tt;
491 OUTPUT:
492 timep
493 RETVAL
494
a0d0e21e 495=head2 Variable-length Parameter Lists
496
497XSUBs can have variable-length parameter lists by specifying an ellipsis
498C<(...)> in the parameter list. This use of the ellipsis is similar to that
499found in ANSI C. The programmer is able to determine the number of
500arguments passed to the XSUB by examining the C<items> variable which the
501B<xsubpp> compiler supplies for all XSUBs. By using this mechanism one can
502create an XSUB which accepts a list of parameters of unknown length.
503
504The I<host> parameter for the rpcb_gettime() XSUB can be
505optional so the ellipsis can be used to indicate that the
506XSUB will take a variable number of parameters. Perl should
d1b91892 507be able to call this XSUB with either of the following statements.
a0d0e21e 508
509 $status = rpcb_gettime( $timep, $host );
510
511 $status = rpcb_gettime( $timep );
512
513The XS code, with ellipsis, follows.
514
515 bool_t
516 rpcb_gettime(timep, ...)
8e07c86e 517 time_t timep = NO_INIT
c07a80fd 518 PREINIT:
a0d0e21e 519 char *host = "localhost";
c07a80fd 520 CODE:
521 if( items > 1 )
522 host = (char *)SvPV(ST(1), na);
523 RETVAL = rpcb_gettime( host, &timep );
a0d0e21e 524 OUTPUT:
525 timep
526 RETVAL
527
528=head2 The PPCODE: Keyword
529
530The PPCODE: keyword is an alternate form of the CODE: keyword and is used
531to tell the B<xsubpp> compiler that the programmer is supplying the code to
d1b91892 532control the argument stack for the XSUBs return values. Occasionally one
a0d0e21e 533will want an XSUB to return a list of values rather than a single value.
534In these cases one must use PPCODE: and then explicitly push the list of
535values on the stack. The PPCODE: and CODE: keywords are not used
536together within the same XSUB.
537
538The following XSUB will call the C rpcb_gettime() function
539and will return its two output values, timep and status, to
540Perl as a single list.
541
d1b91892 542 void
543 rpcb_gettime(host)
8e07c86e 544 char *host
c07a80fd 545 PREINIT:
a0d0e21e 546 time_t timep;
547 bool_t status;
c07a80fd 548 PPCODE:
a0d0e21e 549 status = rpcb_gettime( host, &timep );
550 EXTEND(sp, 2);
cb1a09d0 551 PUSHs(sv_2mortal(newSViv(status)));
552 PUSHs(sv_2mortal(newSViv(timep)));
a0d0e21e 553
554Notice that the programmer must supply the C code necessary
555to have the real rpcb_gettime() function called and to have
556the return values properly placed on the argument stack.
557
558The C<void> return type for this function tells the B<xsubpp> compiler that
559the RETVAL variable is not needed or used and that it should not be created.
560In most scenarios the void return type should be used with the PPCODE:
561directive.
562
563The EXTEND() macro is used to make room on the argument
564stack for 2 return values. The PPCODE: directive causes the
565B<xsubpp> compiler to create a stack pointer called C<sp>, and it
566is this pointer which is being used in the EXTEND() macro.
567The values are then pushed onto the stack with the PUSHs()
568macro.
569
570Now the rpcb_gettime() function can be used from Perl with
571the following statement.
572
573 ($status, $timep) = rpcb_gettime("localhost");
574
575=head2 Returning Undef And Empty Lists
576
5f05dabc 577Occasionally the programmer will want to return simply
a0d0e21e 578C<undef> or an empty list if a function fails rather than a
579separate status value. The rpcb_gettime() function offers
580just this situation. If the function succeeds we would like
581to have it return the time and if it fails we would like to
582have undef returned. In the following Perl code the value
583of $timep will either be undef or it will be a valid time.
584
585 $timep = rpcb_gettime( "localhost" );
586
e7ea3e70 587The following XSUB uses the C<SV *> return type as a mneumonic only,
588and uses a CODE: block to indicate to the compiler
a0d0e21e 589that the programmer has supplied all the necessary code. The
590sv_newmortal() call will initialize the return value to undef, making that
591the default return value.
592
e7ea3e70 593 SV *
a0d0e21e 594 rpcb_gettime(host)
595 char * host
c07a80fd 596 PREINIT:
a0d0e21e 597 time_t timep;
598 bool_t x;
c07a80fd 599 CODE:
a0d0e21e 600 ST(0) = sv_newmortal();
601 if( rpcb_gettime( host, &timep ) )
602 sv_setnv( ST(0), (double)timep);
a0d0e21e 603
604The next example demonstrates how one would place an explicit undef in the
605return value, should the need arise.
606
e7ea3e70 607 SV *
a0d0e21e 608 rpcb_gettime(host)
609 char * host
c07a80fd 610 PREINIT:
a0d0e21e 611 time_t timep;
612 bool_t x;
c07a80fd 613 CODE:
a0d0e21e 614 ST(0) = sv_newmortal();
615 if( rpcb_gettime( host, &timep ) ){
616 sv_setnv( ST(0), (double)timep);
617 }
618 else{
619 ST(0) = &sv_undef;
620 }
a0d0e21e 621
622To return an empty list one must use a PPCODE: block and
623then not push return values on the stack.
624
625 void
626 rpcb_gettime(host)
8e07c86e 627 char *host
c07a80fd 628 PREINIT:
a0d0e21e 629 time_t timep;
c07a80fd 630 PPCODE:
a0d0e21e 631 if( rpcb_gettime( host, &timep ) )
cb1a09d0 632 PUSHs(sv_2mortal(newSViv(timep)));
a0d0e21e 633 else{
634 /* Nothing pushed on stack, so an empty */
635 /* list is implicitly returned. */
636 }
a0d0e21e 637
f27cfbbe 638Some people may be inclined to include an explicit C<return> in the above
639XSUB, rather than letting control fall through to the end. In those
640situations C<XSRETURN_EMPTY> should be used, instead. This will ensure that
641the XSUB stack is properly adjusted. Consult L<perlguts/"API LISTING"> for
642other C<XSRETURN> macros.
643
4633a7c4 644=head2 The REQUIRE: Keyword
645
646The REQUIRE: keyword is used to indicate the minimum version of the
647B<xsubpp> compiler needed to compile the XS module. An XS module which
5f05dabc 648contains the following statement will compile with only B<xsubpp> version
4633a7c4 6491.922 or greater:
650
651 REQUIRE: 1.922
652
a0d0e21e 653=head2 The CLEANUP: Keyword
654
655This keyword can be used when an XSUB requires special cleanup procedures
656before it terminates. When the CLEANUP: keyword is used it must follow
657any CODE:, PPCODE:, or OUTPUT: blocks which are present in the XSUB. The
658code specified for the cleanup block will be added as the last statements
659in the XSUB.
660
661=head2 The BOOT: Keyword
662
663The BOOT: keyword is used to add code to the extension's bootstrap
664function. The bootstrap function is generated by the B<xsubpp> compiler and
665normally holds the statements necessary to register any XSUBs with Perl.
666With the BOOT: keyword the programmer can tell the compiler to add extra
667statements to the bootstrap function.
668
669This keyword may be used any time after the first MODULE keyword and should
670appear on a line by itself. The first blank line after the keyword will
671terminate the code block.
672
673 BOOT:
674 # The following message will be printed when the
675 # bootstrap function executes.
676 printf("Hello from the bootstrap!\n");
677
c07a80fd 678=head2 The VERSIONCHECK: Keyword
679
680The VERSIONCHECK: keyword corresponds to B<xsubpp>'s C<-versioncheck> and
5f05dabc 681C<-noversioncheck> options. This keyword overrides the command line
c07a80fd 682options. Version checking is enabled by default. When version checking is
683enabled the XS module will attempt to verify that its version matches the
684version of the PM module.
685
686To enable version checking:
687
688 VERSIONCHECK: ENABLE
689
690To disable version checking:
691
692 VERSIONCHECK: DISABLE
693
694=head2 The PROTOTYPES: Keyword
695
696The PROTOTYPES: keyword corresponds to B<xsubpp>'s C<-prototypes> and
5f05dabc 697C<-noprototypes> options. This keyword overrides the command-line options.
c07a80fd 698Prototypes are enabled by default. When prototypes are enabled XSUBs will
699be given Perl prototypes. This keyword may be used multiple times in an XS
700module to enable and disable prototypes for different parts of the module.
701
702To enable prototypes:
703
704 PROTOTYPES: ENABLE
705
706To disable prototypes:
707
708 PROTOTYPES: DISABLE
709
710=head2 The PROTOTYPE: Keyword
711
712This keyword is similar to the PROTOTYPES: keyword above but can be used to
713force B<xsubpp> to use a specific prototype for the XSUB. This keyword
714overrides all other prototype options and keywords but affects only the
715current XSUB. Consult L<perlsub/Prototypes> for information about Perl
716prototypes.
717
718 bool_t
719 rpcb_gettime(timep, ...)
720 time_t timep = NO_INIT
721 PROTOTYPE: $;$
722 PREINIT:
723 char *host = "localhost";
724 CODE:
725 if( items > 1 )
726 host = (char *)SvPV(ST(1), na);
727 RETVAL = rpcb_gettime( host, &timep );
728 OUTPUT:
729 timep
730 RETVAL
731
732=head2 The ALIAS: Keyword
733
734The ALIAS: keyword allows an XSUB to have two more more unique Perl names
735and to know which of those names was used when it was invoked. The Perl
736names may be fully-qualified with package names. Each alias is given an
737index. The compiler will setup a variable called C<ix> which contain the
738index of the alias which was used. When the XSUB is called with its
739declared name C<ix> will be 0.
740
741The following example will create aliases C<FOO::gettime()> and
742C<BAR::getit()> for this function.
743
744 bool_t
745 rpcb_gettime(host,timep)
746 char *host
747 time_t &timep
748 ALIAS:
749 FOO::gettime = 1
750 BAR::getit = 2
751 INIT:
752 printf("# ix = %d\n", ix );
753 OUTPUT:
754 timep
755
756=head2 The INCLUDE: Keyword
757
758This keyword can be used to pull other files into the XS module. The other
759files may have XS code. INCLUDE: can also be used to run a command to
760generate the XS code to be pulled into the module.
761
762The file F<Rpcb1.xsh> contains our C<rpcb_gettime()> function:
763
764 bool_t
765 rpcb_gettime(host,timep)
766 char *host
767 time_t &timep
768 OUTPUT:
769 timep
770
771The XS module can use INCLUDE: to pull that file into it.
772
773 INCLUDE: Rpcb1.xsh
774
775If the parameters to the INCLUDE: keyword are followed by a pipe (C<|>) then
776the compiler will interpret the parameters as a command.
777
778 INCLUDE: cat Rpcb1.xsh |
779
780=head2 The CASE: Keyword
781
782The CASE: keyword allows an XSUB to have multiple distinct parts with each
783part acting as a virtual XSUB. CASE: is greedy and if it is used then all
784other XS keywords must be contained within a CASE:. This means nothing may
785precede the first CASE: in the XSUB and anything following the last CASE: is
786included in that case.
787
788A CASE: might switch via a parameter of the XSUB, via the C<ix> ALIAS:
789variable (see L<"The ALIAS: Keyword">), or maybe via the C<items> variable
790(see L<"Variable-length Parameter Lists">). The last CASE: becomes the
791B<default> case if it is not associated with a conditional. The following
792example shows CASE switched via C<ix> with a function C<rpcb_gettime()>
793having an alias C<x_gettime()>. When the function is called as
b772cb6e 794C<rpcb_gettime()> its parameters are the usual C<(char *host, time_t *timep)>,
795but when the function is called as C<x_gettime()> its parameters are
c07a80fd 796reversed, C<(time_t *timep, char *host)>.
797
798 long
799 rpcb_gettime(a,b)
800 CASE: ix == 1
801 ALIAS:
802 x_gettime = 1
803 INPUT:
804 # 'a' is timep, 'b' is host
805 char *b
806 time_t a = NO_INIT
807 CODE:
808 RETVAL = rpcb_gettime( b, &a );
809 OUTPUT:
810 a
811 RETVAL
812 CASE:
813 # 'a' is host, 'b' is timep
814 char *a
815 time_t &b = NO_INIT
816 OUTPUT:
817 b
818 RETVAL
819
820That function can be called with either of the following statements. Note
821the different argument lists.
822
823 $status = rpcb_gettime( $host, $timep );
824
825 $status = x_gettime( $timep, $host );
826
827=head2 The & Unary Operator
828
829The & unary operator is used to tell the compiler that it should dereference
830the object when it calls the C function. This is used when a CODE: block is
831not used and the object is a not a pointer type (the object is an C<int> or
832C<long> but not a C<int*> or C<long*>).
833
834The following XSUB will generate incorrect C code. The xsubpp compiler will
835turn this into code which calls C<rpcb_gettime()> with parameters C<(char
836*host, time_t timep)>, but the real C<rpcb_gettime()> wants the C<timep>
837parameter to be of type C<time_t*> rather than C<time_t>.
838
839 bool_t
840 rpcb_gettime(host,timep)
841 char *host
842 time_t timep
843 OUTPUT:
844 timep
845
846That problem is corrected by using the C<&> operator. The xsubpp compiler
847will now turn this into code which calls C<rpcb_gettime()> correctly with
848parameters C<(char *host, time_t *timep)>. It does this by carrying the
849C<&> through, so the function call looks like C<rpcb_gettime(host, &timep)>.
850
851 bool_t
852 rpcb_gettime(host,timep)
853 char *host
854 time_t &timep
855 OUTPUT:
856 timep
857
a0d0e21e 858=head2 Inserting Comments and C Preprocessor Directives
859
f27cfbbe 860C preprocessor directives are allowed within BOOT:, PREINIT: INIT:,
5f05dabc 861CODE:, PPCODE:, and CLEANUP: blocks, as well as outside the functions.
f27cfbbe 862Comments are allowed anywhere after the MODULE keyword. The compiler
863will pass the preprocessor directives through untouched and will remove
864the commented lines.
b772cb6e 865
f27cfbbe 866Comments can be added to XSUBs by placing a C<#> as the first
867non-whitespace of a line. Care should be taken to avoid making the
868comment look like a C preprocessor directive, lest it be interpreted as
869such. The simplest way to prevent this is to put whitespace in front of
870the C<#>.
871
f27cfbbe 872If you use preprocessor directives to choose one of two
873versions of a function, use
874
875 #if ... version1
876 #else /* ... version2 */
877 #endif
878
879and not
880
881 #if ... version1
882 #endif
883 #if ... version2
884 #endif
885
886because otherwise xsubpp will believe that you made a duplicate
887definition of the function. Also, put a blank line before the
888#else/#endif so it will not be seen as part of the function body.
a0d0e21e 889
890=head2 Using XS With C++
891
892If a function is defined as a C++ method then it will assume
893its first argument is an object pointer. The object pointer
894will be stored in a variable called THIS. The object should
895have been created by C++ with the new() function and should
cb1a09d0 896be blessed by Perl with the sv_setref_pv() macro. The
897blessing of the object by Perl can be handled by a typemap. An example
898typemap is shown at the end of this section.
a0d0e21e 899
900If the method is defined as static it will call the C++
901function using the class::method() syntax. If the method is not static
f27cfbbe 902the function will be called using the THIS-E<gt>method() syntax.
a0d0e21e 903
cb1a09d0 904The next examples will use the following C++ class.
a0d0e21e 905
a5f75d66 906 class color {
cb1a09d0 907 public:
a5f75d66 908 color();
909 ~color();
cb1a09d0 910 int blue();
911 void set_blue( int );
912
913 private:
914 int c_blue;
915 };
916
917The XSUBs for the blue() and set_blue() methods are defined with the class
918name but the parameter for the object (THIS, or "self") is implicit and is
919not listed.
920
921 int
922 color::blue()
a0d0e21e 923
924 void
cb1a09d0 925 color::set_blue( val )
926 int val
a0d0e21e 927
cb1a09d0 928Both functions will expect an object as the first parameter. The xsubpp
929compiler will call that object C<THIS> and will use it to call the specified
930method. So in the C++ code the blue() and set_blue() methods will be called
931in the following manner.
a0d0e21e 932
cb1a09d0 933 RETVAL = THIS->blue();
a0d0e21e 934
cb1a09d0 935 THIS->set_blue( val );
a0d0e21e 936
cb1a09d0 937If the function's name is B<DESTROY> then the C++ C<delete> function will be
938called and C<THIS> will be given as its parameter.
a0d0e21e 939
d1b91892 940 void
cb1a09d0 941 color::DESTROY()
942
943The C++ code will call C<delete>.
944
945 delete THIS;
a0d0e21e 946
cb1a09d0 947If the function's name is B<new> then the C++ C<new> function will be called
948to create a dynamic C++ object. The XSUB will expect the class name, which
949will be kept in a variable called C<CLASS>, to be given as the first
950argument.
a0d0e21e 951
cb1a09d0 952 color *
953 color::new()
a0d0e21e 954
cb1a09d0 955The C++ code will call C<new>.
a0d0e21e 956
cb1a09d0 957 RETVAL = new color();
958
959The following is an example of a typemap that could be used for this C++
960example.
961
962 TYPEMAP
963 color * O_OBJECT
964
965 OUTPUT
966 # The Perl object is blessed into 'CLASS', which should be a
967 # char* having the name of the package for the blessing.
968 O_OBJECT
969 sv_setref_pv( $arg, CLASS, (void*)$var );
a6006777 970
cb1a09d0 971 INPUT
972 O_OBJECT
973 if( sv_isobject($arg) && (SvTYPE(SvRV($arg)) == SVt_PVMG) )
974 $var = ($type)SvIV((SV*)SvRV( $arg ));
975 else{
976 warn( \"${Package}::$func_name() -- $var is not a blessed SV reference\" );
977 XSRETURN_UNDEF;
978 }
a0d0e21e 979
d1b91892 980=head2 Interface Strategy
a0d0e21e 981
982When designing an interface between Perl and a C library a straight
983translation from C to XS is often sufficient. The interface will often be
984very C-like and occasionally nonintuitive, especially when the C function
985modifies one of its parameters. In cases where the programmer wishes to
986create a more Perl-like interface the following strategy may help to
987identify the more critical parts of the interface.
988
989Identify the C functions which modify their parameters. The XSUBs for
990these functions may be able to return lists to Perl, or may be
991candidates to return undef or an empty list in case of failure.
992
d1b91892 993Identify which values are used by only the C and XSUB functions
a0d0e21e 994themselves. If Perl does not need to access the contents of the value
995then it may not be necessary to provide a translation for that value
996from C to Perl.
997
998Identify the pointers in the C function parameter lists and return
999values. Some pointers can be handled in XS with the & unary operator on
1000the variable name while others will require the use of the * operator on
1001the type name. In general it is easier to work with the & operator.
1002
1003Identify the structures used by the C functions. In many
1004cases it may be helpful to use the T_PTROBJ typemap for
1005these structures so they can be manipulated by Perl as
1006blessed objects.
1007
a0d0e21e 1008=head2 Perl Objects And C Structures
1009
1010When dealing with C structures one should select either
1011B<T_PTROBJ> or B<T_PTRREF> for the XS type. Both types are
1012designed to handle pointers to complex objects. The
1013T_PTRREF type will allow the Perl object to be unblessed
1014while the T_PTROBJ type requires that the object be blessed.
1015By using T_PTROBJ one can achieve a form of type-checking
d1b91892 1016because the XSUB will attempt to verify that the Perl object
a0d0e21e 1017is of the expected type.
1018
1019The following XS code shows the getnetconfigent() function which is used
8e07c86e 1020with ONC+ TIRPC. The getnetconfigent() function will return a pointer to a
a0d0e21e 1021C structure and has the C prototype shown below. The example will
1022demonstrate how the C pointer will become a Perl reference. Perl will
1023consider this reference to be a pointer to a blessed object and will
1024attempt to call a destructor for the object. A destructor will be
1025provided in the XS source to free the memory used by getnetconfigent().
1026Destructors in XS can be created by specifying an XSUB function whose name
1027ends with the word B<DESTROY>. XS destructors can be used to free memory
1028which may have been malloc'd by another XSUB.
1029
1030 struct netconfig *getnetconfigent(const char *netid);
1031
1032A C<typedef> will be created for C<struct netconfig>. The Perl
1033object will be blessed in a class matching the name of the C
1034type, with the tag C<Ptr> appended, and the name should not
1035have embedded spaces if it will be a Perl package name. The
1036destructor will be placed in a class corresponding to the
1037class of the object and the PREFIX keyword will be used to
1038trim the name to the word DESTROY as Perl will expect.
1039
1040 typedef struct netconfig Netconfig;
1041
1042 MODULE = RPC PACKAGE = RPC
1043
1044 Netconfig *
1045 getnetconfigent(netid)
8e07c86e 1046 char *netid
a0d0e21e 1047
1048 MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
1049
1050 void
1051 rpcb_DESTROY(netconf)
8e07c86e 1052 Netconfig *netconf
a0d0e21e 1053 CODE:
1054 printf("Now in NetconfigPtr::DESTROY\n");
1055 free( netconf );
1056
1057This example requires the following typemap entry. Consult the typemap
1058section for more information about adding new typemaps for an extension.
1059
1060 TYPEMAP
1061 Netconfig * T_PTROBJ
1062
1063This example will be used with the following Perl statements.
1064
1065 use RPC;
1066 $netconf = getnetconfigent("udp");
1067
1068When Perl destroys the object referenced by $netconf it will send the
1069object to the supplied XSUB DESTROY function. Perl cannot determine, and
1070does not care, that this object is a C struct and not a Perl object. In
1071this sense, there is no difference between the object created by the
1072getnetconfigent() XSUB and an object created by a normal Perl subroutine.
1073
a0d0e21e 1074=head2 The Typemap
1075
1076The typemap is a collection of code fragments which are used by the B<xsubpp>
1077compiler to map C function parameters and values to Perl values. The
1078typemap file may consist of three sections labeled C<TYPEMAP>, C<INPUT>, and
1079C<OUTPUT>. The INPUT section tells the compiler how to translate Perl values
1080into variables of certain C types. The OUTPUT section tells the compiler
1081how to translate the values from certain C types into values Perl can
1082understand. The TYPEMAP section tells the compiler which of the INPUT and
1083OUTPUT code fragments should be used to map a given C type to a Perl value.
1084Each of the sections of the typemap must be preceded by one of the TYPEMAP,
1085INPUT, or OUTPUT keywords.
1086
1087The default typemap in the C<ext> directory of the Perl source contains many
1088useful types which can be used by Perl extensions. Some extensions define
1089additional typemaps which they keep in their own directory. These
1090additional typemaps may reference INPUT and OUTPUT maps in the main
1091typemap. The B<xsubpp> compiler will allow the extension's own typemap to
1092override any mappings which are in the default typemap.
1093
1094Most extensions which require a custom typemap will need only the TYPEMAP
1095section of the typemap file. The custom typemap used in the
1096getnetconfigent() example shown earlier demonstrates what may be the typical
1097use of extension typemaps. That typemap is used to equate a C structure
1098with the T_PTROBJ typemap. The typemap used by getnetconfigent() is shown
1099here. Note that the C type is separated from the XS type with a tab and
1100that the C unary operator C<*> is considered to be a part of the C type name.
1101
1102 TYPEMAP
1103 Netconfig *<tab>T_PTROBJ
1104
1105=head1 EXAMPLES
1106
1107File C<RPC.xs>: Interface to some ONC+ RPC bind library functions.
1108
1109 #include "EXTERN.h"
1110 #include "perl.h"
1111 #include "XSUB.h"
1112
1113 #include <rpc/rpc.h>
1114
1115 typedef struct netconfig Netconfig;
1116
1117 MODULE = RPC PACKAGE = RPC
1118
e7ea3e70 1119 SV *
a0d0e21e 1120 rpcb_gettime(host="localhost")
8e07c86e 1121 char *host
c07a80fd 1122 PREINIT:
a0d0e21e 1123 time_t timep;
c07a80fd 1124 CODE:
a0d0e21e 1125 ST(0) = sv_newmortal();
1126 if( rpcb_gettime( host, &timep ) )
1127 sv_setnv( ST(0), (double)timep );
a0d0e21e 1128
1129 Netconfig *
1130 getnetconfigent(netid="udp")
8e07c86e 1131 char *netid
a0d0e21e 1132
1133 MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
1134
1135 void
1136 rpcb_DESTROY(netconf)
8e07c86e 1137 Netconfig *netconf
a0d0e21e 1138 CODE:
1139 printf("NetconfigPtr::DESTROY\n");
1140 free( netconf );
1141
1142File C<typemap>: Custom typemap for RPC.xs.
1143
1144 TYPEMAP
1145 Netconfig * T_PTROBJ
1146
1147File C<RPC.pm>: Perl module for the RPC extension.
1148
1149 package RPC;
1150
1151 require Exporter;
1152 require DynaLoader;
1153 @ISA = qw(Exporter DynaLoader);
1154 @EXPORT = qw(rpcb_gettime getnetconfigent);
1155
1156 bootstrap RPC;
1157 1;
1158
1159File C<rpctest.pl>: Perl test program for the RPC extension.
1160
1161 use RPC;
1162
1163 $netconf = getnetconfigent();
1164 $a = rpcb_gettime();
1165 print "time = $a\n";
1166 print "netconf = $netconf\n";
1167
1168 $netconf = getnetconfigent("tcp");
1169 $a = rpcb_gettime("poplar");
1170 print "time = $a\n";
1171 print "netconf = $netconf\n";
1172
1173
c07a80fd 1174=head1 XS VERSION
1175
f27cfbbe 1176This document covers features supported by C<xsubpp> 1.935.
c07a80fd 1177
a0d0e21e 1178=head1 AUTHOR
1179
d1b91892 1180Dean Roehrich F<E<lt>roehrich@cray.comE<gt>>
b772cb6e 1181Jul 8, 1996