home *** CD-ROM | disk | FTP | other *** search
/ RISC DISC 2 / RISC_DISC_2.iso / pd_share / utilities / cli / perl / !Perl / Manual / perlapi < prev    next >
Encoding:
Text File  |  1995-04-18  |  37.7 KB  |  920 lines

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