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