home *** CD-ROM | disk | FTP | other *** search
/ Chip 2000 May / Chip_2000-05_cd1.bin / zkuste / Perl / ActivePerl-5.6.0.613.msi / 䆊䌷䈹䈙䏵-䞅䞆䞀㡆䞃䄦䠥 / _64167e57516a1ed5dd984275df50246a < prev    next >
Text File  |  2000-03-23  |  73KB  |  1,541 lines

  1. <HTML>
  2. <HEAD>
  3. <TITLE>perlxs - XS language reference manual</TITLE>
  4. <LINK REL="stylesheet" HREF="../../Active.css" TYPE="text/css">
  5. <LINK REV="made" HREF="mailto:">
  6. </HEAD>
  7.  
  8. <BODY>
  9. <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
  10. <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
  11. <STRONG><P CLASS=block> perlxs - XS language reference manual</P></STRONG>
  12. </TD></TR>
  13. </TABLE>
  14.  
  15. <A NAME="__index__"></A>
  16. <!-- INDEX BEGIN -->
  17.  
  18. <UL>
  19.  
  20.     <LI><A HREF="#name">NAME</A></LI>
  21.     <LI><A HREF="#description">DESCRIPTION</A></LI>
  22.     <UL>
  23.  
  24.         <LI><A HREF="#introduction">Introduction</A></LI>
  25.         <LI><A HREF="#on the road">On The Road</A></LI>
  26.         <LI><A HREF="#the anatomy of an xsub">The Anatomy of an XSUB</A></LI>
  27.         <LI><A HREF="#the argument stack">The Argument Stack</A></LI>
  28.         <LI><A HREF="#the retval variable">The RETVAL Variable</A></LI>
  29.         <LI><A HREF="#the module keyword">The MODULE Keyword</A></LI>
  30.         <LI><A HREF="#the package keyword">The PACKAGE Keyword</A></LI>
  31.         <LI><A HREF="#the prefix keyword">The PREFIX Keyword</A></LI>
  32.         <LI><A HREF="#the output: keyword">The OUTPUT: Keyword</A></LI>
  33.         <LI><A HREF="#the code: keyword">The CODE: Keyword</A></LI>
  34.         <LI><A HREF="#the init: keyword">The INIT: Keyword</A></LI>
  35.         <LI><A HREF="#the no_init keyword">The NO_INIT Keyword</A></LI>
  36.         <LI><A HREF="#initializing function parameters">Initializing Function Parameters</A></LI>
  37.         <LI><A HREF="#default parameter values">Default Parameter Values</A></LI>
  38.         <LI><A HREF="#the preinit: keyword">The PREINIT: Keyword</A></LI>
  39.         <LI><A HREF="#the scope: keyword">The SCOPE: Keyword</A></LI>
  40.         <LI><A HREF="#the input: keyword">The INPUT: Keyword</A></LI>
  41.         <LI><A HREF="#variablelength parameter lists">Variable-length Parameter Lists</A></LI>
  42.         <LI><A HREF="#the c_args: keyword">The C_ARGS: Keyword</A></LI>
  43.         <LI><A HREF="#the ppcode: keyword">The PPCODE: Keyword</A></LI>
  44.         <LI><A HREF="#returning undef and empty lists">Returning Undef And Empty Lists</A></LI>
  45.         <LI><A HREF="#the require: keyword">The REQUIRE: Keyword</A></LI>
  46.         <LI><A HREF="#the cleanup: keyword">The CLEANUP: Keyword</A></LI>
  47.         <LI><A HREF="#the boot: keyword">The BOOT: Keyword</A></LI>
  48.         <LI><A HREF="#the versioncheck: keyword">The VERSIONCHECK: Keyword</A></LI>
  49.         <LI><A HREF="#the prototypes: keyword">The PROTOTYPES: Keyword</A></LI>
  50.         <LI><A HREF="#the prototype: keyword">The PROTOTYPE: Keyword</A></LI>
  51.         <LI><A HREF="#the alias: keyword">The ALIAS: Keyword</A></LI>
  52.         <LI><A HREF="#the interface: keyword">The INTERFACE: Keyword</A></LI>
  53.         <LI><A HREF="#the interface_macro: keyword">The INTERFACE_MACRO: Keyword</A></LI>
  54.         <LI><A HREF="#the include: keyword">The INCLUDE: Keyword</A></LI>
  55.         <LI><A HREF="#the case: keyword">The CASE: Keyword</A></LI>
  56.         <LI><A HREF="#the & unary operator">The & Unary Operator</A></LI>
  57.         <LI><A HREF="#inserting comments and c preprocessor directives">Inserting Comments and C Preprocessor Directives</A></LI>
  58.         <LI><A HREF="#using xs with c++">Using XS With C++</A></LI>
  59.         <LI><A HREF="#interface strategy">Interface Strategy</A></LI>
  60.         <LI><A HREF="#perl objects and c structures">Perl Objects And C Structures</A></LI>
  61.         <LI><A HREF="#the typemap">The Typemap</A></LI>
  62.     </UL>
  63.  
  64.     <LI><A HREF="#examples">EXAMPLES</A></LI>
  65.     <LI><A HREF="#xs version">XS VERSION</A></LI>
  66.     <LI><A HREF="#author">AUTHOR</A></LI>
  67. </UL>
  68. <!-- INDEX END -->
  69.  
  70. <HR>
  71. <P>
  72. <H1><A NAME="name">NAME</A></H1>
  73. <P>perlxs - XS language reference manual</P>
  74. <P>
  75. <HR>
  76. <H1><A NAME="description">DESCRIPTION</A></H1>
  77. <P>
  78. <H2><A NAME="introduction">Introduction</A></H2>
  79. <P>XS is an interface description file format used to create an extension
  80. interface between Perl and C code (or a C library) which one wishes
  81. to use with Perl.  The XS interface is combined with the library to
  82. create a new library which can then be either dynamically loaded
  83. or statically linked into perl.  The XS interface description is
  84. written in the XS language and is the core component of the Perl
  85. extension interface.</P>
  86. <P>An <STRONG>XSUB</STRONG> forms the basic unit of the XS interface.  After compilation
  87. by the <STRONG>xsubpp</STRONG> compiler, each XSUB amounts to a C function definition
  88. which will provide the glue between Perl calling conventions and C
  89. calling conventions.</P>
  90. <P>The glue code pulls the arguments from the Perl stack, converts these
  91. Perl values to the formats expected by a C function, call this C function,
  92. transfers the return values of the C function back to Perl.
  93. Return values here may be a conventional C return value or any C
  94. function arguments that may serve as output parameters.  These return
  95. values may be passed back to Perl either by putting them on the
  96. Perl stack, or by modifying the arguments supplied from the Perl side.</P>
  97. <P>The above is a somewhat simplified view of what really happens.  Since
  98. Perl allows more flexible calling conventions than C, XSUBs may do much
  99. more in practice, such as checking input parameters for validity,
  100. throwing exceptions (or returning undef/empty list) if the return value
  101. from the C function indicates failure, calling different C functions
  102. based on numbers and types of the arguments, providing an object-oriented
  103. interface, etc.</P>
  104. <P>Of course, one could write such glue code directly in C.  However, this
  105. would be a tedious task, especially if one needs to write glue for
  106. multiple C functions, and/or one is not familiar enough with the Perl
  107. stack discipline and other such arcana.  XS comes to the rescue here:
  108. instead of writing this glue C code in long-hand, one can write
  109. a more concise short-hand <EM>description</EM> of what should be done by
  110. the glue, and let the XS compiler <STRONG>xsubpp</STRONG> handle the rest.</P>
  111. <P>The XS language allows one to describe the mapping between how the C
  112. routine is used, and how the corresponding Perl routine is used.  It
  113. also allows creation of Perl routines which are directly translated to
  114. C code and which are not related to a pre-existing C function.  In cases
  115. when the C interface coincides with the Perl interface, the XSUB
  116. declaration is almost identical to a declaration of a C function (in K&R
  117. style).  In such circumstances, there is another tool called <CODE>h2xs</CODE>
  118. that is able to translate an entire C header file into a corresponding
  119. XS file that will provide glue to the functions/macros described in
  120. the header file.</P>
  121. <P>The XS compiler is called <STRONG>xsubpp</STRONG>.  This compiler creates
  122. the constructs necessary to let an XSUB manipulate Perl values, and
  123. creates the glue necessary to let Perl call the XSUB.  The compiler
  124. uses <STRONG>typemaps</STRONG> to determine how to map C function parameters
  125. and output values to Perl values and back.  The default typemap
  126. (which comes with Perl) handles many common C types.  A supplementary
  127. typemap may also be needed to handle any special structures and types
  128. for the library being linked.</P>
  129. <P>A file in XS format starts with a C language section which goes until the
  130. first <CODE>MODULE =</CODE> directive.  Other XS directives and XSUB definitions
  131. may follow this line.  The ``language'' used in this part of the file
  132. is usually referred to as the XS language.</P>
  133. <P>See <A HREF="../../lib/Pod/perlxstut.html">the perlxstut manpage</A> for a tutorial on the whole extension creation process.</P>
  134. <P>Note: For some extensions, Dave Beazley's SWIG system may provide a
  135. significantly more convenient mechanism for creating the extension glue
  136. code. See <A HREF="http://www.swig.org">http://www.swig.org</A> for more 
  137. information.</P>
  138. <P>
  139. <H2><A NAME="on the road">On The Road</A></H2>
  140. <P>Many of the examples which follow will concentrate on creating an interface
  141. between Perl and the ONC+ RPC bind library functions.  The <CODE>rpcb_gettime()</CODE>
  142. function is used to demonstrate many features of the XS language.  This
  143. function has two parameters; the first is an input parameter and the second
  144. is an output parameter.  The function also returns a status value.</P>
  145. <PRE>
  146.         bool_t rpcb_gettime(const char *host, time_t *timep);</PRE>
  147. <P>From C this function will be called with the following
  148. statements.</P>
  149. <PRE>
  150.      #include <rpc/rpc.h>
  151.      bool_t status;
  152.      time_t timep;
  153.      status = rpcb_gettime( "localhost", &timep );</PRE>
  154. <P>If an XSUB is created to offer a direct translation between this function
  155. and Perl, then this XSUB will be used from Perl with the following code.
  156. The $status and $timep variables will contain the output of the function.</P>
  157. <PRE>
  158.      use RPC;
  159.      $status = rpcb_gettime( "localhost", $timep );</PRE>
  160. <P>The following XS file shows an XS subroutine, or XSUB, which
  161. demonstrates one possible interface to the <CODE>rpcb_gettime()</CODE>
  162. function.  This XSUB represents a direct translation between
  163. C and Perl and so preserves the interface even from Perl.
  164. This XSUB will be invoked from Perl with the usage shown
  165. above.  Note that the first three #include statements, for
  166. <CODE>EXTERN.h</CODE>, <CODE>perl.h</CODE>, and <CODE>XSUB.h</CODE>, will always be present at the
  167. beginning of an XS file.  This approach and others will be
  168. expanded later in this document.</P>
  169. <PRE>
  170.      #include "EXTERN.h"
  171.      #include "perl.h"
  172.      #include "XSUB.h"
  173.      #include <rpc/rpc.h></PRE>
  174. <PRE>
  175.      MODULE = RPC  PACKAGE = RPC</PRE>
  176. <PRE>
  177.      bool_t
  178.      rpcb_gettime(host,timep)
  179.           char *host
  180.           time_t &timep
  181.         OUTPUT:
  182.           timep</PRE>
  183. <P>Any extension to Perl, including those containing XSUBs,
  184. should have a Perl module to serve as the bootstrap which
  185. pulls the extension into Perl.  This module will export the
  186. extension's functions and variables to the Perl program and
  187. will cause the extension's XSUBs to be linked into Perl.
  188. The following module will be used for most of the examples
  189. in this document and should be used from Perl with the <A HREF="../../lib/Pod/perlfunc.html#item_use"><CODE>use</CODE></A>
  190. command as shown earlier.  Perl modules are explained in
  191. more detail later in this document.</P>
  192. <PRE>
  193.      package RPC;</PRE>
  194. <PRE>
  195.      require Exporter;
  196.      require DynaLoader;
  197.      @ISA = qw(Exporter DynaLoader);
  198.      @EXPORT = qw( rpcb_gettime );</PRE>
  199. <PRE>
  200.      bootstrap RPC;
  201.      1;</PRE>
  202. <P>Throughout this document a variety of interfaces to the <CODE>rpcb_gettime()</CODE>
  203. XSUB will be explored.  The XSUBs will take their parameters in different
  204. orders or will take different numbers of parameters.  In each case the
  205. XSUB is an abstraction between Perl and the real C <CODE>rpcb_gettime()</CODE>
  206. function, and the XSUB must always ensure that the real <CODE>rpcb_gettime()</CODE>
  207. function is called with the correct parameters.  This abstraction will
  208. allow the programmer to create a more Perl-like interface to the C
  209. function.</P>
  210. <P>
  211. <H2><A NAME="the anatomy of an xsub">The Anatomy of an XSUB</A></H2>
  212. <P>The simplest XSUBs consist of 3 parts: a description of the return
  213. value, the name of the XSUB routine and the names of its arguments,
  214. and a description of types or formats of the arguments.</P>
  215. <P>The following XSUB allows a Perl program to access a C library function
  216. called sin().  The XSUB will imitate the C function which takes a single
  217. argument and returns a single value.</P>
  218. <PRE>
  219.      double
  220.      sin(x)
  221.        double x</PRE>
  222. <P>When using parameters with C pointer types, as in</P>
  223. <PRE>
  224.      double string_to_double(char *s);</PRE>
  225. <P>there may be two ways to describe this argument to <STRONG>xsubpp</STRONG>:</P>
  226. <PRE>
  227.      char *  s
  228.      char    &s</PRE>
  229. <P>Both these XS declarations correspond to the <CODE>char*</CODE> C type, but they have
  230. different semantics.  It is convenient to think that the indirection operator
  231. <CODE>*</CODE> should be considered as a part of the type and the address operator <CODE>&</CODE>
  232. should be considered part of the variable.  See <A HREF="#the typemap">The Typemap</A> and
  233. <A HREF="#the & unary operator">The & Unary Operator</A> for more info about handling qualifiers and unary
  234. operators in C types.</P>
  235. <P>The function name and the return type must be placed on
  236. separate lines and should be flush left-adjusted.</P>
  237. <PRE>
  238.   INCORRECT                        CORRECT</PRE>
  239. <PRE>
  240.   double sin(x)                    double
  241.     double x                       sin(x)
  242.                                      double x</PRE>
  243. <P>The function body may be indented or left-adjusted.  The following example
  244. shows a function with its body left-adjusted.  Most examples in this
  245. document will indent the body for better readability.</P>
  246. <PRE>
  247.   CORRECT</PRE>
  248. <PRE>
  249.   double
  250.   sin(x)
  251.   double x</PRE>
  252. <P>More complicated XSUBs may contain many other sections.  Each section of
  253. an XSUB starts with the corresponding keyword, such as INIT: or CLEANUP:.
  254. However, the first two lines of an XSUB always contain the same data:
  255. descriptions of the return type and the names of the function and its
  256. parameters.  Whatever immediately follows these is considered to be
  257. an INPUT: section unless explicitly marked with another keyword.
  258. (See <A HREF="#the input: keyword">The INPUT: Keyword</A>.)</P>
  259. <P>An XSUB section continues until another section-start keyword is found.</P>
  260. <P>
  261. <H2><A NAME="the argument stack">The Argument Stack</A></H2>
  262. <P>The Perl argument stack is used to store the values which are
  263. sent as parameters to the XSUB and to store the XSUB's
  264. return value(s).  In reality all Perl functions (including non-XSUB
  265. ones) keep their values on this stack all the same time, each limited
  266. to its own range of positions on the stack.  In this document the
  267. first position on that stack which belongs to the active
  268. function will be referred to as position 0 for that function.</P>
  269. <P>XSUBs refer to their stack arguments with the macro <STRONG>ST(x)</STRONG>, where <EM>x</EM>
  270. refers to a position in this XSUB's part of the stack.  Position 0 for that
  271. function would be known to the XSUB as ST(0).  The XSUB's incoming
  272. parameters and outgoing return values always begin at ST(0).  For many
  273. simple cases the <STRONG>xsubpp</STRONG> compiler will generate the code necessary to
  274. handle the argument stack by embedding code fragments found in the
  275. typemaps.  In more complex cases the programmer must supply the code.</P>
  276. <P>
  277. <H2><A NAME="the retval variable">The RETVAL Variable</A></H2>
  278. <P>The RETVAL variable is a special C variable that is declared automatically
  279. for you.  The C type of RETVAL matches the return type of the C library
  280. function.  The <STRONG>xsubpp</STRONG> compiler will declare this variable in each XSUB
  281. with non-<A HREF="../../lib/Pod/perlguts.html#item_void"><CODE>void</CODE></A> return type.  By default the generated C function
  282. will use RETVAL to hold the return value of the C library function being
  283. called.  In simple cases the value of RETVAL will be placed in <CODE>ST(0)</CODE> of
  284. the argument stack where it can be received by Perl as the return value
  285. of the XSUB.</P>
  286. <P>If the XSUB has a return type of <A HREF="../../lib/Pod/perlguts.html#item_void"><CODE>void</CODE></A> then the compiler will
  287. not declare a RETVAL variable for that function.  When using
  288. a PPCODE: section no manipulation of the RETVAL variable is required, the
  289. section may use direct stack manipulation to place output values on the stack.</P>
  290. <P>If PPCODE: directive is not used, <A HREF="../../lib/Pod/perlguts.html#item_void"><CODE>void</CODE></A> return value should be used
  291. only for subroutines which do not return a value, <EM>even if</EM> CODE:
  292. directive is used which sets <CODE>ST(0)</CODE> explicitly.</P>
  293. <P>Older versions of this document recommended to use <A HREF="../../lib/Pod/perlguts.html#item_void"><CODE>void</CODE></A> return
  294. value in such cases. It was discovered that this could lead to
  295. segfaults in cases when XSUB was <EM>truly</EM> <A HREF="../../lib/Pod/perlguts.html#item_void"><CODE>void</CODE></A>. This practice is
  296. now deprecated, and may be not supported at some future version. Use
  297. the return value <CODE>SV *</CODE> in such cases. (Currently <CODE>xsubpp</CODE> contains
  298. some heuristic code which tries to disambiguate between ``truly-void''
  299. and ``old-practice-declared-as-void'' functions. Hence your code is at
  300. mercy of this heuristics unless you use <CODE>SV *</CODE> as return value.)</P>
  301. <P>
  302. <H2><A NAME="the module keyword">The MODULE Keyword</A></H2>
  303. <P>The MODULE keyword is used to start the XS code and to
  304. specify the package of the functions which are being
  305. defined.  All text preceding the first MODULE keyword is
  306. considered C code and is passed through to the output
  307. untouched.  Every XS module will have a bootstrap function
  308. which is used to hook the XSUBs into Perl.  The package name
  309. of this bootstrap function will match the value of the last
  310. MODULE statement in the XS source files.  The value of
  311. MODULE should always remain constant within the same XS
  312. file, though this is not required.</P>
  313. <P>The following example will start the XS code and will place
  314. all functions in a package named RPC.</P>
  315. <PRE>
  316.      MODULE = RPC</PRE>
  317. <P>
  318. <H2><A NAME="the package keyword">The PACKAGE Keyword</A></H2>
  319. <P>When functions within an XS source file must be separated into packages
  320. the PACKAGE keyword should be used.  This keyword is used with the MODULE
  321. keyword and must follow immediately after it when used.</P>
  322. <PRE>
  323.      MODULE = RPC  PACKAGE = RPC</PRE>
  324. <PRE>
  325.      [ XS code in package RPC ]</PRE>
  326. <PRE>
  327.      MODULE = RPC  PACKAGE = RPCB</PRE>
  328. <PRE>
  329.      [ XS code in package RPCB ]</PRE>
  330. <PRE>
  331.      MODULE = RPC  PACKAGE = RPC</PRE>
  332. <PRE>
  333.      [ XS code in package RPC ]</PRE>
  334. <P>Although this keyword is optional and in some cases provides redundant
  335. information it should always be used.  This keyword will ensure that the
  336. XSUBs appear in the desired package.</P>
  337. <P>
  338. <H2><A NAME="the prefix keyword">The PREFIX Keyword</A></H2>
  339. <P>The PREFIX keyword designates prefixes which should be
  340. removed from the Perl function names.  If the C function is
  341. <CODE>rpcb_gettime()</CODE> and the PREFIX value is <CODE>rpcb_</CODE> then Perl will
  342. see this function as <CODE>gettime()</CODE>.</P>
  343. <P>This keyword should follow the PACKAGE keyword when used.
  344. If PACKAGE is not used then PREFIX should follow the MODULE
  345. keyword.</P>
  346. <PRE>
  347.      MODULE = RPC  PREFIX = rpc_</PRE>
  348. <PRE>
  349.      MODULE = RPC  PACKAGE = RPCB  PREFIX = rpcb_</PRE>
  350. <P>
  351. <H2><A NAME="the output: keyword">The OUTPUT: Keyword</A></H2>
  352. <P>The OUTPUT: keyword indicates that certain function parameters should be
  353. updated (new values made visible to Perl) when the XSUB terminates or that
  354. certain values should be returned to the calling Perl function.  For
  355. simple functions which have no CODE: or PPCODE: section,
  356. such as the <A HREF="../../lib/Pod/perlfunc.html#item_sin"><CODE>sin()</CODE></A> function above, the RETVAL variable is
  357. automatically designated as an output value.  For more complex functions
  358. the <STRONG>xsubpp</STRONG> compiler will need help to determine which variables are output
  359. variables.</P>
  360. <P>This keyword will normally be used to complement the CODE:  keyword.
  361. The RETVAL variable is not recognized as an output variable when the
  362. CODE: keyword is present.  The OUTPUT:  keyword is used in this
  363. situation to tell the compiler that RETVAL really is an output
  364. variable.</P>
  365. <P>The OUTPUT: keyword can also be used to indicate that function parameters
  366. are output variables.  This may be necessary when a parameter has been
  367. modified within the function and the programmer would like the update to
  368. be seen by Perl.</P>
  369. <PRE>
  370.      bool_t
  371.      rpcb_gettime(host,timep)
  372.           char *host
  373.           time_t &timep
  374.         OUTPUT:
  375.           timep</PRE>
  376. <P>The OUTPUT: keyword will also allow an output parameter to
  377. be mapped to a matching piece of code rather than to a
  378. typemap.</P>
  379. <PRE>
  380.      bool_t
  381.      rpcb_gettime(host,timep)
  382.           char *host
  383.           time_t &timep
  384.         OUTPUT:
  385.           timep sv_setnv(ST(1), (double)timep);</PRE>
  386. <P><STRONG>xsubpp</STRONG> emits an automatic <CODE>SvSETMAGIC()</CODE> for all parameters in the
  387. OUTPUT section of the XSUB, except RETVAL.  This is the usually desired
  388. behavior, as it takes care of properly invoking 'set' magic on output
  389. parameters (needed for hash or array element parameters that must be
  390. created if they didn't exist).  If for some reason, this behavior is
  391. not desired, the OUTPUT section may contain a <CODE>SETMAGIC: DISABLE</CODE> line
  392. to disable it for the remainder of the parameters in the OUTPUT section.
  393. Likewise,  <CODE>SETMAGIC: ENABLE</CODE> can be used to reenable it for the
  394. remainder of the OUTPUT section.  See <A HREF="../../lib/Pod/perlguts.html">the perlguts manpage</A> for more details
  395. about 'set' magic.</P>
  396. <P>
  397. <H2><A NAME="the code: keyword">The CODE: Keyword</A></H2>
  398. <P>This keyword is used in more complicated XSUBs which require
  399. special handling for the C function.  The RETVAL variable is
  400. still declared, but it will not be returned unless it is specified
  401. in the OUTPUT: section.</P>
  402. <P>The following XSUB is for a C function which requires special handling of
  403. its parameters.  The Perl usage is given first.</P>
  404. <PRE>
  405.      $status = rpcb_gettime( "localhost", $timep );</PRE>
  406. <P>The XSUB follows.</P>
  407. <PRE>
  408.      bool_t
  409.      rpcb_gettime(host,timep)
  410.           char *host
  411.           time_t timep
  412.         CODE:
  413.                RETVAL = rpcb_gettime( host, &timep );
  414.         OUTPUT:
  415.           timep
  416.           RETVAL</PRE>
  417. <P>
  418. <H2><A NAME="the init: keyword">The INIT: Keyword</A></H2>
  419. <P>The INIT: keyword allows initialization to be inserted into the XSUB before
  420. the compiler generates the call to the C function.  Unlike the CODE: keyword
  421. above, this keyword does not affect the way the compiler handles RETVAL.</P>
  422. <PRE>
  423.     bool_t
  424.     rpcb_gettime(host,timep)
  425.           char *host
  426.           time_t &timep
  427.         INIT:
  428.           printf("# Host is %s\n", host );
  429.         OUTPUT:
  430.           timep</PRE>
  431. <P>Another use for the INIT: section is to check for preconditions before
  432. making a call to the C function:</P>
  433. <PRE>
  434.     long long
  435.     lldiv(a,b)
  436.         long long a
  437.         long long b
  438.       INIT:
  439.         if (a == 0 && b == 0)
  440.             XSRETURN_UNDEF;
  441.         if (b == 0)
  442.             croak("lldiv: cannot divide by 0");</PRE>
  443. <P>
  444. <H2><A NAME="the no_init keyword">The NO_INIT Keyword</A></H2>
  445. <P>The NO_INIT keyword is used to indicate that a function
  446. parameter is being used only as an output value.  The <STRONG>xsubpp</STRONG>
  447. compiler will normally generate code to read the values of
  448. all function parameters from the argument stack and assign
  449. them to C variables upon entry to the function.  NO_INIT
  450. will tell the compiler that some parameters will be used for
  451. output rather than for input and that they will be handled
  452. before the function terminates.</P>
  453. <P>The following example shows a variation of the <CODE>rpcb_gettime()</CODE> function.
  454. This function uses the timep variable only as an output variable and does
  455. not care about its initial contents.</P>
  456. <PRE>
  457.      bool_t
  458.      rpcb_gettime(host,timep)
  459.           char *host
  460.           time_t &timep = NO_INIT
  461.         OUTPUT:
  462.           timep</PRE>
  463. <P>
  464. <H2><A NAME="initializing function parameters">Initializing Function Parameters</A></H2>
  465. <P>C function parameters are normally initialized with their values from
  466. the argument stack (which in turn contains the parameters that were
  467. passed to the XSUB from Perl).  The typemaps contain the
  468. code segments which are used to translate the Perl values to
  469. the C parameters.  The programmer, however, is allowed to
  470. override the typemaps and supply alternate (or additional)
  471. initialization code.  Initialization code starts with the first
  472. <CODE>=</CODE>, <CODE>;</CODE> or <CODE>+</CODE> on a line in the INPUT: section.  The only
  473. exception happens if this <CODE>;</CODE> terminates the line, then this <CODE>;</CODE>
  474. is quietly ignored.</P>
  475. <P>The following code demonstrates how to supply initialization code for
  476. function parameters.  The initialization code is eval'd within double
  477. quotes by the compiler before it is added to the output so anything
  478. which should be interpreted literally [mainly <CODE>$</CODE>, <CODE>@</CODE>, or <CODE>\\</CODE>]
  479. must be protected with backslashes.  The variables $var, $arg,
  480. and $type can be used as in typemaps.</P>
  481. <PRE>
  482.      bool_t
  483.      rpcb_gettime(host,timep)
  484.           char *host = (char *)SvPV($arg,PL_na);
  485.           time_t &timep = 0;
  486.         OUTPUT:
  487.           timep</PRE>
  488. <P>This should not be used to supply default values for parameters.  One
  489. would normally use this when a function parameter must be processed by
  490. another library function before it can be used.  Default parameters are
  491. covered in the next section.</P>
  492. <P>If the initialization begins with <CODE>=</CODE>, then it is output in
  493. the declaration for the input variable, replacing the initialization
  494. supplied by the typemap.  If the initialization
  495. begins with <CODE>;</CODE> or <CODE>+</CODE>, then it is performed after
  496. all of the input variables have been declared.  In the <CODE>;</CODE>
  497. case the initialization normally supplied by the typemap is not performed.
  498. For the <CODE>+</CODE> case, the declaration for the variable will include the
  499. initialization from the typemap.  A global
  500. variable, <CODE>%v</CODE>, is available for the truly rare case where
  501. information from one initialization is needed in another
  502. initialization.</P>
  503. <P>Here's a truly obscure example:</P>
  504. <PRE>
  505.      bool_t
  506.      rpcb_gettime(host,timep)
  507.           time_t &timep ; /* \$v{timep}=@{[$v{timep}=$arg]} */
  508.           char *host + SvOK($v{timep}) ? SvPV($arg,PL_na) : NULL;
  509.         OUTPUT:
  510.           timep</PRE>
  511. <P>The construct <CODE>\$v{timep}=@{[$v{timep}=$arg]}</CODE> used in the above
  512. example has a two-fold purpose: first, when this line is processed by
  513. <STRONG>xsubpp</STRONG>, the Perl snippet <CODE>$v{timep}=$arg</CODE> is evaluated.  Second,
  514. the text of the evaluated snippet is output into the generated C file
  515. (inside a C comment)!  During the processing of <CODE>char *host</CODE> line,
  516. $arg will evaluate to <CODE>ST(0)</CODE>, and <CODE>$v{timep}</CODE> will evaluate to
  517. <CODE>ST(1)</CODE>.</P>
  518. <P>
  519. <H2><A NAME="default parameter values">Default Parameter Values</A></H2>
  520. <P>Default values for XSUB arguments can be specified by placing an
  521. assignment statement in the parameter list.  The default value may
  522. be a number, a string or the special string <CODE>NO_INIT</CODE>.  Defaults should
  523. always be used on the right-most parameters only.</P>
  524. <P>To allow the XSUB for <CODE>rpcb_gettime()</CODE> to have a default host
  525. value the parameters to the XSUB could be rearranged.  The
  526. XSUB will then call the real <CODE>rpcb_gettime()</CODE> function with
  527. the parameters in the correct order.  This XSUB can be called
  528. from Perl with either of the following statements:</P>
  529. <PRE>
  530.      $status = rpcb_gettime( $timep, $host );</PRE>
  531. <PRE>
  532.      $status = rpcb_gettime( $timep );</PRE>
  533. <P>The XSUB will look like the code  which  follows.   A  CODE:
  534. block  is used to call the real <CODE>rpcb_gettime()</CODE> function with
  535. the parameters in the correct order for that function.</P>
  536. <PRE>
  537.      bool_t
  538.      rpcb_gettime(timep,host="localhost")
  539.           char *host
  540.           time_t timep = NO_INIT
  541.         CODE:
  542.                RETVAL = rpcb_gettime( host, &timep );
  543.         OUTPUT:
  544.           timep
  545.           RETVAL</PRE>
  546. <P>
  547. <H2><A NAME="the preinit: keyword">The PREINIT: Keyword</A></H2>
  548. <P>The PREINIT: keyword allows extra variables to be declared immediately
  549. before or after the declartions of the parameters from the INPUT: section
  550. are emitted.</P>
  551. <P>If a variable is declared inside a CODE: section it will follow any typemap
  552. code that is emitted for the input parameters.  This may result in the
  553. declaration ending up after C code, which is C syntax error.  Similar
  554. errors may happen with an explicit <CODE>;</CODE>-type or <CODE>+</CODE>-type initialization of
  555. parameters is used (see <A HREF="#initializing function parameters">Initializing Function Parameters</A>).  Declaring
  556. these variables in an INIT: section will not help.</P>
  557. <P>In such cases, to force an additional variable to be declared together
  558. with declarations of other variables, place the declaration into a
  559. PREINIT: section.  The PREINIT: keyword may be used one or more times
  560. within an XSUB.</P>
  561. <P>The following examples are equivalent, but if the code is using complex
  562. typemaps then the first example is safer.</P>
  563. <PRE>
  564.      bool_t
  565.      rpcb_gettime(timep)
  566.           time_t timep = NO_INIT
  567.         PREINIT:
  568.           char *host = "localhost";
  569.         CODE:
  570.           RETVAL = rpcb_gettime( host, &timep );
  571.         OUTPUT:
  572.           timep
  573.           RETVAL</PRE>
  574. <P>For this particular case an INIT: keyword would generate the
  575. same C code as the PREINIT: keyword.  Another correct, but error-prone example:</P>
  576. <PRE>
  577.      bool_t
  578.      rpcb_gettime(timep)
  579.           time_t timep = NO_INIT
  580.         CODE:
  581.           char *host = "localhost";
  582.           RETVAL = rpcb_gettime( host, &timep );
  583.         OUTPUT:
  584.           timep
  585.           RETVAL</PRE>
  586. <P>Another way to declare <CODE>host</CODE> is to use a C block in the CODE: section:</P>
  587. <PRE>
  588.      bool_t
  589.      rpcb_gettime(timep)
  590.           time_t timep = NO_INIT
  591.         CODE:
  592.           {
  593.             char *host = "localhost";
  594.             RETVAL = rpcb_gettime( host, &timep );
  595.           }
  596.         OUTPUT:
  597.           timep
  598.           RETVAL</PRE>
  599. <P>The ability to put additional declarations before the typemap entries are
  600. processed is very handy in the cases when typemap conversions manipulate
  601. some global state:</P>
  602. <PRE>
  603.     MyObject
  604.     mutate(o)
  605.         PREINIT:
  606.             MyState st = global_state;
  607.         INPUT:
  608.             MyObject o;
  609.         CLEANUP:
  610.             reset_to(global_state, st);</PRE>
  611. <P>Here we suppose that conversion to <CODE>MyObject</CODE> in the INPUT: section and from
  612. MyObject when processing RETVAL will modify a global variable <CODE>global_state</CODE>.
  613. After these conversions are performed, we restore the old value of
  614. <CODE>global_state</CODE> (to avoid memory leaks, for example).</P>
  615. <P>There is another way to trade clarity for compactness: INPUT sections allow
  616. declaration of C variables which do not appear in the parameter list of
  617. a subroutine.  Thus the above code for <CODE>mutate()</CODE> can be rewritten as</P>
  618. <PRE>
  619.     MyObject
  620.     mutate(o)
  621.           MyState st = global_state;
  622.           MyObject o;
  623.         CLEANUP:
  624.           reset_to(global_state, st);</PRE>
  625. <P>and the code for <CODE>rpcb_gettime()</CODE> can be rewritten as</P>
  626. <PRE>
  627.      bool_t
  628.      rpcb_gettime(timep)
  629.           time_t timep = NO_INIT
  630.           char *host = "localhost";
  631.         C_ARGS:
  632.           host, &timep
  633.         OUTPUT:
  634.           timep
  635.           RETVAL</PRE>
  636. <P>
  637. <H2><A NAME="the scope: keyword">The SCOPE: Keyword</A></H2>
  638. <P>The SCOPE: keyword allows scoping to be enabled for a particular XSUB. If
  639. enabled, the XSUB will invoke ENTER and LEAVE automatically.</P>
  640. <P>To support potentially complex type mappings, if a typemap entry used
  641. by an XSUB contains a comment like <CODE>/*scope*/</CODE> then scoping will
  642. be automatically enabled for that XSUB.</P>
  643. <P>To enable scoping:</P>
  644. <PRE>
  645.     SCOPE: ENABLE</PRE>
  646. <P>To disable scoping:</P>
  647. <PRE>
  648.     SCOPE: DISABLE</PRE>
  649. <P>
  650. <H2><A NAME="the input: keyword">The INPUT: Keyword</A></H2>
  651. <P>The XSUB's parameters are usually evaluated immediately after entering the
  652. XSUB.  The INPUT: keyword can be used to force those parameters to be
  653. evaluated a little later.  The INPUT: keyword can be used multiple times
  654. within an XSUB and can be used to list one or more input variables.  This
  655. keyword is used with the PREINIT: keyword.</P>
  656. <P>The following example shows how the input parameter <CODE>timep</CODE> can be
  657. evaluated late, after a PREINIT.</P>
  658. <PRE>
  659.     bool_t
  660.     rpcb_gettime(host,timep)
  661.           char *host
  662.         PREINIT:
  663.           time_t tt;
  664.         INPUT:
  665.           time_t timep
  666.         CODE:
  667.                RETVAL = rpcb_gettime( host, &tt );
  668.                timep = tt;
  669.         OUTPUT:
  670.           timep
  671.           RETVAL</PRE>
  672. <P>The next example shows each input parameter evaluated late.</P>
  673. <PRE>
  674.     bool_t
  675.     rpcb_gettime(host,timep)
  676.         PREINIT:
  677.           time_t tt;
  678.         INPUT:
  679.           char *host
  680.         PREINIT:
  681.           char *h;
  682.         INPUT:
  683.           time_t timep
  684.         CODE:
  685.                h = host;
  686.                RETVAL = rpcb_gettime( h, &tt );
  687.                timep = tt;
  688.         OUTPUT:
  689.           timep
  690.           RETVAL</PRE>
  691. <P>Since INPUT sections allow declaration of C variables which do not appear
  692. in the parameter list of a subroutine, this may be shortened to:</P>
  693. <PRE>
  694.     bool_t
  695.     rpcb_gettime(host,timep)
  696.           time_t tt;
  697.           char *host;
  698.           char *h = host;
  699.           time_t timep;
  700.         CODE:
  701.           RETVAL = rpcb_gettime( h, &tt );
  702.           timep = tt;
  703.         OUTPUT:
  704.           timep
  705.           RETVAL</PRE>
  706. <P>(We used our knowledge that input conversion for <CODE>char *</CODE> is a ``simple'' one,
  707. thus <CODE>host</CODE> is initialized on the declaration line, and our assignment
  708. <CODE>h = host</CODE> is not performed too early.  Otherwise one would need to have the
  709. assignment <CODE>h = host</CODE> in a CODE: or INIT: section.)</P>
  710. <P>
  711. <H2><A NAME="variablelength parameter lists">Variable-length Parameter Lists</A></H2>
  712. <P>XSUBs can have variable-length parameter lists by specifying an ellipsis
  713. <CODE>(...)</CODE> in the parameter list.  This use of the ellipsis is similar to that
  714. found in ANSI C.  The programmer is able to determine the number of
  715. arguments passed to the XSUB by examining the <CODE>items</CODE> variable which the
  716. <STRONG>xsubpp</STRONG> compiler supplies for all XSUBs.  By using this mechanism one can
  717. create an XSUB which accepts a list of parameters of unknown length.</P>
  718. <P>The <EM>host</EM> parameter for the <CODE>rpcb_gettime()</CODE> XSUB can be
  719. optional so the ellipsis can be used to indicate that the
  720. XSUB will take a variable number of parameters.  Perl should
  721. be able to call this XSUB with either of the following statements.</P>
  722. <PRE>
  723.      $status = rpcb_gettime( $timep, $host );</PRE>
  724. <PRE>
  725.      $status = rpcb_gettime( $timep );</PRE>
  726. <P>The XS code, with ellipsis, follows.</P>
  727. <PRE>
  728.      bool_t
  729.      rpcb_gettime(timep, ...)
  730.           time_t timep = NO_INIT
  731.         PREINIT:
  732.           char *host = "localhost";
  733.           STRLEN n_a;
  734.         CODE:
  735.           if( items > 1 )
  736.                host = (char *)SvPV(ST(1), n_a);
  737.           RETVAL = rpcb_gettime( host, &timep );
  738.         OUTPUT:
  739.           timep
  740.           RETVAL</PRE>
  741. <P>
  742. <H2><A NAME="the c_args: keyword">The C_ARGS: Keyword</A></H2>
  743. <P>The C_ARGS: keyword allows creating of XSUBS which have different
  744. calling sequence from Perl than from C, without a need to write
  745. CODE: or PPCODE: section.  The contents of the C_ARGS: paragraph is
  746. put as the argument to the called C function without any change.</P>
  747. <P>For example, suppose that a C function is declared as</P>
  748. <PRE>
  749.     symbolic nth_derivative(int n, symbolic function, int flags);</PRE>
  750. <P>and that the default flags are kept in a global C variable
  751. <CODE>default_flags</CODE>.  Suppose that you want to create an interface which
  752. is called as</P>
  753. <PRE>
  754.     $second_deriv = $function->nth_derivative(2);</PRE>
  755. <P>To do this, declare the XSUB as</P>
  756. <PRE>
  757.     symbolic
  758.     nth_derivative(function, n)
  759.         symbolic        function
  760.         int             n
  761.       C_ARGS:
  762.         n, function, default_flags</PRE>
  763. <P>
  764. <H2><A NAME="the ppcode: keyword">The PPCODE: Keyword</A></H2>
  765. <P>The PPCODE: keyword is an alternate form of the CODE: keyword and is used
  766. to tell the <STRONG>xsubpp</STRONG> compiler that the programmer is supplying the code to
  767. control the argument stack for the XSUBs return values.  Occasionally one
  768. will want an XSUB to return a list of values rather than a single value.
  769. In these cases one must use PPCODE: and then explicitly push the list of
  770. values on the stack.  The PPCODE: and CODE:  keywords should not be used
  771. together within the same XSUB.</P>
  772. <P>The actual difference between PPCODE: and CODE: sections is in the
  773. initialization of <CODE>SP</CODE> macro (which stands for the <EM>current</EM> Perl
  774. stack pointer), and in the handling of data on the stack when returning
  775. from an XSUB.  In CODE: sections SP preserves the value which was on
  776. entry to the XSUB: SP is on the function pointer (which follows the
  777. last parameter).  In PPCODE: sections SP is moved backward to the
  778. beginning of the parameter list, which allows <CODE>PUSH*()</CODE> macros
  779. to place output values in the place Perl expects them to be when
  780. the XSUB returns back to Perl.</P>
  781. <P>The generated trailer for a CODE: section ensures that the number of return
  782. values Perl will see is either 0 or 1 (depending on the <A HREF="../../lib/Pod/perlguts.html#item_void"><CODE>void</CODE></A>ness of the
  783. return value of the C function, and heuristics mentioned in
  784. <A HREF="#the retval variable">The RETVAL Variable</A>).  The trailer generated for a PPCODE: section
  785. is based on the number of return values and on the number of times
  786. <CODE>SP</CODE> was updated by <CODE>[X]PUSH*()</CODE> macros.</P>
  787. <P>Note that macros <CODE>ST(i)</CODE>, <CODE>XST_m*()</CODE> and <CODE>XSRETURN*()</CODE> work equally
  788. well in CODE: sections and PPCODE: sections.</P>
  789. <P>The following XSUB will call the C <CODE>rpcb_gettime()</CODE> function
  790. and will return its two output values, timep and status, to
  791. Perl as a single list.</P>
  792. <PRE>
  793.      void
  794.      rpcb_gettime(host)
  795.           char *host
  796.         PREINIT:
  797.           time_t  timep;
  798.           bool_t  status;
  799.         PPCODE:
  800.           status = rpcb_gettime( host, &timep );
  801.           EXTEND(SP, 2);
  802.           PUSHs(sv_2mortal(newSViv(status)));
  803.           PUSHs(sv_2mortal(newSViv(timep)));</PRE>
  804. <P>Notice that the programmer must supply the C code necessary
  805. to have the real <CODE>rpcb_gettime()</CODE> function called and to have
  806. the return values properly placed on the argument stack.</P>
  807. <P>The <A HREF="../../lib/Pod/perlguts.html#item_void"><CODE>void</CODE></A> return type for this function tells the <STRONG>xsubpp</STRONG> compiler that
  808. the RETVAL variable is not needed or used and that it should not be created.
  809. In most scenarios the void return type should be used with the PPCODE:
  810. directive.</P>
  811. <P>The <CODE>EXTEND()</CODE> macro is used to make room on the argument
  812. stack for 2 return values.  The PPCODE: directive causes the
  813. <STRONG>xsubpp</STRONG> compiler to create a stack pointer available as <CODE>SP</CODE>, and it
  814. is this pointer which is being used in the <CODE>EXTEND()</CODE> macro.
  815. The values are then pushed onto the stack with the <CODE>PUSHs()</CODE>
  816. macro.</P>
  817. <P>Now the <CODE>rpcb_gettime()</CODE> function can be used from Perl with
  818. the following statement.</P>
  819. <PRE>
  820.      ($status, $timep) = rpcb_gettime("localhost");</PRE>
  821. <P>When handling output parameters with a PPCODE section, be sure to handle
  822. 'set' magic properly.  See <A HREF="../../lib/Pod/perlguts.html">the perlguts manpage</A> for details about 'set' magic.</P>
  823. <P>
  824. <H2><A NAME="returning undef and empty lists">Returning Undef And Empty Lists</A></H2>
  825. <P>Occasionally the programmer will want to return simply
  826. <A HREF="../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A> or an empty list if a function fails rather than a
  827. separate status value.  The <CODE>rpcb_gettime()</CODE> function offers
  828. just this situation.  If the function succeeds we would like
  829. to have it return the time and if it fails we would like to
  830. have undef returned.  In the following Perl code the value
  831. of $timep will either be undef or it will be a valid time.</P>
  832. <PRE>
  833.      $timep = rpcb_gettime( "localhost" );</PRE>
  834. <P>The following XSUB uses the <CODE>SV *</CODE> return type as a mnemonic only,
  835. and uses a CODE: block to indicate to the compiler
  836. that the programmer has supplied all the necessary code.  The
  837. <CODE>sv_newmortal()</CODE> call will initialize the return value to undef, making that
  838. the default return value.</P>
  839. <PRE>
  840.      SV *
  841.      rpcb_gettime(host)
  842.           char *  host
  843.         PREINIT:
  844.           time_t  timep;
  845.           bool_t x;
  846.         CODE:
  847.           ST(0) = sv_newmortal();
  848.           if( rpcb_gettime( host, &timep ) )
  849.                sv_setnv( ST(0), (double)timep);</PRE>
  850. <P>The next example demonstrates how one would place an explicit undef in the
  851. return value, should the need arise.</P>
  852. <PRE>
  853.      SV *
  854.      rpcb_gettime(host)
  855.           char *  host
  856.         PREINIT:
  857.           time_t  timep;
  858.           bool_t x;
  859.         CODE:
  860.           ST(0) = sv_newmortal();
  861.           if( rpcb_gettime( host, &timep ) ){
  862.                sv_setnv( ST(0), (double)timep);
  863.           }
  864.           else{
  865.                ST(0) = &PL_sv_undef;
  866.           }</PRE>
  867. <P>To return an empty list one must use a PPCODE: block and
  868. then not push return values on the stack.</P>
  869. <PRE>
  870.      void
  871.      rpcb_gettime(host)
  872.           char *host
  873.         PREINIT:
  874.           time_t  timep;
  875.         PPCODE:
  876.           if( rpcb_gettime( host, &timep ) )
  877.                PUSHs(sv_2mortal(newSViv(timep)));
  878.           else{
  879.               /* Nothing pushed on stack, so an empty
  880.                * list is implicitly returned. */
  881.           }</PRE>
  882. <P>Some people may be inclined to include an explicit <A HREF="../../lib/Pod/perlfunc.html#item_return"><CODE>return</CODE></A> in the above
  883. XSUB, rather than letting control fall through to the end.  In those
  884. situations <CODE>XSRETURN_EMPTY</CODE> should be used, instead.  This will ensure that
  885. the XSUB stack is properly adjusted.  Consult <A HREF="../../lib/Pod/perlguts.html#api listing">API LISTING in the perlguts manpage</A> for
  886. other <CODE>XSRETURN</CODE> macros.</P>
  887. <P>Since <CODE>XSRETURN_*</CODE> macros can be used with CODE blocks as well, one can
  888. rewrite this example as:</P>
  889. <PRE>
  890.      int
  891.      rpcb_gettime(host)
  892.           char *host
  893.         PREINIT:
  894.           time_t  timep;
  895.         CODE:
  896.           RETVAL = rpcb_gettime( host, &timep );
  897.           if (RETVAL == 0)
  898.                 XSRETURN_UNDEF;
  899.         OUTPUT:
  900.           RETVAL</PRE>
  901. <P>In fact, one can put this check into a CLEANUP: section as well.  Together
  902. with PREINIT: simplifications, this leads to:</P>
  903. <PRE>
  904.      int
  905.      rpcb_gettime(host)
  906.           char *host
  907.           time_t  timep;
  908.         CLEANUP:
  909.           if (RETVAL == 0)
  910.                 XSRETURN_UNDEF;</PRE>
  911. <P>
  912. <H2><A NAME="the require: keyword">The REQUIRE: Keyword</A></H2>
  913. <P>The REQUIRE: keyword is used to indicate the minimum version of the
  914. <STRONG>xsubpp</STRONG> compiler needed to compile the XS module.  An XS module which
  915. contains the following statement will compile with only <STRONG>xsubpp</STRONG> version
  916. 1.922 or greater:</P>
  917. <PRE>
  918.         REQUIRE: 1.922</PRE>
  919. <P>
  920. <H2><A NAME="the cleanup: keyword">The CLEANUP: Keyword</A></H2>
  921. <P>This keyword can be used when an XSUB requires special cleanup procedures
  922. before it terminates.  When the CLEANUP:  keyword is used it must follow
  923. any CODE:, PPCODE:, or OUTPUT: blocks which are present in the XSUB.  The
  924. code specified for the cleanup block will be added as the last statements
  925. in the XSUB.</P>
  926. <P>
  927. <H2><A NAME="the boot: keyword">The BOOT: Keyword</A></H2>
  928. <P>The BOOT: keyword is used to add code to the extension's bootstrap
  929. function.  The bootstrap function is generated by the <STRONG>xsubpp</STRONG> compiler and
  930. normally holds the statements necessary to register any XSUBs with Perl.
  931. With the BOOT: keyword the programmer can tell the compiler to add extra
  932. statements to the bootstrap function.</P>
  933. <P>This keyword may be used any time after the first MODULE keyword and should
  934. appear on a line by itself.  The first blank line after the keyword will
  935. terminate the code block.</P>
  936. <PRE>
  937.      BOOT:
  938.      # The following message will be printed when the
  939.      # bootstrap function executes.
  940.      printf("Hello from the bootstrap!\n");</PRE>
  941. <P>
  942. <H2><A NAME="the versioncheck: keyword">The VERSIONCHECK: Keyword</A></H2>
  943. <P>The VERSIONCHECK: keyword corresponds to <STRONG>xsubpp</STRONG>'s <CODE>-versioncheck</CODE> and
  944. <CODE>-noversioncheck</CODE> options.  This keyword overrides the command line
  945. options.  Version checking is enabled by default.  When version checking is
  946. enabled the XS module will attempt to verify that its version matches the
  947. version of the PM module.</P>
  948. <P>To enable version checking:</P>
  949. <PRE>
  950.     VERSIONCHECK: ENABLE</PRE>
  951. <P>To disable version checking:</P>
  952. <PRE>
  953.     VERSIONCHECK: DISABLE</PRE>
  954. <P>
  955. <H2><A NAME="the prototypes: keyword">The PROTOTYPES: Keyword</A></H2>
  956. <P>The PROTOTYPES: keyword corresponds to <STRONG>xsubpp</STRONG>'s <CODE>-prototypes</CODE> and
  957. <CODE>-noprototypes</CODE> options.  This keyword overrides the command line options.
  958. Prototypes are enabled by default.  When prototypes are enabled XSUBs will
  959. be given Perl prototypes.  This keyword may be used multiple times in an XS
  960. module to enable and disable prototypes for different parts of the module.</P>
  961. <P>To enable prototypes:</P>
  962. <PRE>
  963.     PROTOTYPES: ENABLE</PRE>
  964. <P>To disable prototypes:</P>
  965. <PRE>
  966.     PROTOTYPES: DISABLE</PRE>
  967. <P>
  968. <H2><A NAME="the prototype: keyword">The PROTOTYPE: Keyword</A></H2>
  969. <P>This keyword is similar to the PROTOTYPES: keyword above but can be used to
  970. force <STRONG>xsubpp</STRONG> to use a specific prototype for the XSUB.  This keyword
  971. overrides all other prototype options and keywords but affects only the
  972. current XSUB.  Consult <A HREF="../../lib/Pod/perlsub.html#prototypes">Prototypes in the perlsub manpage</A> for information about Perl
  973. prototypes.</P>
  974. <PRE>
  975.     bool_t
  976.     rpcb_gettime(timep, ...)
  977.           time_t timep = NO_INIT
  978.         PROTOTYPE: $;$
  979.         PREINIT:
  980.           char *host = "localhost";
  981.           STRLEN n_a;
  982.         CODE:
  983.                   if( items > 1 )
  984.                        host = (char *)SvPV(ST(1), n_a);
  985.                   RETVAL = rpcb_gettime( host, &timep );
  986.         OUTPUT:
  987.           timep
  988.           RETVAL</PRE>
  989. <P>
  990. <H2><A NAME="the alias: keyword">The ALIAS: Keyword</A></H2>
  991. <P>The ALIAS: keyword allows an XSUB to have two or more unique Perl names
  992. and to know which of those names was used when it was invoked.  The Perl
  993. names may be fully-qualified with package names.  Each alias is given an
  994. index.  The compiler will setup a variable called <CODE>ix</CODE> which contain the
  995. index of the alias which was used.  When the XSUB is called with its
  996. declared name <CODE>ix</CODE> will be 0.</P>
  997. <P>The following example will create aliases <CODE>FOO::gettime()</CODE> and
  998. <CODE>BAR::getit()</CODE> for this function.</P>
  999. <PRE>
  1000.     bool_t
  1001.     rpcb_gettime(host,timep)
  1002.           char *host
  1003.           time_t &timep
  1004.         ALIAS:
  1005.             FOO::gettime = 1
  1006.             BAR::getit = 2
  1007.         INIT:
  1008.           printf("# ix = %d\n", ix );
  1009.         OUTPUT:
  1010.           timep</PRE>
  1011. <P>
  1012. <H2><A NAME="the interface: keyword">The INTERFACE: Keyword</A></H2>
  1013. <P>This keyword declares the current XSUB as a keeper of the given
  1014. calling signature.  If some text follows this keyword, it is
  1015. considered as a list of functions which have this signature, and
  1016. should be attached to the current XSUB.</P>
  1017. <P>For example, if you have 4 C functions multiply(), divide(), add(),
  1018. <CODE>subtract()</CODE> all having the signature:</P>
  1019. <PRE>
  1020.     symbolic f(symbolic, symbolic);</PRE>
  1021. <P>you can make them all to use the same XSUB using this:</P>
  1022. <PRE>
  1023.     symbolic
  1024.     interface_s_ss(arg1, arg2)  
  1025.         symbolic        arg1
  1026.         symbolic        arg2
  1027.     INTERFACE:
  1028.         multiply divide 
  1029.         add subtract</PRE>
  1030. <P>(This is the complete XSUB code for 4 Perl functions!)  Four generated
  1031. Perl function share names with corresponding C functions.</P>
  1032. <P>The advantage of this approach comparing to ALIAS: keyword is that there
  1033. is no need to code a switch statement, each Perl function (which shares
  1034. the same XSUB) knows which C function it should call.  Additionally, one
  1035. can attach an extra function <CODE>remainder()</CODE> at runtime by using</P>
  1036. <PRE>
  1037.     CV *mycv = newXSproto("Symbolic::remainder", 
  1038.                           XS_Symbolic_interface_s_ss, __FILE__, "$$");
  1039.     XSINTERFACE_FUNC_SET(mycv, remainder);</PRE>
  1040. <P>say, from another XSUB.  (This example supposes that there was no
  1041. INTERFACE_MACRO: section, otherwise one needs to use something else instead of
  1042. <CODE>XSINTERFACE_FUNC_SET</CODE>, see the next section.)</P>
  1043. <P>
  1044. <H2><A NAME="the interface_macro: keyword">The INTERFACE_MACRO: Keyword</A></H2>
  1045. <P>This keyword allows one to define an INTERFACE using a different way
  1046. to extract a function pointer from an XSUB.  The text which follows
  1047. this keyword should give the name of macros which would extract/set a
  1048. function pointer.  The extractor macro is given return type, <CODE>CV*</CODE>,
  1049. and <CODE>XSANY.any_dptr</CODE> for this <CODE>CV*</CODE>.  The setter macro is given cv,
  1050. and the function pointer.</P>
  1051. <P>The default value is <CODE>XSINTERFACE_FUNC</CODE> and <CODE>XSINTERFACE_FUNC_SET</CODE>.
  1052. An INTERFACE keyword with an empty list of functions can be omitted if
  1053. INTERFACE_MACRO keyword is used.</P>
  1054. <P>Suppose that in the previous example functions pointers for 
  1055. multiply(), divide(), add(), <CODE>subtract()</CODE> are kept in a global C array
  1056. <CODE>fp[]</CODE> with offsets being <CODE>multiply_off</CODE>, <CODE>divide_off</CODE>, <CODE>add_off</CODE>,
  1057. <CODE>subtract_off</CODE>.  Then one can use</P>
  1058. <PRE>
  1059.     #define XSINTERFACE_FUNC_BYOFFSET(ret,cv,f) \
  1060.         ((XSINTERFACE_CVT(ret,))fp[CvXSUBANY(cv).any_i32])
  1061.     #define XSINTERFACE_FUNC_BYOFFSET_set(cv,f) \
  1062.         CvXSUBANY(cv).any_i32 = CAT2( f, _off )</PRE>
  1063. <P>in C section,</P>
  1064. <PRE>
  1065.     symbolic
  1066.     interface_s_ss(arg1, arg2)  
  1067.         symbolic        arg1
  1068.         symbolic        arg2
  1069.       INTERFACE_MACRO: 
  1070.         XSINTERFACE_FUNC_BYOFFSET
  1071.         XSINTERFACE_FUNC_BYOFFSET_set
  1072.       INTERFACE:
  1073.         multiply divide 
  1074.         add subtract</PRE>
  1075. <P>in XSUB section.</P>
  1076. <P>
  1077. <H2><A NAME="the include: keyword">The INCLUDE: Keyword</A></H2>
  1078. <P>This keyword can be used to pull other files into the XS module.  The other
  1079. files may have XS code.  INCLUDE: can also be used to run a command to
  1080. generate the XS code to be pulled into the module.</P>
  1081. <P>The file <EM>Rpcb1.xsh</EM> contains our <CODE>rpcb_gettime()</CODE> function:</P>
  1082. <PRE>
  1083.     bool_t
  1084.     rpcb_gettime(host,timep)
  1085.           char *host
  1086.           time_t &timep
  1087.         OUTPUT:
  1088.           timep</PRE>
  1089. <P>The XS module can use INCLUDE: to pull that file into it.</P>
  1090. <PRE>
  1091.     INCLUDE: Rpcb1.xsh</PRE>
  1092. <P>If the parameters to the INCLUDE: keyword are followed by a pipe (<CODE>|</CODE>) then
  1093. the compiler will interpret the parameters as a command.</P>
  1094. <PRE>
  1095.     INCLUDE: cat Rpcb1.xsh |</PRE>
  1096. <P>
  1097. <H2><A NAME="the case: keyword">The CASE: Keyword</A></H2>
  1098. <P>The CASE: keyword allows an XSUB to have multiple distinct parts with each
  1099. part acting as a virtual XSUB.  CASE: is greedy and if it is used then all
  1100. other XS keywords must be contained within a CASE:.  This means nothing may
  1101. precede the first CASE: in the XSUB and anything following the last CASE: is
  1102. included in that case.</P>
  1103. <P>A CASE: might switch via a parameter of the XSUB, via the <CODE>ix</CODE> ALIAS:
  1104. variable (see <A HREF="#the alias: keyword">The ALIAS: Keyword</A>), or maybe via the <CODE>items</CODE> variable
  1105. (see <A HREF="#variablelength parameter lists">Variable-length Parameter Lists</A>).  The last CASE: becomes the
  1106. <STRONG>default</STRONG> case if it is not associated with a conditional.  The following
  1107. example shows CASE switched via <CODE>ix</CODE> with a function <CODE>rpcb_gettime()</CODE>
  1108. having an alias <CODE>x_gettime()</CODE>.  When the function is called as
  1109. <CODE>rpcb_gettime()</CODE> its parameters are the usual <CODE>(char *host, time_t *timep)</CODE>,
  1110. but when the function is called as <CODE>x_gettime()</CODE> its parameters are
  1111. reversed, <CODE>(time_t *timep, char *host)</CODE>.</P>
  1112. <PRE>
  1113.     long
  1114.     rpcb_gettime(a,b)
  1115.       CASE: ix == 1
  1116.         ALIAS:
  1117.           x_gettime = 1
  1118.         INPUT:
  1119.           # 'a' is timep, 'b' is host
  1120.           char *b
  1121.           time_t a = NO_INIT
  1122.         CODE:
  1123.                RETVAL = rpcb_gettime( b, &a );
  1124.         OUTPUT:
  1125.           a
  1126.           RETVAL
  1127.       CASE:
  1128.           # 'a' is host, 'b' is timep
  1129.           char *a
  1130.           time_t &b = NO_INIT
  1131.         OUTPUT:
  1132.           b
  1133.           RETVAL</PRE>
  1134. <P>That function can be called with either of the following statements.  Note
  1135. the different argument lists.</P>
  1136. <PRE>
  1137.         $status = rpcb_gettime( $host, $timep );</PRE>
  1138. <PRE>
  1139.         $status = x_gettime( $timep, $host );</PRE>
  1140. <P>
  1141. <H2><A NAME="the & unary operator">The & Unary Operator</A></H2>
  1142. <P>The <CODE>&</CODE> unary operator in the INPUT: section is used to tell <STRONG>xsubpp</STRONG>
  1143. that it should convert a Perl value to/from C using the C type to the left
  1144. of <CODE>&</CODE>, but provide a pointer to this value when the C function is called.</P>
  1145. <P>This is useful to avoid a CODE: block for a C function which takes a parameter
  1146. by reference.  Typically, the parameter should be not a pointer type (an
  1147. <A HREF="../../lib/Pod/perlfunc.html#item_int"><CODE>int</CODE></A> or <CODE>long</CODE> but not a <CODE>int*</CODE> or <CODE>long*</CODE>).</P>
  1148. <P>The following XSUB will generate incorrect C code.  The <STRONG>xsubpp</STRONG> compiler will
  1149. turn this into code which calls <CODE>rpcb_gettime()</CODE> with parameters <CODE>(char
  1150. *host, time_t timep)</CODE>, but the real <CODE>rpcb_gettime()</CODE> wants the <CODE>timep</CODE>
  1151. parameter to be of type <CODE>time_t*</CODE> rather than <CODE>time_t</CODE>.</P>
  1152. <PRE>
  1153.     bool_t
  1154.     rpcb_gettime(host,timep)
  1155.           char *host
  1156.           time_t timep
  1157.         OUTPUT:
  1158.           timep</PRE>
  1159. <P>That problem is corrected by using the <CODE>&</CODE> operator.  The <STRONG>xsubpp</STRONG> compiler
  1160. will now turn this into code which calls <CODE>rpcb_gettime()</CODE> correctly with
  1161. parameters <CODE>(char *host, time_t *timep)</CODE>.  It does this by carrying the
  1162. <CODE>&</CODE> through, so the function call looks like <CODE>rpcb_gettime(host, &timep)</CODE>.</P>
  1163. <PRE>
  1164.     bool_t
  1165.     rpcb_gettime(host,timep)
  1166.           char *host
  1167.           time_t &timep
  1168.         OUTPUT:
  1169.           timep</PRE>
  1170. <P>
  1171. <H2><A NAME="inserting comments and c preprocessor directives">Inserting Comments and C Preprocessor Directives</A></H2>
  1172. <P>C preprocessor directives are allowed within BOOT:, PREINIT: INIT:,
  1173. CODE:, PPCODE:, and CLEANUP: blocks, as well as outside the functions.
  1174. Comments are allowed anywhere after the MODULE keyword.  The compiler
  1175. will pass the preprocessor directives through untouched and will remove
  1176. the commented lines.</P>
  1177. <P>Comments can be added to XSUBs by placing a <CODE>#</CODE> as the first
  1178. non-whitespace of a line.  Care should be taken to avoid making the
  1179. comment look like a C preprocessor directive, lest it be interpreted as
  1180. such.  The simplest way to prevent this is to put whitespace in front of
  1181. the <CODE>#</CODE>.</P>
  1182. <P>If you use preprocessor directives to choose one of two
  1183. versions of a function, use</P>
  1184. <PRE>
  1185.     #if ... version1
  1186.     #else /* ... version2  */
  1187.     #endif</PRE>
  1188. <P>and not</P>
  1189. <PRE>
  1190.     #if ... version1
  1191.     #endif
  1192.     #if ... version2
  1193.     #endif</PRE>
  1194. <P>because otherwise <STRONG>xsubpp</STRONG> will believe that you made a duplicate
  1195. definition of the function.  Also, put a blank line before the
  1196. #else/#endif so it will not be seen as part of the function body.</P>
  1197. <P>
  1198. <H2><A NAME="using xs with c++">Using XS With C++</A></H2>
  1199. <P>If an XSUB name contains <CODE>::</CODE>, it is considered to be a C++ method.
  1200. The generated Perl function will assume that
  1201. its first argument is an object pointer.  The object pointer
  1202. will be stored in a variable called THIS.  The object should
  1203. have been created by C++ with the <CODE>new()</CODE> function and should
  1204. be blessed by Perl with the <CODE>sv_setref_pv()</CODE> macro.  The
  1205. blessing of the object by Perl can be handled by a typemap.  An example
  1206. typemap is shown at the end of this section.</P>
  1207. <P>If the return type of the XSUB includes <CODE>static</CODE>, the method is considered
  1208. to be a static method.  It will call the C++
  1209. function using the class::method() syntax.  If the method is not static
  1210. the function will be called using the THIS-><CODE>method()</CODE> syntax.</P>
  1211. <P>The next examples will use the following C++ class.</P>
  1212. <PRE>
  1213.      class color {
  1214.           public:
  1215.           color();
  1216.           ~color();
  1217.           int blue();
  1218.           void set_blue( int );</PRE>
  1219. <PRE>
  1220.           private:
  1221.           int c_blue;
  1222.      };</PRE>
  1223. <P>The XSUBs for the <CODE>blue()</CODE> and <CODE>set_blue()</CODE> methods are defined with the class
  1224. name but the parameter for the object (THIS, or ``self'') is implicit and is
  1225. not listed.</P>
  1226. <PRE>
  1227.      int
  1228.      color::blue()</PRE>
  1229. <PRE>
  1230.      void
  1231.      color::set_blue( val )
  1232.           int val</PRE>
  1233. <P>Both Perl functions will expect an object as the first parameter.  In the 
  1234. generated C++ code the object is called <CODE>THIS</CODE>, and the method call will
  1235. be performed on this object.  So in the C++ code the <CODE>blue()</CODE> and <CODE>set_blue()</CODE>
  1236. methods will be called as this:</P>
  1237. <PRE>
  1238.      RETVAL = THIS->blue();</PRE>
  1239. <PRE>
  1240.      THIS->set_blue( val );</PRE>
  1241. <P>You could also write a single get/set method using an optional argument:</P>
  1242. <PRE>
  1243.      int
  1244.      color::blue( val = NO_INIT )
  1245.          int val
  1246.          PROTOTYPE $;$
  1247.          CODE:
  1248.              if (items > 1)
  1249.                  THIS->set_blue( val );
  1250.              RETVAL = THIS->blue();
  1251.          OUTPUT:
  1252.              RETVAL</PRE>
  1253. <P>If the function's name is <STRONG>DESTROY</STRONG> then the C++ <A HREF="../../lib/Pod/perlfunc.html#item_delete"><CODE>delete</CODE></A> function will be
  1254. called and <CODE>THIS</CODE> will be given as its parameter.  The generated C++ code for</P>
  1255. <PRE>
  1256.      void
  1257.      color::DESTROY()</PRE>
  1258. <P>will look like this:</P>
  1259. <PRE>
  1260.      color *THIS = ...; // Initialized as in typemap</PRE>
  1261. <PRE>
  1262.      delete THIS;</PRE>
  1263. <P>If the function's name is <STRONG>new</STRONG> then the C++ <CODE>new</CODE> function will be called
  1264. to create a dynamic C++ object.  The XSUB will expect the class name, which
  1265. will be kept in a variable called <CODE>CLASS</CODE>, to be given as the first
  1266. argument.</P>
  1267. <PRE>
  1268.      color *
  1269.      color::new()</PRE>
  1270. <P>The generated C++ code will call <CODE>new</CODE>.</P>
  1271. <PRE>
  1272.      RETVAL = new color();</PRE>
  1273. <P>The following is an example of a typemap that could be used for this C++
  1274. example.</P>
  1275. <PRE>
  1276.     TYPEMAP
  1277.     color *             O_OBJECT</PRE>
  1278. <PRE>
  1279.     OUTPUT
  1280.     # The Perl object is blessed into 'CLASS', which should be a
  1281.     # char* having the name of the package for the blessing.
  1282.     O_OBJECT
  1283.         sv_setref_pv( $arg, CLASS, (void*)$var );</PRE>
  1284. <PRE>
  1285.     INPUT
  1286.     O_OBJECT
  1287.         if( sv_isobject($arg) && (SvTYPE(SvRV($arg)) == SVt_PVMG) )
  1288.                 $var = ($type)SvIV((SV*)SvRV( $arg ));
  1289.         else{
  1290.                 warn( \"${Package}::$func_name() -- $var is not a blessed SV reference\" );
  1291.                 XSRETURN_UNDEF;
  1292.         }</PRE>
  1293. <P>
  1294. <H2><A NAME="interface strategy">Interface Strategy</A></H2>
  1295. <P>When designing an interface between Perl and a C library a straight
  1296. translation from C to XS (such as created by <CODE>h2xs -x</CODE>) is often sufficient.
  1297. However, sometimes the interface will look
  1298. very C-like and occasionally nonintuitive, especially when the C function
  1299. modifies one of its parameters, or returns failure inband (as in ``negative
  1300. return values mean failure'').  In cases where the programmer wishes to
  1301. create a more Perl-like interface the following strategy may help to
  1302. identify the more critical parts of the interface.</P>
  1303. <P>Identify the C functions with input/output or output parameters.  The XSUBs for
  1304. these functions may be able to return lists to Perl.</P>
  1305. <P>Identify the C functions which use some inband info as an indication
  1306. of failure.  They may be
  1307. candidates to return undef or an empty list in case of failure.  If the
  1308. failure may be detected without a call to the C function, you may want to use
  1309. an INIT: section to report the failure.  For failures detectable after the C
  1310. function returns one may want to use a CLEANUP: section to process the
  1311. failure.  In more complicated cases use CODE: or PPCODE: sections.</P>
  1312. <P>If many functions use the same failure indication based on the return value,
  1313. you may want to create a special typedef to handle this situation.  Put</P>
  1314. <PRE>
  1315.   typedef int negative_is_failure;</PRE>
  1316. <P>near the beginning of XS file, and create an OUTPUT typemap entry
  1317. for <CODE>negative_is_failure</CODE> which converts negative values to <A HREF="../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A>, or
  1318. maybe croak()s.  After this the return value of type <CODE>negative_is_failure</CODE>
  1319. will create more Perl-like interface.</P>
  1320. <P>Identify which values are used by only the C and XSUB functions
  1321. themselves, say, when a parameter to a function should be a contents of a
  1322. global variable.  If Perl does not need to access the contents of the value
  1323. then it may not be necessary to provide a translation for that value
  1324. from C to Perl.</P>
  1325. <P>Identify the pointers in the C function parameter lists and return
  1326. values.  Some pointers may be used to implement input/output or
  1327. output parameters, they can be handled in XS with the <CODE>&</CODE> unary operator,
  1328. and, possibly, using the NO_INIT keyword.
  1329. Some others will require handling of types like <CODE>int *</CODE>, and one needs
  1330. to decide what a useful Perl translation will do in such a case.  When
  1331. the semantic is clear, it is advisable to put the translation into a typemap
  1332. file.</P>
  1333. <P>Identify the structures used by the C functions.  In many
  1334. cases it may be helpful to use the T_PTROBJ typemap for
  1335. these structures so they can be manipulated by Perl as
  1336. blessed objects.  (This is handled automatically by <CODE>h2xs -x</CODE>.)</P>
  1337. <P>If the same C type is used in several different contexts which require
  1338. different translations, <CODE>typedef</CODE> several new types mapped to this C type,
  1339. and create separate <EM>typemap</EM> entries for these new types.  Use these
  1340. types in declarations of return type and parameters to XSUBs.</P>
  1341. <P>
  1342. <H2><A NAME="perl objects and c structures">Perl Objects And C Structures</A></H2>
  1343. <P>When dealing with C structures one should select either
  1344. <STRONG>T_PTROBJ</STRONG> or <STRONG>T_PTRREF</STRONG> for the XS type.  Both types are
  1345. designed to handle pointers to complex objects.  The
  1346. T_PTRREF type will allow the Perl object to be unblessed
  1347. while the T_PTROBJ type requires that the object be blessed.
  1348. By using T_PTROBJ one can achieve a form of type-checking
  1349. because the XSUB will attempt to verify that the Perl object
  1350. is of the expected type.</P>
  1351. <P>The following XS code shows the <CODE>getnetconfigent()</CODE> function which is used
  1352. with ONC+ TIRPC.  The <CODE>getnetconfigent()</CODE> function will return a pointer to a
  1353. C structure and has the C prototype shown below.  The example will
  1354. demonstrate how the C pointer will become a Perl reference.  Perl will
  1355. consider this reference to be a pointer to a blessed object and will
  1356. attempt to call a destructor for the object.  A destructor will be
  1357. provided in the XS source to free the memory used by getnetconfigent().
  1358. Destructors in XS can be created by specifying an XSUB function whose name
  1359. ends with the word <STRONG>DESTROY</STRONG>.  XS destructors can be used to free memory
  1360. which may have been malloc'd by another XSUB.</P>
  1361. <PRE>
  1362.      struct netconfig *getnetconfigent(const char *netid);</PRE>
  1363. <P>A <CODE>typedef</CODE> will be created for <CODE>struct netconfig</CODE>.  The Perl
  1364. object will be blessed in a class matching the name of the C
  1365. type, with the tag <CODE>Ptr</CODE> appended, and the name should not
  1366. have embedded spaces if it will be a Perl package name.  The
  1367. destructor will be placed in a class corresponding to the
  1368. class of the object and the PREFIX keyword will be used to
  1369. trim the name to the word DESTROY as Perl will expect.</P>
  1370. <PRE>
  1371.      typedef struct netconfig Netconfig;</PRE>
  1372. <PRE>
  1373.      MODULE = RPC  PACKAGE = RPC</PRE>
  1374. <PRE>
  1375.      Netconfig *
  1376.      getnetconfigent(netid)
  1377.           char *netid</PRE>
  1378. <PRE>
  1379.      MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_</PRE>
  1380. <PRE>
  1381.      void
  1382.      rpcb_DESTROY(netconf)
  1383.           Netconfig *netconf
  1384.         CODE:
  1385.           printf("Now in NetconfigPtr::DESTROY\n");
  1386.           free( netconf );</PRE>
  1387. <P>This example requires the following typemap entry.  Consult the typemap
  1388. section for more information about adding new typemaps for an extension.</P>
  1389. <PRE>
  1390.      TYPEMAP
  1391.      Netconfig *  T_PTROBJ</PRE>
  1392. <P>This example will be used with the following Perl statements.</P>
  1393. <PRE>
  1394.      use RPC;
  1395.      $netconf = getnetconfigent("udp");</PRE>
  1396. <P>When Perl destroys the object referenced by $netconf it will send the
  1397. object to the supplied XSUB DESTROY function.  Perl cannot determine, and
  1398. does not care, that this object is a C struct and not a Perl object.  In
  1399. this sense, there is no difference between the object created by the
  1400. <CODE>getnetconfigent()</CODE> XSUB and an object created by a normal Perl subroutine.</P>
  1401. <P>
  1402. <H2><A NAME="the typemap">The Typemap</A></H2>
  1403. <P>The typemap is a collection of code fragments which are used by the <STRONG>xsubpp</STRONG>
  1404. compiler to map C function parameters and values to Perl values.  The
  1405. typemap file may consist of three sections labeled <CODE>TYPEMAP</CODE>, <CODE>INPUT</CODE>, and
  1406. <CODE>OUTPUT</CODE>.  An unlabelled initial section is assumed to be a <CODE>TYPEMAP</CODE>
  1407. section.  The INPUT section tells
  1408. the compiler how to translate Perl values
  1409. into variables of certain C types.  The OUTPUT section tells the compiler
  1410. how to translate the values from certain C types into values Perl can
  1411. understand.  The TYPEMAP section tells the compiler which of the INPUT and
  1412. OUTPUT code fragments should be used to map a given C type to a Perl value.
  1413. The section labels <CODE>TYPEMAP</CODE>, <CODE>INPUT</CODE>, or <CODE>OUTPUT</CODE> must begin
  1414. in the first column on a line by themselves, and must be in uppercase.</P>
  1415. <P>The default typemap in the <CODE>ext</CODE> directory of the Perl source contains many
  1416. useful types which can be used by Perl extensions.  Some extensions define
  1417. additional typemaps which they keep in their own directory.  These
  1418. additional typemaps may reference INPUT and OUTPUT maps in the main
  1419. typemap.  The <STRONG>xsubpp</STRONG> compiler will allow the extension's own typemap to
  1420. override any mappings which are in the default typemap.</P>
  1421. <P>Most extensions which require a custom typemap will need only the TYPEMAP
  1422. section of the typemap file.  The custom typemap used in the
  1423. <CODE>getnetconfigent()</CODE> example shown earlier demonstrates what may be the typical
  1424. use of extension typemaps.  That typemap is used to equate a C structure
  1425. with the T_PTROBJ typemap.  The typemap used by <CODE>getnetconfigent()</CODE> is shown
  1426. here.  Note that the C type is separated from the XS type with a tab and
  1427. that the C unary operator <CODE>*</CODE> is considered to be a part of the C type name.</P>
  1428. <PRE>
  1429.         TYPEMAP
  1430.         Netconfig *<tab>T_PTROBJ</PRE>
  1431. <P>Here's a more complicated example: suppose that you wanted <CODE>struct
  1432. netconfig</CODE> to be blessed into the class <CODE>Net::Config</CODE>.  One way to do
  1433. this is to use underscores (_) to separate package names, as follows:</P>
  1434. <PRE>
  1435.         typedef struct netconfig * Net_Config;</PRE>
  1436. <P>And then provide a typemap entry <CODE>T_PTROBJ_SPECIAL</CODE> that maps underscores to
  1437. double-colons (::), and declare <CODE>Net_Config</CODE> to be of that type:</P>
  1438. <PRE>
  1439.         TYPEMAP
  1440.         Net_Config      T_PTROBJ_SPECIAL</PRE>
  1441. <PRE>
  1442.         INPUT
  1443.         T_PTROBJ_SPECIAL
  1444.                 if (sv_derived_from($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")) {
  1445.                         IV tmp = SvIV((SV*)SvRV($arg));
  1446.                 $var = ($type) tmp;
  1447.                 }
  1448.                 else
  1449.                         croak(\"$var is not of type ${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")</PRE>
  1450. <PRE>
  1451.         OUTPUT
  1452.         T_PTROBJ_SPECIAL
  1453.                 sv_setref_pv($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\",
  1454.                 (void*)$var);</PRE>
  1455. <P>The INPUT and OUTPUT sections substitute underscores for double-colons
  1456. on the fly, giving the desired effect.  This example demonstrates some
  1457. of the power and versatility of the typemap facility.</P>
  1458. <P>
  1459. <HR>
  1460. <H1><A NAME="examples">EXAMPLES</A></H1>
  1461. <P>File <CODE>RPC.xs</CODE>: Interface to some ONC+ RPC bind library functions.</P>
  1462. <PRE>
  1463.      #include "EXTERN.h"
  1464.      #include "perl.h"
  1465.      #include "XSUB.h"</PRE>
  1466. <PRE>
  1467.      #include <rpc/rpc.h></PRE>
  1468. <PRE>
  1469.      typedef struct netconfig Netconfig;</PRE>
  1470. <PRE>
  1471.      MODULE = RPC  PACKAGE = RPC</PRE>
  1472. <PRE>
  1473.      SV *
  1474.      rpcb_gettime(host="localhost")
  1475.           char *host
  1476.         PREINIT:
  1477.           time_t  timep;
  1478.         CODE:
  1479.           ST(0) = sv_newmortal();
  1480.           if( rpcb_gettime( host, &timep ) )
  1481.                sv_setnv( ST(0), (double)timep );</PRE>
  1482. <PRE>
  1483.      Netconfig *
  1484.      getnetconfigent(netid="udp")
  1485.           char *netid</PRE>
  1486. <PRE>
  1487.      MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_</PRE>
  1488. <PRE>
  1489.      void
  1490.      rpcb_DESTROY(netconf)
  1491.           Netconfig *netconf
  1492.         CODE:
  1493.           printf("NetconfigPtr::DESTROY\n");
  1494.           free( netconf );</PRE>
  1495. <P>File <CODE>typemap</CODE>: Custom typemap for RPC.xs.</P>
  1496. <PRE>
  1497.      TYPEMAP
  1498.      Netconfig *  T_PTROBJ</PRE>
  1499. <P>File <CODE>RPC.pm</CODE>: Perl module for the RPC extension.</P>
  1500. <PRE>
  1501.      package RPC;</PRE>
  1502. <PRE>
  1503.      require Exporter;
  1504.      require DynaLoader;
  1505.      @ISA = qw(Exporter DynaLoader);
  1506.      @EXPORT = qw(rpcb_gettime getnetconfigent);</PRE>
  1507. <PRE>
  1508.      bootstrap RPC;
  1509.      1;</PRE>
  1510. <P>File <CODE>rpctest.pl</CODE>: Perl test program for the RPC extension.</P>
  1511. <PRE>
  1512.      use RPC;</PRE>
  1513. <PRE>
  1514.      $netconf = getnetconfigent();
  1515.      $a = rpcb_gettime();
  1516.      print "time = $a\n";
  1517.      print "netconf = $netconf\n";</PRE>
  1518. <PRE>
  1519.      $netconf = getnetconfigent("tcp");
  1520.      $a = rpcb_gettime("poplar");
  1521.      print "time = $a\n";
  1522.      print "netconf = $netconf\n";</PRE>
  1523. <P>
  1524. <HR>
  1525. <H1><A NAME="xs version">XS VERSION</A></H1>
  1526. <P>This document covers features supported by <CODE>xsubpp</CODE> 1.935.</P>
  1527. <P>
  1528. <HR>
  1529. <H1><A NAME="author">AUTHOR</A></H1>
  1530. <P>Originally written by Dean Roehrich <<EM><A HREF="mailto:roehrich@cray.com">roehrich@cray.com</A></EM>>.</P>
  1531. <P>Maintained since 1996 by The Perl Porters <<EM><A HREF="mailto:perlbug@perl.com">perlbug@perl.com</A></EM>>.</P>
  1532. <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
  1533. <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
  1534. <STRONG><P CLASS=block> perlxs - XS language reference manual</P></STRONG>
  1535. </TD></TR>
  1536. </TABLE>
  1537.  
  1538. </BODY>
  1539.  
  1540. </HTML>
  1541.