Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1780 lines
64 KiB

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