This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Integrate with Sarathy. perl.h and util.c required manual resolving.
[perl5.git] / pod / perlxs.pod
index 5e7699b..ee582e0 100644 (file)
@@ -25,6 +25,11 @@ linked.
 
 See L<perlxstut> for a tutorial on the whole extension creation process.
 
+Note: For many extensions, Dave Beazley's SWIG system provides a
+significantly more convenient mechanism for creating the XS glue
+code. See L<http://www.cs.utah.edu/~beazley/SWIG> for more 
+information.
+
 =head2 On The Road
 
 Many of the examples which follow will concentrate on creating an interface
@@ -167,7 +172,21 @@ be received by Perl as the return value of the XSUB.
 
 If the XSUB has a return type of C<void> then the compiler will
 not supply a RETVAL variable for that function.  When using
-the PPCODE: directive the RETVAL variable may not be needed.
+the PPCODE: directive the RETVAL variable is not needed, unless used
+explicitly.
+
+If PPCODE: directive is not used, C<void> return value should be used
+only for subroutines which do not return a value, I<even if> CODE:
+directive is used which sets ST(0) explicitly.
+
+Older versions of this document recommended to use C<void> return
+value in such cases. It was discovered that this could lead to
+segfaults in cases when XSUB was I<truly> C<void>. This practice is
+now deprecated, and may be not supported at some future version. Use
+the return value C<SV *> in such cases. (Currently C<xsubpp> contains
+some heuristic code which tries to disambiguate between "truly-void"
+and "old-practice-declared-as-void" functions. Hence your code is at
+mercy of this heuristics unless you use C<SV *> as return value.)
 
 =head2 The MODULE Keyword
 
@@ -263,6 +282,17 @@ typemap.
           OUTPUT:
           timep sv_setnv(ST(1), (double)timep);
 
+B<xsubpp> emits an automatic C<SvSETMAGIC()> for all parameters in the
+OUTPUT section of the XSUB, except RETVAL.  This is the usually desired
+behavior, as it takes care of properly invoking 'set' magic on output
+parameters (needed for hash or array element parameters that must be
+created if they didn't exist).  If for some reason, this behavior is
+not desired, the OUTPUT section may contain a C<SETMAGIC: DISABLE> line
+to disable it for the remainder of the parameters in the OUTPUT section.
+Likewise,  C<SETMAGIC: ENABLE> can be used to reenable it for the
+remainder of the OUTPUT section.  See L<perlguts> for more details
+about 'set' magic.
+
 =head2 The CODE: Keyword
 
 This keyword is used in more complicated XSUBs which require
@@ -275,7 +305,7 @@ its parameters.  The Perl usage is given first.
 
      $status = rpcb_gettime( "localhost", $timep );
 
-The XSUB follows. 
+The XSUB follows.
 
      bool_t
      rpcb_gettime(host,timep)
@@ -305,7 +335,7 @@ above, this keyword does not affect the way the compiler handles RETVAL.
 =head2 The NO_INIT Keyword
 
 The NO_INIT keyword is used to indicate that a function
-parameter is being used as only an output value.  The B<xsubpp>
+parameter is being used only as an output value.  The B<xsubpp>
 compiler will normally generate code to read the values of
 all function parameters from the argument stack and assign
 them to C variables upon entry to the function.  NO_INIT
@@ -314,7 +344,7 @@ output rather than for input and that they will be handled
 before the function terminates.
 
 The following example shows a variation of the rpcb_gettime() function.
-This function uses the timep variable as only an output variable and does
+This function uses the timep variable only as an output variable and does
 not care about its initial contents.
 
      bool_t
@@ -330,17 +360,19 @@ Function parameters are normally initialized with their
 values from the argument stack.  The typemaps contain the
 code segments which are used to transfer the Perl values to
 the C parameters.  The programmer, however, is allowed to
-override the typemaps and supply alternate initialization
-code.
+override the typemaps and supply alternate (or additional)
+initialization code.
 
 The following code demonstrates how to supply initialization code for
-function parameters.  The initialization code is eval'd by the compiler
-before it is added to the output so anything which should be interpreted
-literally, such as double quotes, must be protected with backslashes.
+function parameters.  The initialization code is eval'd within double
+quotes by the compiler before it is added to the output so anything
+which should be interpreted literally [mainly C<$>, C<@>, or C<\\>]
+must be protected with backslashes.  The variables $var, $arg,
+and $type can be used as in typemaps.
 
      bool_t
      rpcb_gettime(host,timep)
-          char *host = (char *)SvPV(ST(0),na);
+          char *host = (char *)SvPV($arg,PL_na);
           time_t &timep = 0;
           OUTPUT:
           timep
@@ -350,6 +382,24 @@ would normally use this when a function parameter must be processed by
 another library function before it can be used.  Default parameters are
 covered in the next section.
 
+If the initialization begins with C<=>, then it is output on
+the same line where the input variable is declared.  If the
+initialization begins with C<;> or C<+>, then it is output after
+all of the input variables have been declared.  The C<=> and C<;>
+cases replace the initialization normally supplied from the typemap.
+For the C<+> case, the initialization from the typemap will precede
+the initialization code included after the C<+>.  A global
+variable, C<%v>, is available for the truly rare case where
+information from one initialization is needed in another
+initialization.
+
+     bool_t
+     rpcb_gettime(host,timep)
+          time_t &timep ; /*\$v{time}=@{[$v{time}=$arg]}*/
+          char *host + SvOK($v{time}) ? SvPV($arg,PL_na) : NULL;
+          OUTPUT:
+          timep
+
 =head2 Default Parameter Values
 
 Default values can be specified for function parameters by
@@ -416,6 +466,23 @@ A correct, but error-prone example.
           timep
           RETVAL
 
+=head2 The SCOPE: Keyword
+
+The SCOPE: keyword allows scoping to be enabled for a particular XSUB. If
+enabled, the XSUB will invoke ENTER and LEAVE automatically.
+
+To support potentially complex type mappings, if a typemap entry used
+by this XSUB contains a comment like C</*scope*/> then scoping will
+automatically be enabled for that XSUB.
+
+To enable scoping:
+
+    SCOPE: ENABLE
+
+To disable scoping:
+
+    SCOPE: DISABLE
+
 =head2 The INPUT: Keyword
 
 The XSUB's parameters are usually evaluated immediately after entering the
@@ -486,14 +553,41 @@ The XS code, with ellipsis, follows.
           time_t timep = NO_INIT
          PREINIT:
           char *host = "localhost";
+         STRLEN n_a;
           CODE:
                  if( items > 1 )
-                      host = (char *)SvPV(ST(1), na);
+                      host = (char *)SvPV(ST(1), n_a);
                  RETVAL = rpcb_gettime( host, &timep );
           OUTPUT:
           timep
           RETVAL
 
+=head2 The C_ARGS: Keyword
+
+The C_ARGS: keyword allows creating of XSUBS which have different
+calling sequence from Perl than from C, without a need to write
+CODE: or CPPCODE: section.  The contents of the C_ARGS: paragraph is
+put as the argument to the called C function without any change.
+
+For example, suppose that C function is declared as
+
+    symbolic nth_derivative(int n, symbolic function, int flags);
+
+and that the default flags are kept in a global C variable
+C<default_flags>.  Suppose that you want to create an interface which
+is called as
+
+    $second_deriv = $function->nth_derivative(2);
+
+To do this, declare the XSUB as
+
+    symbolic
+    nth_derivative(function, n)
+       symbolic        function
+       int             n
+    C_ARGS:
+       n, function, default_flags
+
 =head2 The PPCODE: Keyword
 
 The PPCODE: keyword is an alternate form of the CODE: keyword and is used
@@ -516,7 +610,7 @@ Perl as a single list.
           bool_t  status;
           PPCODE:
           status = rpcb_gettime( host, &timep );
-          EXTEND(sp, 2);
+          EXTEND(SP, 2);
           PUSHs(sv_2mortal(newSViv(status)));
           PUSHs(sv_2mortal(newSViv(timep)));
 
@@ -531,7 +625,7 @@ directive.
 
 The EXTEND() macro is used to make room on the argument
 stack for 2 return values.  The PPCODE: directive causes the
-B<xsubpp> compiler to create a stack pointer called C<sp>, and it
+B<xsubpp> compiler to create a stack pointer available as C<SP>, and it
 is this pointer which is being used in the EXTEND() macro.
 The values are then pushed onto the stack with the PUSHs()
 macro.
@@ -541,9 +635,12 @@ the following statement.
 
      ($status, $timep) = rpcb_gettime("localhost");
 
+When handling output parameters with a PPCODE section, be sure to handle
+'set' magic properly.  See L<perlguts> for details about 'set' magic.
+
 =head2 Returning Undef And Empty Lists
 
-Occasionally the programmer will want to simply return
+Occasionally the programmer will want to return simply
 C<undef> or an empty list if a function fails rather than a
 separate status value.  The rpcb_gettime() function offers
 just this situation.  If the function succeeds we would like
@@ -553,13 +650,13 @@ of $timep will either be undef or it will be a valid time.
 
      $timep = rpcb_gettime( "localhost" );
 
-The following XSUB uses the C<void> return type to disable the generation of
-the RETVAL variable and uses a CODE: block to indicate to the compiler
+The following XSUB uses the C<SV *> return type as a mnemonic only,
+and uses a CODE: block to indicate to the compiler
 that the programmer has supplied all the necessary code.  The
 sv_newmortal() call will initialize the return value to undef, making that
 the default return value.
 
-     void
+     SV *
      rpcb_gettime(host)
           char *  host
          PREINIT:
@@ -573,7 +670,7 @@ the default return value.
 The next example demonstrates how one would place an explicit undef in the
 return value, should the need arise.
 
-     void
+     SV *
      rpcb_gettime(host)
           char *  host
          PREINIT:
@@ -585,7 +682,7 @@ return value, should the need arise.
                sv_setnv( ST(0), (double)timep);
           }
           else{
-               ST(0) = &sv_undef;
+               ST(0) = &PL_sv_undef;
           }
 
 To return an empty list one must use a PPCODE: block and
@@ -604,11 +701,17 @@ then not push return values on the stack.
           /* list is implicitly returned. */
           }
 
+Some people may be inclined to include an explicit C<return> in the above
+XSUB, rather than letting control fall through to the end.  In those
+situations C<XSRETURN_EMPTY> should be used, instead.  This will ensure that
+the XSUB stack is properly adjusted.  Consult L<perlguts/"API LISTING"> for
+other C<XSRETURN> macros.
+
 =head2 The REQUIRE: Keyword
 
 The REQUIRE: keyword is used to indicate the minimum version of the
 B<xsubpp> compiler needed to compile the XS module.  An XS module which
-contains the following statement will only compile with B<xsubpp> version
+contains the following statement will compile with only B<xsubpp> version
 1.922 or greater:
 
        REQUIRE: 1.922
@@ -641,7 +744,7 @@ terminate the code block.
 =head2 The VERSIONCHECK: Keyword
 
 The VERSIONCHECK: keyword corresponds to B<xsubpp>'s C<-versioncheck> and
-C<-noversioncheck> options.  This keyword overrides the commandline
+C<-noversioncheck> options.  This keyword overrides the command line
 options.  Version checking is enabled by default.  When version checking is
 enabled the XS module will attempt to verify that its version matches the
 version of the PM module.
@@ -657,7 +760,7 @@ To disable version checking:
 =head2 The PROTOTYPES: Keyword
 
 The PROTOTYPES: keyword corresponds to B<xsubpp>'s C<-prototypes> and
-C<-noprototypes> options.  This keyword overrides the commandline options.
+C<-noprototypes> options.  This keyword overrides the command line options.
 Prototypes are enabled by default.  When prototypes are enabled XSUBs will
 be given Perl prototypes.  This keyword may be used multiple times in an XS
 module to enable and disable prototypes for different parts of the module.
@@ -684,9 +787,10 @@ prototypes.
          PROTOTYPE: $;$
          PREINIT:
           char *host = "localhost";
+         STRLEN n_a;
           CODE:
                  if( items > 1 )
-                      host = (char *)SvPV(ST(1), na);
+                      host = (char *)SvPV(ST(1), n_a);
                  RETVAL = rpcb_gettime( host, &timep );
           OUTPUT:
           timep
@@ -694,7 +798,7 @@ prototypes.
 
 =head2 The ALIAS: Keyword
 
-The ALIAS: keyword allows an XSUB to have two more more unique Perl names
+The ALIAS: keyword allows an XSUB to have two or more unique Perl names
 and to know which of those names was used when it was invoked.  The Perl
 names may be fully-qualified with package names.  Each alias is given an
 index.  The compiler will setup a variable called C<ix> which contain the
@@ -716,6 +820,77 @@ C<BAR::getit()> for this function.
           OUTPUT:
           timep
 
+=head2 The INTERFACE: Keyword
+
+This keyword declares the current XSUB as a keeper of the given
+calling signature.  If some text follows this keyword, it is
+considered as a list of functions which have this signature, and
+should be attached to XSUBs.
+
+Say, if you have 4 functions multiply(), divide(), add(), subtract() all
+having the signature
+
+    symbolic f(symbolic, symbolic);
+
+you code them all by using XSUB
+
+    symbolic
+    interface_s_ss(arg1, arg2)  
+       symbolic        arg1
+       symbolic        arg2
+    INTERFACE:
+       multiply divide 
+       add subtract
+
+The advantage of this approach comparing to ALIAS: keyword is that one
+can attach an extra function remainder() at runtime by using
+    
+    CV *mycv = newXSproto("Symbolic::remainder", 
+                         XS_Symbolic_interface_s_ss, __FILE__, "$$");
+    XSINTERFACE_FUNC_SET(mycv, remainder);
+
+(This example supposes that there was no INTERFACE_MACRO: section,
+otherwise one needs to use something else instead of
+C<XSINTERFACE_FUNC_SET>.)
+
+=head2 The INTERFACE_MACRO: Keyword
+
+This keyword allows one to define an INTERFACE using a different way
+to extract a function pointer from an XSUB.  The text which follows
+this keyword should give the name of macros which would extract/set a
+function pointer.  The extractor macro is given return type, C<CV*>,
+and C<XSANY.any_dptr> for this C<CV*>.  The setter macro is given cv,
+and the function pointer.
+
+The default value is C<XSINTERFACE_FUNC> and C<XSINTERFACE_FUNC_SET>.
+An INTERFACE keyword with an empty list of functions can be omitted if
+INTERFACE_MACRO keyword is used.
+
+Suppose that in the previous example functions pointers for 
+multiply(), divide(), add(), subtract() are kept in a global C array
+C<fp[]> with offsets being C<multiply_off>, C<divide_off>, C<add_off>,
+C<subtract_off>.  Then one can use 
+
+    #define XSINTERFACE_FUNC_BYOFFSET(ret,cv,f) \
+       ((XSINTERFACE_CVT(ret,))fp[CvXSUBANY(cv).any_i32])
+    #define XSINTERFACE_FUNC_BYOFFSET_set(cv,f) \
+       CvXSUBANY(cv).any_i32 = CAT2( f, _off )
+
+in C section,
+
+    symbolic
+    interface_s_ss(arg1, arg2)  
+       symbolic        arg1
+       symbolic        arg2
+    INTERFACE_MACRO: 
+       XSINTERFACE_FUNC_BYOFFSET
+       XSINTERFACE_FUNC_BYOFFSET_set
+    INTERFACE:
+       multiply divide 
+       add subtract
+
+in XSUB section.
+
 =head2 The INCLUDE: Keyword
 
 This keyword can be used to pull other files into the XS module.  The other
@@ -754,8 +929,8 @@ variable (see L<"The ALIAS: Keyword">), or maybe via the C<items> variable
 B<default> case if it is not associated with a conditional.  The following
 example shows CASE switched via C<ix> with a function C<rpcb_gettime()>
 having an alias C<x_gettime()>.  When the function is called as
-C<rpcb_gettime()> it's parameters are the usual C<(char *host, time_t
-*timep)>, but when the function is called as C<x_gettime()> is parameters are
+C<rpcb_gettime()> its parameters are the usual C<(char *host, time_t *timep)>,
+but when the function is called as C<x_gettime()> its parameters are
 reversed, C<(time_t *timep, char *host)>.
 
     long
@@ -820,13 +995,35 @@ C<&> through, so the function call looks like C<rpcb_gettime(host, &timep)>.
 
 =head2 Inserting Comments and C Preprocessor Directives
 
-Comments and C preprocessor directives are allowed within
-CODE:, PPCODE:, BOOT:, and CLEANUP: blocks.  The compiler
-will pass the preprocessor directives through untouched and
-will remove the commented lines.  Comments can be added to
-XSUBs by placing a C<#> at the beginning of the line.  Care
-should be taken to avoid making the comment look like a C
-preprocessor directive, lest it be interpreted as such.
+C preprocessor directives are allowed within BOOT:, PREINIT: INIT:,
+CODE:, PPCODE:, and CLEANUP: blocks, as well as outside the functions.
+Comments are allowed anywhere after the MODULE keyword.  The compiler
+will pass the preprocessor directives through untouched and will remove
+the commented lines.
+
+Comments can be added to XSUBs by placing a C<#> as the first
+non-whitespace of a line.  Care should be taken to avoid making the
+comment look like a C preprocessor directive, lest it be interpreted as
+such.  The simplest way to prevent this is to put whitespace in front of
+the C<#>.
+
+If you use preprocessor directives to choose one of two
+versions of a function, use
+
+    #if ... version1
+    #else /* ... version2  */
+    #endif
+
+and not
+
+    #if ... version1
+    #endif
+    #if ... version2
+    #endif
+
+because otherwise xsubpp will believe that you made a duplicate
+definition of the function.  Also, put a blank line before the
+#else/#endif so it will not be seen as part of the function body.
 
 =head2 Using XS With C++
 
@@ -840,7 +1037,7 @@ typemap is shown at the end of this section.
 
 If the method is defined as static it will call the C++
 function using the class::method() syntax.  If the method is not static
-the function will be called using the THIS->method() syntax.
+the function will be called using the THIS-E<gt>method() syntax.
 
 The next examples will use the following C++ class.
 
@@ -908,7 +1105,7 @@ example.
     # char* having the name of the package for the blessing.
     O_OBJECT
        sv_setref_pv( $arg, CLASS, (void*)$var );
-    
+
     INPUT
     O_OBJECT
        if( sv_isobject($arg) && (SvTYPE(SvRV($arg)) == SVt_PVMG) )
@@ -1017,13 +1214,15 @@ getnetconfigent() XSUB and an object created by a normal Perl subroutine.
 The typemap is a collection of code fragments which are used by the B<xsubpp>
 compiler to map C function parameters and values to Perl values.  The
 typemap file may consist of three sections labeled C<TYPEMAP>, C<INPUT>, and
-C<OUTPUT>.  The INPUT section tells the compiler how to translate Perl values
+C<OUTPUT>.  Any unlabelled initial section is assumed to be a C<TYPEMAP>
+section if a name is not explicitly specified.  The INPUT section tells
+the compiler how to translate Perl values
 into variables of certain C types.  The OUTPUT section tells the compiler
 how to translate the values from certain C types into values Perl can
 understand.  The TYPEMAP section tells the compiler which of the INPUT and
 OUTPUT code fragments should be used to map a given C type to a Perl value.
-Each of the sections of the typemap must be preceded by one of the TYPEMAP,
-INPUT, or OUTPUT keywords.
+The section labels C<TYPEMAP>, C<INPUT>, or C<OUTPUT> must begin
+in the first column on a line by themselves, and must be in uppercase.
 
 The default typemap in the C<ext> directory of the Perl source contains many
 useful types which can be used by Perl extensions.  Some extensions define
@@ -1043,6 +1242,37 @@ that the C unary operator C<*> is considered to be a part of the C type name.
      TYPEMAP
      Netconfig *<tab>T_PTROBJ
 
+Here's a more complicated example: suppose that you wanted C<struct
+netconfig> to be blessed into the class C<Net::Config>.  One way to do
+this is to use underscores (_) to separate package names, as follows:
+
+        typedef struct netconfig * Net_Config;
+
+And then provide a typemap entry C<T_PTROBJ_SPECIAL> that maps underscores to
+double-colons (::), and declare C<Net_Config> to be of that type:
+
+
+        TYPEMAP
+        Net_Config      T_PTROBJ_SPECIAL
+
+        INPUT
+        T_PTROBJ_SPECIAL
+                if (sv_derived_from($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")) {
+                        IV tmp = SvIV((SV*)SvRV($arg));
+                $var = ($type) tmp;
+                }
+                else
+                        croak(\"$var is not of type ${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")
+
+        OUTPUT
+        T_PTROBJ_SPECIAL
+                sv_setref_pv($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\",
+                (void*)$var);
+
+The INPUT and OUTPUT sections substitute underscores for double-colons
+on the fly, giving the desired effect.  This example demonstrates some
+of the power and versatility of the typemap facility.
+
 =head1 EXAMPLES
 
 File C<RPC.xs>: Interface to some ONC+ RPC bind library functions.
@@ -1057,7 +1287,7 @@ File C<RPC.xs>: Interface to some ONC+ RPC bind library functions.
 
      MODULE = RPC  PACKAGE = RPC
 
-     void
+     SV *
      rpcb_gettime(host="localhost")
           char *host
          PREINIT:
@@ -1114,9 +1344,9 @@ File C<rpctest.pl>: Perl test program for the RPC extension.
 
 =head1 XS VERSION
 
-This document covers features supported by C<xsubpp> 1.933.
+This document covers features supported by C<xsubpp> 1.935.
 
 =head1 AUTHOR
 
-Dean Roehrich F<E<lt>roehrich@cray.comE<gt>>
-Feb 13, 1996
+Dean Roehrich <F<roehrich@cray.com>>
+Jul 8, 1996