3 perlxs - XS language reference manual
9 XS is a language used to create an extension interface
10 between Perl and some C library which one wishes to use with
11 Perl. The XS interface is combined with the library to
12 create a new library which can be linked to Perl. An B<XSUB>
13 is a function in the XS language and is the core component
14 of the Perl application interface.
16 The XS compiler is called B<xsubpp>. This compiler will embed
17 the constructs necessary to let an XSUB, which is really a C
18 function in disguise, manipulate Perl values and creates the
19 glue necessary to let Perl access the XSUB. The compiler
20 uses B<typemaps> to determine how to map C function parameters
21 and variables to Perl values. The default typemap handles
22 many common C types. A supplement typemap must be created
23 to handle special structures and types for the library being
26 See L<perlxstut> for a tutorial on the whole extension creation process.
28 Note: For many extensions, Dave Beazley's SWIG system provides a
29 significantly more convenient mechanism for creating the XS glue
30 code. See L<http://www.cs.utah.edu/~beazley/SWIG> for more
35 Many of the examples which follow will concentrate on creating an interface
36 between Perl and the ONC+ RPC bind library functions. The rpcb_gettime()
37 function is used to demonstrate many features of the XS language. This
38 function has two parameters; the first is an input parameter and the second
39 is an output parameter. The function also returns a status value.
41 bool_t rpcb_gettime(const char *host, time_t *timep);
43 From C this function will be called with the following
49 status = rpcb_gettime( "localhost", &timep );
51 If an XSUB is created to offer a direct translation between this function
52 and Perl, then this XSUB will be used from Perl with the following code.
53 The $status and $timep variables will contain the output of the function.
56 $status = rpcb_gettime( "localhost", $timep );
58 The following XS file shows an XS subroutine, or XSUB, which
59 demonstrates one possible interface to the rpcb_gettime()
60 function. This XSUB represents a direct translation between
61 C and Perl and so preserves the interface even from Perl.
62 This XSUB will be invoked from Perl with the usage shown
63 above. Note that the first three #include statements, for
64 C<EXTERN.h>, C<perl.h>, and C<XSUB.h>, will always be present at the
65 beginning of an XS file. This approach and others will be
66 expanded later in this document.
73 MODULE = RPC PACKAGE = RPC
76 rpcb_gettime(host,timep)
82 Any extension to Perl, including those containing XSUBs,
83 should have a Perl module to serve as the bootstrap which
84 pulls the extension into Perl. This module will export the
85 extension's functions and variables to the Perl program and
86 will cause the extension's XSUBs to be linked into Perl.
87 The following module will be used for most of the examples
88 in this document and should be used from Perl with the C<use>
89 command as shown earlier. Perl modules are explained in
90 more detail later in this document.
96 @ISA = qw(Exporter DynaLoader);
97 @EXPORT = qw( rpcb_gettime );
102 Throughout this document a variety of interfaces to the rpcb_gettime()
103 XSUB will be explored. The XSUBs will take their parameters in different
104 orders or will take different numbers of parameters. In each case the
105 XSUB is an abstraction between Perl and the real C rpcb_gettime()
106 function, and the XSUB must always ensure that the real rpcb_gettime()
107 function is called with the correct parameters. This abstraction will
108 allow the programmer to create a more Perl-like interface to the C
111 =head2 The Anatomy of an XSUB
113 The following XSUB allows a Perl program to access a C library function
114 called sin(). The XSUB will imitate the C function which takes a single
115 argument and returns a single value.
121 When using C pointers the indirection operator C<*> should be considered
122 part of the type and the address operator C<&> should be considered part of
123 the variable, as is demonstrated in the rpcb_gettime() function above. See
124 the section on typemaps for more about handling qualifiers and unary
125 operators in C types.
127 The function name and the return type must be placed on
136 The function body may be indented or left-adjusted. The following example
137 shows a function with its body left-adjusted. Most examples in this
138 document will indent the body.
146 =head2 The Argument Stack
148 The argument stack is used to store the values which are
149 sent as parameters to the XSUB and to store the XSUB's
150 return value. In reality all Perl functions keep their
151 values on this stack at the same time, each limited to its
152 own range of positions on the stack. In this document the
153 first position on that stack which belongs to the active
154 function will be referred to as position 0 for that function.
156 XSUBs refer to their stack arguments with the macro B<ST(x)>, where I<x>
157 refers to a position in this XSUB's part of the stack. Position 0 for that
158 function would be known to the XSUB as ST(0). The XSUB's incoming
159 parameters and outgoing return values always begin at ST(0). For many
160 simple cases the B<xsubpp> compiler will generate the code necessary to
161 handle the argument stack by embedding code fragments found in the
162 typemaps. In more complex cases the programmer must supply the code.
164 =head2 The RETVAL Variable
166 The RETVAL variable is a magic variable which always matches
167 the return type of the C library function. The B<xsubpp> compiler will
168 supply this variable in each XSUB and by default will use it to hold the
169 return value of the C library function being called. In simple cases the
170 value of RETVAL will be placed in ST(0) of the argument stack where it can
171 be received by Perl as the return value of the XSUB.
173 If the XSUB has a return type of C<void> then the compiler will
174 not supply a RETVAL variable for that function. When using
175 the PPCODE: directive the RETVAL variable is not needed, unless used
178 If PPCODE: directive is not used, C<void> return value should be used
179 only for subroutines which do not return a value, I<even if> CODE:
180 directive is used which sets ST(0) explicitly.
182 Older versions of this document recommended to use C<void> return
183 value in such cases. It was discovered that this could lead to
184 segfaults in cases when XSUB was I<truely> C<void>. This practice is
185 now deprecated, and may be not supported at some future version. Use
186 the return value C<SV *> in such cases. (Currently C<xsubpp> contains
187 some heuristic code which tries to disambiguate between "truely-void"
188 and "old-practice-declared-as-void" functions. Hence your code is at
189 mercy of this heuristics unless you use C<SV *> as return value.)
191 =head2 The MODULE Keyword
193 The MODULE keyword is used to start the XS code and to
194 specify the package of the functions which are being
195 defined. All text preceding the first MODULE keyword is
196 considered C code and is passed through to the output
197 untouched. Every XS module will have a bootstrap function
198 which is used to hook the XSUBs into Perl. The package name
199 of this bootstrap function will match the value of the last
200 MODULE statement in the XS source files. The value of
201 MODULE should always remain constant within the same XS
202 file, though this is not required.
204 The following example will start the XS code and will place
205 all functions in a package named RPC.
209 =head2 The PACKAGE Keyword
211 When functions within an XS source file must be separated into packages
212 the PACKAGE keyword should be used. This keyword is used with the MODULE
213 keyword and must follow immediately after it when used.
215 MODULE = RPC PACKAGE = RPC
217 [ XS code in package RPC ]
219 MODULE = RPC PACKAGE = RPCB
221 [ XS code in package RPCB ]
223 MODULE = RPC PACKAGE = RPC
225 [ XS code in package RPC ]
227 Although this keyword is optional and in some cases provides redundant
228 information it should always be used. This keyword will ensure that the
229 XSUBs appear in the desired package.
231 =head2 The PREFIX Keyword
233 The PREFIX keyword designates prefixes which should be
234 removed from the Perl function names. If the C function is
235 C<rpcb_gettime()> and the PREFIX value is C<rpcb_> then Perl will
236 see this function as C<gettime()>.
238 This keyword should follow the PACKAGE keyword when used.
239 If PACKAGE is not used then PREFIX should follow the MODULE
242 MODULE = RPC PREFIX = rpc_
244 MODULE = RPC PACKAGE = RPCB PREFIX = rpcb_
246 =head2 The OUTPUT: Keyword
248 The OUTPUT: keyword indicates that certain function parameters should be
249 updated (new values made visible to Perl) when the XSUB terminates or that
250 certain values should be returned to the calling Perl function. For
251 simple functions, such as the sin() function above, the RETVAL variable is
252 automatically designated as an output value. In more complex functions
253 the B<xsubpp> compiler will need help to determine which variables are output
256 This keyword will normally be used to complement the CODE: keyword.
257 The RETVAL variable is not recognized as an output variable when the
258 CODE: keyword is present. The OUTPUT: keyword is used in this
259 situation to tell the compiler that RETVAL really is an output
262 The OUTPUT: keyword can also be used to indicate that function parameters
263 are output variables. This may be necessary when a parameter has been
264 modified within the function and the programmer would like the update to
268 rpcb_gettime(host,timep)
274 The OUTPUT: keyword will also allow an output parameter to
275 be mapped to a matching piece of code rather than to a
279 rpcb_gettime(host,timep)
283 timep sv_setnv(ST(1), (double)timep);
285 B<xsubpp> emits an automatic C<SvSETMAGIC()> for all parameters in the
286 OUTPUT section of the XSUB, except RETVAL. This is the usually desired
287 behavior, as it takes care of properly invoking 'set' magic on output
288 parameters (needed for hash or array element parameters that must be
289 created if they didn't exist). If for some reason, this behavior is
290 not desired, the OUTPUT section may contain a C<SETMAGIC: DISABLE> line
291 to disable it for the remainder of the parameters in the OUTPUT section.
292 Likewise, C<SETMAGIC: ENABLE> can be used to reenable it for the
293 remainder of the OUTPUT section. See L<perlguts> for more details
296 =head2 The CODE: Keyword
298 This keyword is used in more complicated XSUBs which require
299 special handling for the C function. The RETVAL variable is
300 available but will not be returned unless it is specified
301 under the OUTPUT: keyword.
303 The following XSUB is for a C function which requires special handling of
304 its parameters. The Perl usage is given first.
306 $status = rpcb_gettime( "localhost", $timep );
311 rpcb_gettime(host,timep)
315 RETVAL = rpcb_gettime( host, &timep );
320 =head2 The INIT: Keyword
322 The INIT: keyword allows initialization to be inserted into the XSUB before
323 the compiler generates the call to the C function. Unlike the CODE: keyword
324 above, this keyword does not affect the way the compiler handles RETVAL.
327 rpcb_gettime(host,timep)
331 printf("# Host is %s\n", host );
335 =head2 The NO_INIT Keyword
337 The NO_INIT keyword is used to indicate that a function
338 parameter is being used only as an output value. The B<xsubpp>
339 compiler will normally generate code to read the values of
340 all function parameters from the argument stack and assign
341 them to C variables upon entry to the function. NO_INIT
342 will tell the compiler that some parameters will be used for
343 output rather than for input and that they will be handled
344 before the function terminates.
346 The following example shows a variation of the rpcb_gettime() function.
347 This function uses the timep variable only as an output variable and does
348 not care about its initial contents.
351 rpcb_gettime(host,timep)
353 time_t &timep = NO_INIT
357 =head2 Initializing Function Parameters
359 Function parameters are normally initialized with their
360 values from the argument stack. The typemaps contain the
361 code segments which are used to transfer the Perl values to
362 the C parameters. The programmer, however, is allowed to
363 override the typemaps and supply alternate initialization
366 The following code demonstrates how to supply initialization code for
367 function parameters. The initialization code is eval'd by the compiler
368 before it is added to the output so anything which should be interpreted
369 literally, such as double quotes, must be protected with backslashes.
372 rpcb_gettime(host,timep)
373 char *host = (char *)SvPV(ST(0),na);
378 This should not be used to supply default values for parameters. One
379 would normally use this when a function parameter must be processed by
380 another library function before it can be used. Default parameters are
381 covered in the next section.
383 =head2 Default Parameter Values
385 Default values can be specified for function parameters by
386 placing an assignment statement in the parameter list. The
387 default value may be a number or a string. Defaults should
388 always be used on the right-most parameters only.
390 To allow the XSUB for rpcb_gettime() to have a default host
391 value the parameters to the XSUB could be rearranged. The
392 XSUB will then call the real rpcb_gettime() function with
393 the parameters in the correct order. Perl will call this
394 XSUB with either of the following statements.
396 $status = rpcb_gettime( $timep, $host );
398 $status = rpcb_gettime( $timep );
400 The XSUB will look like the code which follows. A CODE:
401 block is used to call the real rpcb_gettime() function with
402 the parameters in the correct order for that function.
405 rpcb_gettime(timep,host="localhost")
407 time_t timep = NO_INIT
409 RETVAL = rpcb_gettime( host, &timep );
414 =head2 The PREINIT: Keyword
416 The PREINIT: keyword allows extra variables to be declared before the
417 typemaps are expanded. If a variable is declared in a CODE: block then that
418 variable will follow any typemap code. This may result in a C syntax
419 error. To force the variable to be declared before the typemap code, place
420 it into a PREINIT: block. The PREINIT: keyword may be used one or more
421 times within an XSUB.
423 The following examples are equivalent, but if the code is using complex
424 typemaps then the first example is safer.
428 time_t timep = NO_INIT
430 char *host = "localhost";
432 RETVAL = rpcb_gettime( host, &timep );
437 A correct, but error-prone example.
441 time_t timep = NO_INIT
443 char *host = "localhost";
444 RETVAL = rpcb_gettime( host, &timep );
449 =head2 The SCOPE: Keyword
451 The SCOPE: keyword allows scoping to be enabled for a particular XSUB. If
452 enabled, the XSUB will invoke ENTER and LEAVE automatically.
454 To support potentially complex type mappings, if a typemap entry used
455 by this XSUB contains a comment like C</*scope*/> then scoping will
456 automatically be enabled for that XSUB.
466 =head2 The INPUT: Keyword
468 The XSUB's parameters are usually evaluated immediately after entering the
469 XSUB. The INPUT: keyword can be used to force those parameters to be
470 evaluated a little later. The INPUT: keyword can be used multiple times
471 within an XSUB and can be used to list one or more input variables. This
472 keyword is used with the PREINIT: keyword.
474 The following example shows how the input parameter C<timep> can be
475 evaluated late, after a PREINIT.
478 rpcb_gettime(host,timep)
485 RETVAL = rpcb_gettime( host, &tt );
491 The next example shows each input parameter evaluated late.
494 rpcb_gettime(host,timep)
505 RETVAL = rpcb_gettime( h, &tt );
511 =head2 Variable-length Parameter Lists
513 XSUBs can have variable-length parameter lists by specifying an ellipsis
514 C<(...)> in the parameter list. This use of the ellipsis is similar to that
515 found in ANSI C. The programmer is able to determine the number of
516 arguments passed to the XSUB by examining the C<items> variable which the
517 B<xsubpp> compiler supplies for all XSUBs. By using this mechanism one can
518 create an XSUB which accepts a list of parameters of unknown length.
520 The I<host> parameter for the rpcb_gettime() XSUB can be
521 optional so the ellipsis can be used to indicate that the
522 XSUB will take a variable number of parameters. Perl should
523 be able to call this XSUB with either of the following statements.
525 $status = rpcb_gettime( $timep, $host );
527 $status = rpcb_gettime( $timep );
529 The XS code, with ellipsis, follows.
532 rpcb_gettime(timep, ...)
533 time_t timep = NO_INIT
535 char *host = "localhost";
538 host = (char *)SvPV(ST(1), na);
539 RETVAL = rpcb_gettime( host, &timep );
544 =head2 The PPCODE: Keyword
546 The PPCODE: keyword is an alternate form of the CODE: keyword and is used
547 to tell the B<xsubpp> compiler that the programmer is supplying the code to
548 control the argument stack for the XSUBs return values. Occasionally one
549 will want an XSUB to return a list of values rather than a single value.
550 In these cases one must use PPCODE: and then explicitly push the list of
551 values on the stack. The PPCODE: and CODE: keywords are not used
552 together within the same XSUB.
554 The following XSUB will call the C rpcb_gettime() function
555 and will return its two output values, timep and status, to
556 Perl as a single list.
565 status = rpcb_gettime( host, &timep );
567 PUSHs(sv_2mortal(newSViv(status)));
568 PUSHs(sv_2mortal(newSViv(timep)));
570 Notice that the programmer must supply the C code necessary
571 to have the real rpcb_gettime() function called and to have
572 the return values properly placed on the argument stack.
574 The C<void> return type for this function tells the B<xsubpp> compiler that
575 the RETVAL variable is not needed or used and that it should not be created.
576 In most scenarios the void return type should be used with the PPCODE:
579 The EXTEND() macro is used to make room on the argument
580 stack for 2 return values. The PPCODE: directive causes the
581 B<xsubpp> compiler to create a stack pointer available as C<SP>, and it
582 is this pointer which is being used in the EXTEND() macro.
583 The values are then pushed onto the stack with the PUSHs()
586 Now the rpcb_gettime() function can be used from Perl with
587 the following statement.
589 ($status, $timep) = rpcb_gettime("localhost");
591 When handling output parameters with a PPCODE section, be sure to handle
592 'set' magic properly. See L<perlguts> for details about 'set' magic.
594 =head2 Returning Undef And Empty Lists
596 Occasionally the programmer will want to return simply
597 C<undef> or an empty list if a function fails rather than a
598 separate status value. The rpcb_gettime() function offers
599 just this situation. If the function succeeds we would like
600 to have it return the time and if it fails we would like to
601 have undef returned. In the following Perl code the value
602 of $timep will either be undef or it will be a valid time.
604 $timep = rpcb_gettime( "localhost" );
606 The following XSUB uses the C<SV *> return type as a mnemonic only,
607 and uses a CODE: block to indicate to the compiler
608 that the programmer has supplied all the necessary code. The
609 sv_newmortal() call will initialize the return value to undef, making that
610 the default return value.
619 ST(0) = sv_newmortal();
620 if( rpcb_gettime( host, &timep ) )
621 sv_setnv( ST(0), (double)timep);
623 The next example demonstrates how one would place an explicit undef in the
624 return value, should the need arise.
633 ST(0) = sv_newmortal();
634 if( rpcb_gettime( host, &timep ) ){
635 sv_setnv( ST(0), (double)timep);
641 To return an empty list one must use a PPCODE: block and
642 then not push return values on the stack.
650 if( rpcb_gettime( host, &timep ) )
651 PUSHs(sv_2mortal(newSViv(timep)));
653 /* Nothing pushed on stack, so an empty */
654 /* list is implicitly returned. */
657 Some people may be inclined to include an explicit C<return> in the above
658 XSUB, rather than letting control fall through to the end. In those
659 situations C<XSRETURN_EMPTY> should be used, instead. This will ensure that
660 the XSUB stack is properly adjusted. Consult L<perlguts/"API LISTING"> for
661 other C<XSRETURN> macros.
663 =head2 The REQUIRE: Keyword
665 The REQUIRE: keyword is used to indicate the minimum version of the
666 B<xsubpp> compiler needed to compile the XS module. An XS module which
667 contains the following statement will compile with only B<xsubpp> version
672 =head2 The CLEANUP: Keyword
674 This keyword can be used when an XSUB requires special cleanup procedures
675 before it terminates. When the CLEANUP: keyword is used it must follow
676 any CODE:, PPCODE:, or OUTPUT: blocks which are present in the XSUB. The
677 code specified for the cleanup block will be added as the last statements
680 =head2 The BOOT: Keyword
682 The BOOT: keyword is used to add code to the extension's bootstrap
683 function. The bootstrap function is generated by the B<xsubpp> compiler and
684 normally holds the statements necessary to register any XSUBs with Perl.
685 With the BOOT: keyword the programmer can tell the compiler to add extra
686 statements to the bootstrap function.
688 This keyword may be used any time after the first MODULE keyword and should
689 appear on a line by itself. The first blank line after the keyword will
690 terminate the code block.
693 # The following message will be printed when the
694 # bootstrap function executes.
695 printf("Hello from the bootstrap!\n");
697 =head2 The VERSIONCHECK: Keyword
699 The VERSIONCHECK: keyword corresponds to B<xsubpp>'s C<-versioncheck> and
700 C<-noversioncheck> options. This keyword overrides the command line
701 options. Version checking is enabled by default. When version checking is
702 enabled the XS module will attempt to verify that its version matches the
703 version of the PM module.
705 To enable version checking:
709 To disable version checking:
711 VERSIONCHECK: DISABLE
713 =head2 The PROTOTYPES: Keyword
715 The PROTOTYPES: keyword corresponds to B<xsubpp>'s C<-prototypes> and
716 C<-noprototypes> options. This keyword overrides the command line options.
717 Prototypes are enabled by default. When prototypes are enabled XSUBs will
718 be given Perl prototypes. This keyword may be used multiple times in an XS
719 module to enable and disable prototypes for different parts of the module.
721 To enable prototypes:
725 To disable prototypes:
729 =head2 The PROTOTYPE: Keyword
731 This keyword is similar to the PROTOTYPES: keyword above but can be used to
732 force B<xsubpp> to use a specific prototype for the XSUB. This keyword
733 overrides all other prototype options and keywords but affects only the
734 current XSUB. Consult L<perlsub/Prototypes> for information about Perl
738 rpcb_gettime(timep, ...)
739 time_t timep = NO_INIT
742 char *host = "localhost";
745 host = (char *)SvPV(ST(1), na);
746 RETVAL = rpcb_gettime( host, &timep );
751 =head2 The ALIAS: Keyword
753 The ALIAS: keyword allows an XSUB to have two more unique Perl names
754 and to know which of those names was used when it was invoked. The Perl
755 names may be fully-qualified with package names. Each alias is given an
756 index. The compiler will setup a variable called C<ix> which contain the
757 index of the alias which was used. When the XSUB is called with its
758 declared name C<ix> will be 0.
760 The following example will create aliases C<FOO::gettime()> and
761 C<BAR::getit()> for this function.
764 rpcb_gettime(host,timep)
771 printf("# ix = %d\n", ix );
775 =head2 The INCLUDE: Keyword
777 This keyword can be used to pull other files into the XS module. The other
778 files may have XS code. INCLUDE: can also be used to run a command to
779 generate the XS code to be pulled into the module.
781 The file F<Rpcb1.xsh> contains our C<rpcb_gettime()> function:
784 rpcb_gettime(host,timep)
790 The XS module can use INCLUDE: to pull that file into it.
794 If the parameters to the INCLUDE: keyword are followed by a pipe (C<|>) then
795 the compiler will interpret the parameters as a command.
797 INCLUDE: cat Rpcb1.xsh |
799 =head2 The CASE: Keyword
801 The CASE: keyword allows an XSUB to have multiple distinct parts with each
802 part acting as a virtual XSUB. CASE: is greedy and if it is used then all
803 other XS keywords must be contained within a CASE:. This means nothing may
804 precede the first CASE: in the XSUB and anything following the last CASE: is
805 included in that case.
807 A CASE: might switch via a parameter of the XSUB, via the C<ix> ALIAS:
808 variable (see L<"The ALIAS: Keyword">), or maybe via the C<items> variable
809 (see L<"Variable-length Parameter Lists">). The last CASE: becomes the
810 B<default> case if it is not associated with a conditional. The following
811 example shows CASE switched via C<ix> with a function C<rpcb_gettime()>
812 having an alias C<x_gettime()>. When the function is called as
813 C<rpcb_gettime()> its parameters are the usual C<(char *host, time_t *timep)>,
814 but when the function is called as C<x_gettime()> its parameters are
815 reversed, C<(time_t *timep, char *host)>.
823 # 'a' is timep, 'b' is host
827 RETVAL = rpcb_gettime( b, &a );
832 # 'a' is host, 'b' is timep
839 That function can be called with either of the following statements. Note
840 the different argument lists.
842 $status = rpcb_gettime( $host, $timep );
844 $status = x_gettime( $timep, $host );
846 =head2 The & Unary Operator
848 The & unary operator is used to tell the compiler that it should dereference
849 the object when it calls the C function. This is used when a CODE: block is
850 not used and the object is a not a pointer type (the object is an C<int> or
851 C<long> but not a C<int*> or C<long*>).
853 The following XSUB will generate incorrect C code. The xsubpp compiler will
854 turn this into code which calls C<rpcb_gettime()> with parameters C<(char
855 *host, time_t timep)>, but the real C<rpcb_gettime()> wants the C<timep>
856 parameter to be of type C<time_t*> rather than C<time_t>.
859 rpcb_gettime(host,timep)
865 That problem is corrected by using the C<&> operator. The xsubpp compiler
866 will now turn this into code which calls C<rpcb_gettime()> correctly with
867 parameters C<(char *host, time_t *timep)>. It does this by carrying the
868 C<&> through, so the function call looks like C<rpcb_gettime(host, &timep)>.
871 rpcb_gettime(host,timep)
877 =head2 Inserting Comments and C Preprocessor Directives
879 C preprocessor directives are allowed within BOOT:, PREINIT: INIT:,
880 CODE:, PPCODE:, and CLEANUP: blocks, as well as outside the functions.
881 Comments are allowed anywhere after the MODULE keyword. The compiler
882 will pass the preprocessor directives through untouched and will remove
885 Comments can be added to XSUBs by placing a C<#> as the first
886 non-whitespace of a line. Care should be taken to avoid making the
887 comment look like a C preprocessor directive, lest it be interpreted as
888 such. The simplest way to prevent this is to put whitespace in front of
891 If you use preprocessor directives to choose one of two
892 versions of a function, use
895 #else /* ... version2 */
905 because otherwise xsubpp will believe that you made a duplicate
906 definition of the function. Also, put a blank line before the
907 #else/#endif so it will not be seen as part of the function body.
909 =head2 Using XS With C++
911 If a function is defined as a C++ method then it will assume
912 its first argument is an object pointer. The object pointer
913 will be stored in a variable called THIS. The object should
914 have been created by C++ with the new() function and should
915 be blessed by Perl with the sv_setref_pv() macro. The
916 blessing of the object by Perl can be handled by a typemap. An example
917 typemap is shown at the end of this section.
919 If the method is defined as static it will call the C++
920 function using the class::method() syntax. If the method is not static
921 the function will be called using the THIS-E<gt>method() syntax.
923 The next examples will use the following C++ class.
930 void set_blue( int );
936 The XSUBs for the blue() and set_blue() methods are defined with the class
937 name but the parameter for the object (THIS, or "self") is implicit and is
944 color::set_blue( val )
947 Both functions will expect an object as the first parameter. The xsubpp
948 compiler will call that object C<THIS> and will use it to call the specified
949 method. So in the C++ code the blue() and set_blue() methods will be called
950 in the following manner.
952 RETVAL = THIS->blue();
954 THIS->set_blue( val );
956 If the function's name is B<DESTROY> then the C++ C<delete> function will be
957 called and C<THIS> will be given as its parameter.
962 The C++ code will call C<delete>.
966 If the function's name is B<new> then the C++ C<new> function will be called
967 to create a dynamic C++ object. The XSUB will expect the class name, which
968 will be kept in a variable called C<CLASS>, to be given as the first
974 The C++ code will call C<new>.
976 RETVAL = new color();
978 The following is an example of a typemap that could be used for this C++
985 # The Perl object is blessed into 'CLASS', which should be a
986 # char* having the name of the package for the blessing.
988 sv_setref_pv( $arg, CLASS, (void*)$var );
992 if( sv_isobject($arg) && (SvTYPE(SvRV($arg)) == SVt_PVMG) )
993 $var = ($type)SvIV((SV*)SvRV( $arg ));
995 warn( \"${Package}::$func_name() -- $var is not a blessed SV reference\" );
999 =head2 Interface Strategy
1001 When designing an interface between Perl and a C library a straight
1002 translation from C to XS is often sufficient. The interface will often be
1003 very C-like and occasionally nonintuitive, especially when the C function
1004 modifies one of its parameters. In cases where the programmer wishes to
1005 create a more Perl-like interface the following strategy may help to
1006 identify the more critical parts of the interface.
1008 Identify the C functions which modify their parameters. The XSUBs for
1009 these functions may be able to return lists to Perl, or may be
1010 candidates to return undef or an empty list in case of failure.
1012 Identify which values are used by only the C and XSUB functions
1013 themselves. If Perl does not need to access the contents of the value
1014 then it may not be necessary to provide a translation for that value
1017 Identify the pointers in the C function parameter lists and return
1018 values. Some pointers can be handled in XS with the & unary operator on
1019 the variable name while others will require the use of the * operator on
1020 the type name. In general it is easier to work with the & operator.
1022 Identify the structures used by the C functions. In many
1023 cases it may be helpful to use the T_PTROBJ typemap for
1024 these structures so they can be manipulated by Perl as
1027 =head2 Perl Objects And C Structures
1029 When dealing with C structures one should select either
1030 B<T_PTROBJ> or B<T_PTRREF> for the XS type. Both types are
1031 designed to handle pointers to complex objects. The
1032 T_PTRREF type will allow the Perl object to be unblessed
1033 while the T_PTROBJ type requires that the object be blessed.
1034 By using T_PTROBJ one can achieve a form of type-checking
1035 because the XSUB will attempt to verify that the Perl object
1036 is of the expected type.
1038 The following XS code shows the getnetconfigent() function which is used
1039 with ONC+ TIRPC. The getnetconfigent() function will return a pointer to a
1040 C structure and has the C prototype shown below. The example will
1041 demonstrate how the C pointer will become a Perl reference. Perl will
1042 consider this reference to be a pointer to a blessed object and will
1043 attempt to call a destructor for the object. A destructor will be
1044 provided in the XS source to free the memory used by getnetconfigent().
1045 Destructors in XS can be created by specifying an XSUB function whose name
1046 ends with the word B<DESTROY>. XS destructors can be used to free memory
1047 which may have been malloc'd by another XSUB.
1049 struct netconfig *getnetconfigent(const char *netid);
1051 A C<typedef> will be created for C<struct netconfig>. The Perl
1052 object will be blessed in a class matching the name of the C
1053 type, with the tag C<Ptr> appended, and the name should not
1054 have embedded spaces if it will be a Perl package name. The
1055 destructor will be placed in a class corresponding to the
1056 class of the object and the PREFIX keyword will be used to
1057 trim the name to the word DESTROY as Perl will expect.
1059 typedef struct netconfig Netconfig;
1061 MODULE = RPC PACKAGE = RPC
1064 getnetconfigent(netid)
1067 MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
1070 rpcb_DESTROY(netconf)
1073 printf("Now in NetconfigPtr::DESTROY\n");
1076 This example requires the following typemap entry. Consult the typemap
1077 section for more information about adding new typemaps for an extension.
1080 Netconfig * T_PTROBJ
1082 This example will be used with the following Perl statements.
1085 $netconf = getnetconfigent("udp");
1087 When Perl destroys the object referenced by $netconf it will send the
1088 object to the supplied XSUB DESTROY function. Perl cannot determine, and
1089 does not care, that this object is a C struct and not a Perl object. In
1090 this sense, there is no difference between the object created by the
1091 getnetconfigent() XSUB and an object created by a normal Perl subroutine.
1095 The typemap is a collection of code fragments which are used by the B<xsubpp>
1096 compiler to map C function parameters and values to Perl values. The
1097 typemap file may consist of three sections labeled C<TYPEMAP>, C<INPUT>, and
1098 C<OUTPUT>. The INPUT section tells the compiler how to translate Perl values
1099 into variables of certain C types. The OUTPUT section tells the compiler
1100 how to translate the values from certain C types into values Perl can
1101 understand. The TYPEMAP section tells the compiler which of the INPUT and
1102 OUTPUT code fragments should be used to map a given C type to a Perl value.
1103 Each of the sections of the typemap must be preceded by one of the TYPEMAP,
1104 INPUT, or OUTPUT keywords.
1106 The default typemap in the C<ext> directory of the Perl source contains many
1107 useful types which can be used by Perl extensions. Some extensions define
1108 additional typemaps which they keep in their own directory. These
1109 additional typemaps may reference INPUT and OUTPUT maps in the main
1110 typemap. The B<xsubpp> compiler will allow the extension's own typemap to
1111 override any mappings which are in the default typemap.
1113 Most extensions which require a custom typemap will need only the TYPEMAP
1114 section of the typemap file. The custom typemap used in the
1115 getnetconfigent() example shown earlier demonstrates what may be the typical
1116 use of extension typemaps. That typemap is used to equate a C structure
1117 with the T_PTROBJ typemap. The typemap used by getnetconfigent() is shown
1118 here. Note that the C type is separated from the XS type with a tab and
1119 that the C unary operator C<*> is considered to be a part of the C type name.
1122 Netconfig *<tab>T_PTROBJ
1124 Here's a more complicated example: suppose that you wanted C<struct
1125 netconfig> to be blessed into the class C<Net::Config>. One way to do
1126 this is to use underscores (_) to separate package names, as follows:
1128 typedef struct netconfig * Net_Config;
1130 And then provide a typemap entry C<T_PTROBJ_SPECIAL> that maps underscores to
1131 double-colons (::), and declare C<Net_Config> to be of that type:
1135 Net_Config T_PTROBJ_SPECIAL
1139 if (sv_derived_from($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")) {
1140 IV tmp = SvIV((SV*)SvRV($arg));
1144 croak(\"$var is not of type ${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")
1148 sv_setref_pv($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\",
1151 The INPUT and OUTPUT sections substitute underscores for double-colons
1152 on the fly, giving the desired effect. This example demonstrates some
1153 of the power and versatility of the typemap facility.
1157 File C<RPC.xs>: Interface to some ONC+ RPC bind library functions.
1163 #include <rpc/rpc.h>
1165 typedef struct netconfig Netconfig;
1167 MODULE = RPC PACKAGE = RPC
1170 rpcb_gettime(host="localhost")
1175 ST(0) = sv_newmortal();
1176 if( rpcb_gettime( host, &timep ) )
1177 sv_setnv( ST(0), (double)timep );
1180 getnetconfigent(netid="udp")
1183 MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
1186 rpcb_DESTROY(netconf)
1189 printf("NetconfigPtr::DESTROY\n");
1192 File C<typemap>: Custom typemap for RPC.xs.
1195 Netconfig * T_PTROBJ
1197 File C<RPC.pm>: Perl module for the RPC extension.
1203 @ISA = qw(Exporter DynaLoader);
1204 @EXPORT = qw(rpcb_gettime getnetconfigent);
1209 File C<rpctest.pl>: Perl test program for the RPC extension.
1213 $netconf = getnetconfigent();
1214 $a = rpcb_gettime();
1215 print "time = $a\n";
1216 print "netconf = $netconf\n";
1218 $netconf = getnetconfigent("tcp");
1219 $a = rpcb_gettime("poplar");
1220 print "time = $a\n";
1221 print "netconf = $netconf\n";
1226 This document covers features supported by C<xsubpp> 1.935.
1230 Dean Roehrich <F<roehrich@cray.com>>