home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl501m.zip / pod / perlapi.pod < prev    next >
Text File  |  1995-07-03  |  35KB  |  960 lines

  1. =head1 NAME
  2.  
  3. perlapi - Perl 5 application programming interface for C extensions
  4.  
  5. =head1 DESCRIPTION
  6.  
  7. =head2 Introduction
  8.  
  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.
  15.  
  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
  24. linked.
  25.  
  26. Many of the examples which follow will concentrate on creating an
  27. interface between Perl and the ONC+RPC bind library functions.
  28. Specifically, the rpcb_gettime() function will be used to demonstrate many
  29. features of the XS language.  This function has two parameters; the first
  30. is an input parameter and the second is an output parameter.  The function
  31. also returns a status value.
  32.  
  33.     bool_t rpcb_gettime(const char *host, time_t *timep);
  34.  
  35. From C this function will be called with the following
  36. statements.
  37.  
  38.      #include <rpc/rpc.h>
  39.      bool_t status;
  40.      time_t timep;
  41.      status = rpcb_gettime( "localhost", &timep );
  42.  
  43. If an XSUB is created to offer a direct translation between this function
  44. and Perl, then this XSUB will be used from Perl with the following code.
  45. The $status and $timep variables will contain the output of the function.
  46.  
  47.      use RPC;
  48.      $status = rpcb_gettime( "localhost", $timep );
  49.  
  50. The following XS file shows an XS subroutine, or XSUB, which
  51. demonstrates one possible interface to the rpcb_gettime()
  52. function.  This XSUB represents a direct translation between
  53. C and Perl and so preserves the interface even from Perl.
  54. This XSUB will be invoked from Perl with the usage shown
  55. above.  Note that the first three #include statements, for
  56. C<EXTERN.h>, C<perl.h>, and C<XSUB.h>, will always be present at the
  57. beginning of an XS file.  This approach and others will be
  58. expanded later in this document.
  59.  
  60.      #include "EXTERN.h"
  61.      #include "perl.h"
  62.      #include "XSUB.h"
  63.      #include <rpc/rpc.h>
  64.  
  65.      MODULE = RPC  PACKAGE = RPC
  66.  
  67.      bool_t
  68.      rpcb_gettime(host,timep)
  69.           char *  host
  70.           time_t  &timep
  71.           OUTPUT:
  72.           timep
  73.  
  74. Any extension to Perl, including those containing XSUBs,
  75. should have a Perl module to serve as the bootstrap which
  76. pulls the extension into Perl.  This module will export the
  77. extension's functions and variables to the Perl program and
  78. will cause the extension's XSUBs to be linked into Perl.
  79. The following module will be used for most of the examples
  80. in this document and should be used from Perl with the C<use>
  81. command as shown earlier.  Perl modules are explained in
  82. more detail later in this document.
  83.  
  84.      package RPC;
  85.  
  86.      require Exporter;
  87.      require DynaLoader;
  88.      @ISA = qw(Exporter DynaLoader);
  89.      @EXPORT = qw( rpcb_gettime );
  90.  
  91.      bootstrap RPC;
  92.      1;
  93.  
  94. Throughout this document a variety of interfaces to the rpcb_gettime()
  95. XSUB will be explored.  The XSUBs will take their parameters in different
  96. orders or will take different numbers of parameters.  In each case the
  97. XSUB is an abstraction between Perl and the real C rpcb_gettime()
  98. function, and the XSUB must always ensure that the real rpcb_gettime()
  99. function is called with the correct parameters.  This abstraction will
  100. allow the programmer to create a more Perl-like interface to the C
  101. function.
  102.  
  103. It is recommended that the B<h2xs> tool be used when creating new
  104. extensions.  This tool will generate template source files and Makefiles.
  105. This is discussed in more detail in the section titled "Creating A New
  106. Extension" and in the B<h2xs> manpage.
  107.  
  108. =head2 The Anatomy of an XSUB
  109.  
  110. The following XSUB allows a Perl program to access a  C  library  function  called  sin().  The XSUB will imitate the C
  111. function which takes a single argument and returns a  single
  112. value.
  113.  
  114.      double
  115.      sin(x)
  116.        double<tab>x
  117.  
  118. The compiler expects a tab between the parameter name and its type, and
  119. any or no whitespace before the type.  When using C pointers the
  120. indirection operator C<*> should be considered part of the type and the
  121. address operator C<&> should be considered part of the variable, as is
  122. demonstrated in the rpcb_gettime() function above.  See the section on
  123. typemaps for more about handling qualifiers and unary operators in C
  124. types.
  125.  
  126. The parameter list of a function must not have whitespace
  127. after the open-parenthesis or before the close-parenthesis.
  128.  
  129.    INCORRECT                      CORRECT
  130.  
  131.    double                         double
  132.    sin( x )                       sin(x)
  133.      double  x                      double  x
  134.  
  135. The function name and the return type must be placed on
  136. separate lines.
  137.  
  138.   INCORRECT                        CORRECT
  139.  
  140.   double sin(x)                    double
  141.     double  x                      sin(x)
  142.                      double  x
  143.  
  144. =head2 The Argument Stack
  145.  
  146. The argument stack is used to store the values which are
  147. sent as parameters to the XSUB and to store the XSUB's
  148. return value.  In reality all Perl functions keep their
  149. values on this stack at the same time, each limited to its
  150. own range of positions on the stack.  In this document the
  151. first position on that stack which belongs to the active
  152. function will be referred to as position 0 for that function.
  153.  
  154. XSUBs refer to their stack arguments with the macro B<ST(x)>, where I<x> refers
  155. to a position in this XSUB's part of the stack.  Position 0 for that
  156. function would be known to the XSUB as ST(0).  The XSUB's incoming
  157. parameters and outgoing return values always begin at ST(0).  For many
  158. simple cases the B<xsubpp> compiler will generate the code necessary to
  159. handle the argument stack by embedding code fragments found in the
  160. typemaps.  In more complex cases the programmer must supply the code.
  161.  
  162. =head2 The RETVAL Variable
  163.  
  164. The RETVAL variable is a magic variable which always matches
  165. the return type of the C library function.  The B<xsubpp> compiler will
  166. supply this variable in each XSUB and by default will use it to hold the
  167. return value of the C library function being called.  In simple cases the
  168. value of RETVAL will be placed in ST(0) of the argument stack where it can
  169. be received by Perl as the return value of the XSUB.
  170.  
  171. If the XSUB has a return type of C<void> then the compiler will
  172. not supply a RETVAL variable for that function.  When using
  173. the PPCODE: directive the RETVAL variable may not be needed.
  174.  
  175. =head2 The MODULE Keyword
  176.  
  177. The MODULE keyword is used to start the XS code and to
  178. specify the package of the functions which are being
  179. defined.  All text preceding the first MODULE keyword is
  180. considered C code and is passed through to the output
  181. untouched.  Every XS module will have a bootstrap function
  182. which is used to hook the XSUBs into Perl.  The package name
  183. of this bootstrap function will match the value of the last
  184. MODULE statement in the XS source files.  The value of
  185. MODULE should always remain constant within the same XS
  186. file, though this is not required.
  187.  
  188. The following example will start the XS code and will place
  189. all functions in a package named RPC.
  190.  
  191.      MODULE = RPC
  192.  
  193. =head2 The PACKAGE Keyword
  194.  
  195. When functions within an XS source file must be separated into packages
  196. the PACKAGE keyword should be used.  This keyword is used with the MODULE
  197. keyword and must follow immediately after it when used.
  198.  
  199.      MODULE = RPC  PACKAGE = RPC
  200.  
  201.      [ XS code in package RPC ]
  202.  
  203.      MODULE = RPC  PACKAGE = RPCB
  204.  
  205.      [ XS code in package RPCB ]
  206.  
  207.      MODULE = RPC  PACKAGE = RPC
  208.  
  209.      [ XS code in package RPC ]
  210.  
  211. Although this keyword is optional and in some cases provides redundant
  212. information it should always be used.  This keyword will ensure that the
  213. XSUBs appear in the desired package.
  214.  
  215. =head2 The PREFIX Keyword
  216.  
  217. The PREFIX keyword designates prefixes which should be
  218. removed from the Perl function names.  If the C function is
  219. C<rpcb_gettime()> and the PREFIX value is C<rpcb_> then Perl will
  220. see this function as C<gettime()>.
  221.  
  222. This keyword should follow the PACKAGE keyword when used.
  223. If PACKAGE is not used then PREFIX should follow the MODULE
  224. keyword.
  225.  
  226.      MODULE = RPC  PREFIX = rpc_
  227.  
  228.      MODULE = RPC  PACKAGE = RPCB  PREFIX = rpcb_
  229.  
  230. =head2 The OUTPUT: Keyword
  231.  
  232. The OUTPUT: keyword indicates that certain function parameters should be
  233. updated (new values made visible to Perl) when the XSUB terminates or that
  234. certain values should be returned to the calling Perl function.  For
  235. simple functions, such as the sin() function above, the RETVAL variable is
  236. automatically designated as an output value.  In more complex functions
  237. the B<xsubpp> compiler will need help to determine which variables are output
  238. variables.
  239.  
  240. This keyword will normally be used to complement the CODE:  keyword.
  241. The RETVAL variable is not recognized as an output variable when the
  242. CODE: keyword is present.  The OUTPUT:  keyword is used in this
  243. situation to tell the compiler that RETVAL really is an output
  244. variable.
  245.  
  246. The OUTPUT: keyword can also be used to indicate that function parameters
  247. are output variables.  This may be necessary when a parameter has been
  248. modified within the function and the programmer would like the update to
  249. be seen by Perl.  If function parameters are listed under OUTPUT: along
  250. with the RETVAL variable then the RETVAL variable must be the last one
  251. listed.
  252.  
  253.      bool_t
  254.      rpcb_gettime(host,timep)
  255.           char *  host
  256.           time_t  &timep
  257.           OUTPUT:
  258.           timep
  259.  
  260. The OUTPUT: keyword will also allow an output parameter to
  261. be mapped to a matching piece of code rather than to a
  262. typemap.
  263.  
  264.      bool_t
  265.      rpcb_gettime(host,timep)
  266.           char *  host
  267.           time_t  &timep
  268.           OUTPUT:
  269.           timep<tab>sv_setnv(ST(1), (double)timep);
  270.  
  271. =head2 The CODE: Keyword
  272.  
  273. This keyword is used in more complicated XSUBs which require
  274. special handling for the C function.  The RETVAL variable is
  275. available but will not be returned unless it is specified
  276. under the OUTPUT: keyword.
  277.  
  278. The following XSUB is for a C function which requires special handling of
  279. its parameters.  The Perl usage is given first.
  280.  
  281.      $status = rpcb_gettime( "localhost", $timep );
  282.  
  283. The XSUB follows. 
  284.  
  285.      bool_t
  286.      rpcb_gettime(host,timep)
  287.           char *  host
  288.           time_t  timep
  289.           CODE:
  290.                RETVAL = rpcb_gettime( host, &timep );
  291.           OUTPUT:
  292.           timep
  293.           RETVAL
  294.  
  295. In many of the examples shown here the CODE: block (and
  296. other blocks) will often be contained within braces ( C<{> and
  297. C<}> ).  This protects the CODE: block from complex INPUT
  298. typemaps and ensures the resulting C code is legal.
  299.  
  300. =head2 The NO_INIT Keyword
  301.  
  302. The NO_INIT keyword is used to indicate that a function
  303. parameter is being used as only an output value.  The B<xsubpp>
  304. compiler will normally generate code to read the values of
  305. all function parameters from the argument stack and assign
  306. them to C variables upon entry to the function.  NO_INIT
  307. will tell the compiler that some parameters will be used for
  308. output rather than for input and that they will be handled
  309. before the function terminates.
  310.  
  311. The following example shows a variation of the rpcb_gettime() function.
  312. This function uses the timep variable as only an output variable and does
  313. not care about its initial contents.
  314.  
  315.      bool_t
  316.      rpcb_gettime(host,timep)
  317.           char *  host
  318.           time_t  &timep = NO_INIT
  319.           OUTPUT:
  320.           timep
  321.  
  322. =head2 Initializing Function Parameters
  323.  
  324. Function parameters are normally initialized with their
  325. values from the argument stack.  The typemaps contain the
  326. code segments which are used to transfer the Perl values to
  327. the C parameters.  The programmer, however, is allowed to
  328. override the typemaps and supply alternate initialization
  329. code.
  330.  
  331. The following code demonstrates how to supply initialization code for
  332. function parameters.  The initialization code is eval'd by the compiler
  333. before it is added to the output so anything which should be interpreted
  334. literally, such as double quotes, must be protected with backslashes.
  335.  
  336.      bool_t
  337.      rpcb_gettime(host,timep)
  338.           char *  host = (char *)SvPV(ST(0),na);
  339.           time_t  &timep = 0;
  340.           OUTPUT:
  341.           timep
  342.  
  343. This should not be used to supply default values for parameters.  One
  344. would normally use this when a function parameter must be processed by
  345. another library function before it can be used.  Default parameters are
  346. covered in the next section.
  347.  
  348. =head2 Default Parameter Values
  349.  
  350. Default values can be specified for function parameters by
  351. placing an assignment statement in the parameter list.  The
  352. default value may be a number or a string.  Defaults should
  353. always be used on the right-most parameters only.
  354.  
  355. To allow the XSUB for rpcb_gettime() to have a default host
  356. value the parameters to the XSUB could be rearranged.  The
  357. XSUB will then call the real rpcb_gettime() function with
  358. the parameters in the correct order.  Perl will call this
  359. XSUB with either of the following statements.
  360.  
  361.      $status = rpcb_gettime( $timep, $host );
  362.  
  363.      $status = rpcb_gettime( $timep );
  364.  
  365. The XSUB will look like the code  which  follows.   A  CODE:
  366. block  is used to call the real rpcb_gettime() function with
  367. the parameters in the correct order for that function.
  368.  
  369.      bool_t
  370.      rpcb_gettime(timep,host="localhost")
  371.           char *  host
  372.           time_t  timep = NO_INIT
  373.           CODE:
  374.                RETVAL = rpcb_gettime( host, &timep );
  375.           OUTPUT:
  376.           timep
  377.           RETVAL
  378.  
  379. =head2 Variable-length Parameter Lists
  380.  
  381. XSUBs can have variable-length parameter lists by specifying an ellipsis
  382. C<(...)> in the parameter list.  This use of the ellipsis is similar to that
  383. found in ANSI C.  The programmer is able to determine the number of
  384. arguments passed to the XSUB by examining the C<items> variable which the
  385. B<xsubpp> compiler supplies for all XSUBs.  By using this mechanism one can
  386. create an XSUB which accepts a list of parameters of unknown length.
  387.  
  388. The I<host> parameter for the rpcb_gettime() XSUB can be
  389. optional so the ellipsis can be used to indicate that the
  390. XSUB will take a variable number of parameters.  Perl should
  391. be able to call this XSUB with either of the following statements.
  392.  
  393.      $status = rpcb_gettime( $timep, $host );
  394.  
  395.      $status = rpcb_gettime( $timep );
  396.  
  397. The XS code, with ellipsis, follows.
  398.  
  399.      bool_t
  400.      rpcb_gettime(timep, ...)
  401.           time_t  timep = NO_INIT
  402.           CODE:
  403.           {
  404.           char *host = "localhost";
  405.  
  406.           if( items > 1 )
  407.                host = (char *)SvPV(ST(1), na);
  408.           RETVAL = rpcb_gettime( host, &timep );
  409.           }
  410.           OUTPUT:
  411.           timep
  412.           RETVAL
  413.  
  414. =head2 The PPCODE: Keyword
  415.  
  416. The PPCODE: keyword is an alternate form of the CODE: keyword and is used
  417. to tell the B<xsubpp> compiler that the programmer is supplying the code to
  418. control the argument stack for the XSUBs return values.  Occasionally one
  419. will want an XSUB to return a list of values rather than a single value.
  420. In these cases one must use PPCODE: and then explicitly push the list of
  421. values on the stack.  The PPCODE: and CODE:  keywords are not used
  422. together within the same XSUB.
  423.  
  424. The following XSUB will call the C rpcb_gettime() function
  425. and will return its two output values, timep and status, to
  426. Perl as a single list.
  427.  
  428.      void
  429.      rpcb_gettime(host)
  430.           char *  host
  431.           PPCODE:
  432.           {
  433.           time_t  timep;
  434.           bool_t  status;
  435.           status = rpcb_gettime( host, &timep );
  436.           EXTEND(sp, 2);
  437.           PUSHs(sv_2mortal(newSVnv(status)));
  438.           PUSHs(sv_2mortal(newSVnv(timep)));
  439.           }
  440.  
  441. Notice that the programmer must supply the C code necessary
  442. to have the real rpcb_gettime() function called and to have
  443. the return values properly placed on the argument stack.
  444.  
  445. The C<void> return type for this function tells the B<xsubpp> compiler that
  446. the RETVAL variable is not needed or used and that it should not be created.
  447. In most scenarios the void return type should be used with the PPCODE:
  448. directive.
  449.  
  450. The EXTEND() macro is used to make room on the argument
  451. stack for 2 return values.  The PPCODE: directive causes the
  452. B<xsubpp> compiler to create a stack pointer called C<sp>, and it
  453. is this pointer which is being used in the EXTEND() macro.
  454. The values are then pushed onto the stack with the PUSHs()
  455. macro.
  456.  
  457. Now the rpcb_gettime() function can be used from Perl with
  458. the following statement.
  459.  
  460.      ($status, $timep) = rpcb_gettime("localhost");
  461.  
  462. =head2 Returning Undef And Empty Lists
  463.  
  464. Occasionally the programmer will want to simply return
  465. C<undef> or an empty list if a function fails rather than a
  466. separate status value.  The rpcb_gettime() function offers
  467. just this situation.  If the function succeeds we would like
  468. to have it return the time and if it fails we would like to
  469. have undef returned.  In the following Perl code the value
  470. of $timep will either be undef or it will be a valid time.
  471.  
  472.      $timep = rpcb_gettime( "localhost" );
  473.  
  474. The following XSUB uses the C<void> return type to disable the generation of
  475. the RETVAL variable and uses a CODE: block to indicate to the compiler
  476. that the programmer has supplied all the necessary code.  The
  477. sv_newmortal() call will initialize the return value to undef, making that
  478. the default return value.
  479.  
  480.      void
  481.      rpcb_gettime(host)
  482.           char *  host
  483.           CODE:
  484.           {
  485.           time_t  timep;
  486.           bool_t x;
  487.           ST(0) = sv_newmortal();
  488.           if( rpcb_gettime( host, &timep ) )
  489.                sv_setnv( ST(0), (double)timep);
  490.           }
  491.  
  492. The next example demonstrates how one would place an explicit undef in the
  493. return value, should the need arise.
  494.  
  495.      void
  496.      rpcb_gettime(host)
  497.           char *  host
  498.           CODE:
  499.           {
  500.           time_t  timep;
  501.           bool_t x;
  502.           ST(0) = sv_newmortal();
  503.           if( rpcb_gettime( host, &timep ) ){
  504.                sv_setnv( ST(0), (double)timep);
  505.           }
  506.           else{
  507.                ST(0) = &sv_undef;
  508.           }
  509.           }
  510.  
  511. To return an empty list one must use a PPCODE: block and
  512. then not push return values on the stack.
  513.  
  514.      void
  515.      rpcb_gettime(host)
  516.           char *  host
  517.           PPCODE:
  518.           {
  519.           time_t  timep;
  520.           if( rpcb_gettime( host, &timep ) )
  521.                PUSHs(sv_2mortal(newSVnv(timep)));
  522.           else{
  523.           /* Nothing pushed on stack, so an empty */
  524.           /* list is implicitly returned. */
  525.           }
  526.           }
  527.  
  528. =head2 The CLEANUP: Keyword
  529.  
  530. This keyword can be used when an XSUB requires special cleanup procedures
  531. before it terminates.  When the CLEANUP:  keyword is used it must follow
  532. any CODE:, PPCODE:, or OUTPUT: blocks which are present in the XSUB.  The
  533. code specified for the cleanup block will be added as the last statements
  534. in the XSUB.
  535.  
  536. =head2 The BOOT: Keyword
  537.  
  538. The BOOT: keyword is used to add code to the extension's bootstrap
  539. function.  The bootstrap function is generated by the B<xsubpp> compiler and
  540. normally holds the statements necessary to register any XSUBs with Perl.
  541. With the BOOT: keyword the programmer can tell the compiler to add extra
  542. statements to the bootstrap function.
  543.  
  544. This keyword may be used any time after the first MODULE keyword and should
  545. appear on a line by itself.  The first blank line after the keyword will
  546. terminate the code block.
  547.  
  548.      BOOT:
  549.      # The following message will be printed when the
  550.      # bootstrap function executes.
  551.      printf("Hello from the bootstrap!\n");
  552.  
  553. =head2 Inserting Comments and C Preprocessor Directives
  554.  
  555. Comments and C preprocessor directives are allowed within
  556. CODE:, PPCODE:, BOOT:, and CLEANUP: blocks.  The compiler
  557. will pass the preprocessor directives through untouched and
  558. will remove the commented lines.  Comments can be added to
  559. XSUBs by placing a C<#> at the beginning of the line.  Care
  560. should be taken to avoid making the comment look like a C
  561. preprocessor directive, lest it be interpreted as such.
  562.  
  563. =head2 Using XS With C++
  564.  
  565. If a function is defined as a C++ method then it will assume
  566. its first argument is an object pointer.  The object pointer
  567. will be stored in a variable called THIS.  The object should
  568. have been created by C++ with the new() function and should
  569. be blessed by Perl with the sv_setptrobj() macro.  The
  570. blessing of the object by Perl can be handled by the
  571. T_PTROBJ typemap.
  572.  
  573. If the method is defined as static it will call the C++
  574. function using the class::method() syntax.  If the method is not static
  575. the function will be called using the THIS->method() syntax.
  576.  
  577. =head2 Perl Variables
  578.  
  579. The following demonstrates how the Perl variable $host can
  580. be accessed from an XSUB.  The function B<perl_get_sv()> is
  581. used to obtain a pointer to the variable, known as an B<SV>
  582. (Scalar Variable) internally.  The package name C<RPC> will be
  583. added to the name of the variable so perl_get_sv() will know
  584. in which package $host can be found.  If the package name is
  585. not supplied then perl_get_sv() will search package C<main> for
  586. the variable.  The macro B<SvPVX()> is then used to dereference
  587. the SV to obtain a C<char*> pointer to its contents.
  588.  
  589.      void
  590.      rpcb_gettime()
  591.           PPCODE:
  592.           {
  593.           char *host;
  594.           SV *hostsv;
  595.           time_t timep;
  596.  
  597.           hostsv = perl_get_sv( "RPC::host", FALSE );
  598.           if( hostsv != NULL ){
  599.                host = SvPVX( hostsv );
  600.                if( rpcb_gettime( host, &timep ) )
  601.                     PUSHs(sv_2mortal(newSVnv(timep)));
  602.           }
  603.           }
  604.  
  605. This Perl code can be used to call that XSUB.
  606.  
  607.      $RPC::host = "localhost";
  608.      $timep = rpcb_gettime();
  609.  
  610. In the above example the SV contained a C C<char*> but a Perl
  611. scalar variable may also contain numbers and references.  If
  612. the SV is expected to have a C C<int> then the macro B<SvIVX()>
  613. should be used to dereference the SV.  When the SV contains
  614. a C double then B<SvNVX()> should be used.
  615.  
  616. The macro B<SvRV()> can be used to dereference an SV when it is a Perl
  617. reference.  The result will be another SV which points to the actual Perl
  618. variable.  This can then be dereferenced with SvPVX(), SvNVX(), or
  619. SvIVX().  The following XSUB will use SvRV().
  620.  
  621.      void
  622.      rpcb_gettime()
  623.           PPCODE:
  624.           {
  625.           char *host;
  626.           SV *rv;
  627.           SV *hostsv;
  628.           time_t timep;
  629.  
  630.           rv = perl_get_sv( "RPC::host", FALSE );
  631.           if( rv != NULL ){
  632.                hostsv = SvRV( rv );
  633.                host = SvPVX( hostsv );
  634.                if( rpcb_gettime( host, &timep ) )
  635.                     PUSHs(sv_2mortal(newSVnv(timep)));
  636.           }
  637.           }
  638.  
  639. This Perl code will create a variable $RPC::host which is a
  640. reference to $MY::host.  The variable $MY::host contains the
  641. hostname which will be used.
  642.  
  643.      $MY::host = "localhost";
  644.      $RPC::host = \$MY::host;
  645.      $timep = rpcb_gettime();
  646.  
  647. The second argument to perl_get_sv() will normally be B<FALSE>
  648. as shown in the above examples.  An argument of B<TRUE> will
  649. cause variables to be created if they do not already exist.
  650. One should not use TRUE unless steps are taken to deal with
  651. a possibly empty SV.
  652.  
  653. XSUBs may use B<perl_get_av()>, B<perl_get_hv()>, and B<perl_get_cv()> to
  654. access Perl arrays, hashes, and code values.
  655.  
  656. =head2 Interface Strategy
  657.  
  658. When designing an interface between Perl and a C library a straight
  659. translation from C to XS is often sufficient.  The interface will often be
  660. very C-like and occasionally nonintuitive, especially when the C function
  661. modifies one of its parameters.  In cases where the programmer wishes to
  662. create a more Perl-like interface the following strategy may help to
  663. identify the more critical parts of the interface.
  664.  
  665. Identify the C functions which modify their parameters.  The XSUBs for
  666. these functions may be able to return lists to Perl, or may be
  667. candidates to return undef or an empty list in case of failure.
  668.  
  669. Identify which values are used by only the C and XSUB functions
  670. themselves.  If Perl does not need to access the contents of the value
  671. then it may not be necessary to provide a translation for that value
  672. from C to Perl.
  673.  
  674. Identify the pointers in the C function parameter lists and return
  675. values.  Some pointers can be handled in XS with the & unary operator on
  676. the variable name while others will require the use of the * operator on
  677. the type name.  In general it is easier to work with the & operator.
  678.  
  679. Identify the structures used by the C functions.  In many
  680. cases it may be helpful to use the T_PTROBJ typemap for
  681. these structures so they can be manipulated by Perl as
  682. blessed objects.
  683.  
  684. =head2 The Perl Module
  685.  
  686. The Perl module is the link between the extension library,
  687. which was generated from XS code, and the Perl interpreter.
  688. The module is used to tell Perl what the extension library
  689. contains.  The name and package of the module should match
  690. the name of the library.
  691.  
  692. The following is a Perl module for an extension containing
  693. some ONC+ RPC bind library functions.
  694.  
  695.      package RPC;
  696.  
  697.      require Exporter;
  698.      require DynaLoader;
  699.      @ISA = qw(Exporter DynaLoader);
  700.      @EXPORT = qw( rpcb_gettime rpcb_getmaps rpcb_getaddr
  701.                      rpcb_rmtcall rpcb_set rpcb_unset );
  702.  
  703.      bootstrap RPC;
  704.      1;
  705.  
  706. The RPC extension contains the functions found in the
  707. @EXPORT list.  By using the C<Exporter> module the RPC module
  708. can make these function names visible to the rest of the
  709. Perl program.  The C<DynaLoader> module will allow the RPC
  710. module to bootstrap the extension library.  To load this
  711. extension and make the functions available, the following
  712. Perl statement should be used.
  713.  
  714.      use RPC;
  715.  
  716. For more information about the DynaLoader consult its documentation in the
  717. ext/DynaLoader directory in the Perl source.
  718.  
  719. =head2 Perl Objects And C Structures
  720.  
  721. When dealing with C structures one should select either
  722. B<T_PTROBJ> or B<T_PTRREF> for the XS type.  Both types are
  723. designed to handle pointers to complex objects.  The
  724. T_PTRREF type will allow the Perl object to be unblessed
  725. while the T_PTROBJ type requires that the object be blessed.
  726. By using T_PTROBJ one can achieve a form of type-checking
  727. because the XSUB will attempt to verify that the Perl object
  728. is of the expected type.
  729.  
  730. The following XS code shows the getnetconfigent() function which is used
  731. with ONC TIRPC.  The getnetconfigent() function will return a pointer to a
  732. C structure and has the C prototype shown below.  The example will
  733. demonstrate how the C pointer will become a Perl reference.  Perl will
  734. consider this reference to be a pointer to a blessed object and will
  735. attempt to call a destructor for the object.  A destructor will be
  736. provided in the XS source to free the memory used by getnetconfigent().
  737. Destructors in XS can be created by specifying an XSUB function whose name
  738. ends with the word B<DESTROY>.  XS destructors can be used to free memory
  739. which may have been malloc'd by another XSUB.
  740.  
  741.      struct netconfig *getnetconfigent(const char *netid);
  742.  
  743. A C<typedef> will be created for C<struct netconfig>.  The Perl
  744. object will be blessed in a class matching the name of the C
  745. type, with the tag C<Ptr> appended, and the name should not
  746. have embedded spaces if it will be a Perl package name.  The
  747. destructor will be placed in a class corresponding to the
  748. class of the object and the PREFIX keyword will be used to
  749. trim the name to the word DESTROY as Perl will expect.
  750.  
  751.      typedef struct netconfig Netconfig;
  752.  
  753.      MODULE = RPC  PACKAGE = RPC
  754.  
  755.      Netconfig *
  756.      getnetconfigent(netid)
  757.           char *  netid
  758.  
  759.      MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_
  760.  
  761.      void
  762.      rpcb_DESTROY(netconf)
  763.           Netconfig *  netconf
  764.           CODE:
  765.           printf("Now in NetconfigPtr::DESTROY\n");
  766.           free( netconf );
  767.  
  768. This example requires the following typemap entry.  Consult the typemap
  769. section for more information about adding new typemaps for an extension.
  770.  
  771.      TYPEMAP
  772.      Netconfig *  T_PTROBJ
  773.  
  774. This example will be used with the following Perl statements.
  775.  
  776.      use RPC;
  777.      $netconf = getnetconfigent("udp");
  778.  
  779. When Perl destroys the object referenced by $netconf it will send the
  780. object to the supplied XSUB DESTROY function.  Perl cannot determine, and
  781. does not care, that this object is a C struct and not a Perl object.  In
  782. this sense, there is no difference between the object created by the
  783. getnetconfigent() XSUB and an object created by a normal Perl subroutine.
  784.  
  785. =head2 C Headers and Perl
  786.  
  787. The B<h2xs> compiler is designed to convert C header files in
  788. /usr/include into Perl extensions.  This compiler will
  789. create a directory under the C<ext> directory of the Perl
  790. source and will populate it with a Makefile, a Perl Module,
  791. an XS source file, and a MANIFEST file.
  792.  
  793. The following command will create an extension called C<Rusers>
  794. from the <rpcsvc/rusers.h> header.
  795.  
  796.      h2xs rpcsvc/rusers
  797.  
  798. When the Rusers extension has been compiled and installed
  799. Perl can use it to retrieve any C<#define> statements which
  800. were in the C header.
  801.  
  802.      use Rusers;
  803.      print "RPC program number for rusers service: ";
  804.      print &RUSERSPROG, "\n";
  805.  
  806. =head2 Creating A New Extension
  807.  
  808. The B<h2xs> compiler can generate template source files and
  809. Makefiles.  These templates offer a suitable starting point
  810. for most extensions.  The following example demonstrates how
  811. one might use B<h2xs> to create an extension containing the RPC
  812. functions in this document.
  813.  
  814. The extension will not use autoloaded functions and will not define
  815. constants, so the B<-A> option will be given to B<h2xs>.  When run from the
  816. Perl source directory, the B<h2xs> compiler will create the directory
  817. ext/RPC and will populate it with files called RPC.xs, RPC.pm, Makefile.PL,
  818. and MANIFEST.  The XS code for the RPC functions should be added to the
  819. RPC.xs file.  The @EXPORT list in RPC.pm should be updated to include the
  820. functions from RPC.xs.
  821.  
  822.      h2xs -An RPC
  823.  
  824. To compile the extension for dynamic loading the following
  825. command should be executed from the ext/RPC directory.
  826.  
  827.      make dynamic
  828.  
  829. If the extension will be statically linked into the Perl
  830. binary then the makefile (use C<makefile>, not C<Makefile>) in the
  831. Perl source directory should be edited to add C<ext/RPC/RPC.a>
  832. to the C<static_ext> variable.  Before making this change Perl
  833. should have already been built.  After the makefile has been
  834. updated the following command should be executed from the
  835. Perl source directory.
  836.  
  837.      make
  838.  
  839. Perl's B<Configure> script can also be used to add extensions.  The extension
  840. should be placed in the C<ext> directory under the Perl source before Perl
  841. has been built and prior to running Configure.  When Configure is run it
  842. will find the extension along with the other extensions in the C<ext>
  843. directory and will add it to the list of extensions to be built.  When make
  844. is run the extension will be built along with the other extensions.
  845.  
  846. Configure recognizes extensions if they have an XS source
  847. file which matches the name of the extension directory.  If
  848. the extension directory includes a MANIFEST file Configure
  849. will search that file for any B<.SH> files and extract them
  850. after it extracts all the other .SH files listed in the main
  851. MANIFEST.  The main Perl Makefile will then run B<make> in the
  852. extension's directory if it finds an XS file matching the
  853. name of the extension's directory.
  854.  
  855. =head2 The Typemap
  856.  
  857. The typemap is a collection of code fragments which are used by the B<xsubpp>
  858. compiler to map C function parameters and values to Perl values.  The
  859. typemap file may consist of three sections labeled C<TYPEMAP>, C<INPUT>, and
  860. C<OUTPUT>.  The INPUT section tells the compiler how to translate Perl values
  861. into variables of certain C types.  The OUTPUT section tells the compiler
  862. how to translate the values from certain C types into values Perl can
  863. understand.  The TYPEMAP section tells the compiler which of the INPUT and
  864. OUTPUT code fragments should be used to map a given C type to a Perl value.
  865. Each of the sections of the typemap must be preceded by one of the TYPEMAP,
  866. INPUT, or OUTPUT keywords.
  867.  
  868. The default typemap in the C<ext> directory of the Perl source contains many
  869. useful types which can be used by Perl extensions.  Some extensions define
  870. additional typemaps which they keep in their own directory.  These
  871. additional typemaps may reference INPUT and OUTPUT maps in the main
  872. typemap.  The B<xsubpp> compiler will allow the extension's own typemap to
  873. override any mappings which are in the default typemap.
  874.  
  875. Most extensions which require a custom typemap will need only the TYPEMAP
  876. section of the typemap file.  The custom typemap used in the
  877. getnetconfigent() example shown earlier demonstrates what may be the typical
  878. use of extension typemaps.  That typemap is used to equate a C structure
  879. with the T_PTROBJ typemap.  The typemap used by getnetconfigent() is shown
  880. here.  Note that the C type is separated from the XS type with a tab and
  881. that the C unary operator C<*> is considered to be a part of the C type name.
  882.  
  883.      TYPEMAP
  884.      Netconfig *<tab>T_PTROBJ
  885.  
  886. =head1 EXAMPLES
  887.  
  888. File C<RPC.xs>: Interface to some ONC+ RPC bind library functions.
  889.  
  890.      #include "EXTERN.h"
  891.      #include "perl.h"
  892.      #include "XSUB.h"
  893.  
  894.      #include <rpc/rpc.h>
  895.  
  896.      typedef struct netconfig Netconfig;
  897.  
  898.      MODULE = RPC  PACKAGE = RPC
  899.  
  900.      void
  901.      rpcb_gettime(host="localhost")
  902.           char *  host
  903.           CODE:
  904.           {
  905.           time_t  timep;
  906.           ST(0) = sv_newmortal();
  907.           if( rpcb_gettime( host, &timep ) )
  908.                sv_setnv( ST(0), (double)timep );
  909.           }
  910.  
  911.      Netconfig *
  912.      getnetconfigent(netid="udp")
  913.           char *  netid
  914.  
  915.      MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_
  916.  
  917.      void
  918.      rpcb_DESTROY(netconf)
  919.           Netconfig *  netconf
  920.           CODE:
  921.           printf("NetconfigPtr::DESTROY\n");
  922.           free( netconf );
  923.  
  924. File C<typemap>: Custom typemap for RPC.xs.
  925.  
  926.      TYPEMAP
  927.      Netconfig *  T_PTROBJ
  928.  
  929. File C<RPC.pm>: Perl module for the RPC extension.
  930.  
  931.      package RPC;
  932.  
  933.      require Exporter;
  934.      require DynaLoader;
  935.      @ISA = qw(Exporter DynaLoader);
  936.      @EXPORT = qw(rpcb_gettime getnetconfigent);
  937.  
  938.      bootstrap RPC;
  939.      1;
  940.  
  941. File C<rpctest.pl>: Perl test program for the RPC extension.
  942.  
  943.      use RPC;
  944.  
  945.      $netconf = getnetconfigent();
  946.      $a = rpcb_gettime();
  947.      print "time = $a\n";
  948.      print "netconf = $netconf\n";
  949.  
  950.      $netconf = getnetconfigent("tcp");
  951.      $a = rpcb_gettime("poplar");
  952.      print "time = $a\n";
  953.      print "netconf = $netconf\n";
  954.  
  955.  
  956. =head1 AUTHOR
  957.  
  958. Dean Roehrich F<E<lt>roehrich@cray.comE<gt>>
  959. May 3, 1995
  960.