Source code of Windows XP (NT5)
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.

1352 lines
45 KiB

  1. =head1 NAME
  2. perlxs - XS language reference manual
  3. =head1 DESCRIPTION
  4. =head2 Introduction
  5. XS is a language used to create an extension interface
  6. between Perl and some C library which one wishes to use with
  7. Perl. The XS interface is combined with the library to
  8. create a new library which can be linked to Perl. An B<XSUB>
  9. is a function in the XS language and is the core component
  10. of the Perl application interface.
  11. The XS compiler is called B<xsubpp>. This compiler will embed
  12. the constructs necessary to let an XSUB, which is really a C
  13. function in disguise, manipulate Perl values and creates the
  14. glue necessary to let Perl access the XSUB. The compiler
  15. uses B<typemaps> to determine how to map C function parameters
  16. and variables to Perl values. The default typemap handles
  17. many common C types. A supplement typemap must be created
  18. to handle special structures and types for the library being
  19. linked.
  20. See L<perlxstut> for a tutorial on the whole extension creation process.
  21. Note: For many extensions, Dave Beazley's SWIG system provides a
  22. significantly more convenient mechanism for creating the XS glue
  23. code. See L<http://www.cs.utah.edu/~beazley/SWIG> for more
  24. information.
  25. =head2 On The Road
  26. Many of the examples which follow will concentrate on creating an interface
  27. between Perl and the ONC+ RPC bind library functions. The rpcb_gettime()
  28. function is used to demonstrate many features of the XS language. This
  29. function has two parameters; the first is an input parameter and the second
  30. is an output parameter. The function also returns a status value.
  31. bool_t rpcb_gettime(const char *host, time_t *timep);
  32. From C this function will be called with the following
  33. statements.
  34. #include <rpc/rpc.h>
  35. bool_t status;
  36. time_t timep;
  37. status = rpcb_gettime( "localhost", &timep );
  38. If an XSUB is created to offer a direct translation between this function
  39. and Perl, then this XSUB will be used from Perl with the following code.
  40. The $status and $timep variables will contain the output of the function.
  41. use RPC;
  42. $status = rpcb_gettime( "localhost", $timep );
  43. The following XS file shows an XS subroutine, or XSUB, which
  44. demonstrates one possible interface to the rpcb_gettime()
  45. function. This XSUB represents a direct translation between
  46. C and Perl and so preserves the interface even from Perl.
  47. This XSUB will be invoked from Perl with the usage shown
  48. above. Note that the first three #include statements, for
  49. C<EXTERN.h>, C<perl.h>, and C<XSUB.h>, will always be present at the
  50. beginning of an XS file. This approach and others will be
  51. expanded later in this document.
  52. #include "EXTERN.h"
  53. #include "perl.h"
  54. #include "XSUB.h"
  55. #include <rpc/rpc.h>
  56. MODULE = RPC PACKAGE = RPC
  57. bool_t
  58. rpcb_gettime(host,timep)
  59. char *host
  60. time_t &timep
  61. OUTPUT:
  62. timep
  63. Any extension to Perl, including those containing XSUBs,
  64. should have a Perl module to serve as the bootstrap which
  65. pulls the extension into Perl. This module will export the
  66. extension's functions and variables to the Perl program and
  67. will cause the extension's XSUBs to be linked into Perl.
  68. The following module will be used for most of the examples
  69. in this document and should be used from Perl with the C<use>
  70. command as shown earlier. Perl modules are explained in
  71. more detail later in this document.
  72. package RPC;
  73. require Exporter;
  74. require DynaLoader;
  75. @ISA = qw(Exporter DynaLoader);
  76. @EXPORT = qw( rpcb_gettime );
  77. bootstrap RPC;
  78. 1;
  79. Throughout this document a variety of interfaces to the rpcb_gettime()
  80. XSUB will be explored. The XSUBs will take their parameters in different
  81. orders or will take different numbers of parameters. In each case the
  82. XSUB is an abstraction between Perl and the real C rpcb_gettime()
  83. function, and the XSUB must always ensure that the real rpcb_gettime()
  84. function is called with the correct parameters. This abstraction will
  85. allow the programmer to create a more Perl-like interface to the C
  86. function.
  87. =head2 The Anatomy of an XSUB
  88. The following XSUB allows a Perl program to access a C library function
  89. called sin(). The XSUB will imitate the C function which takes a single
  90. argument and returns a single value.
  91. double
  92. sin(x)
  93. double x
  94. When using C pointers the indirection operator C<*> should be considered
  95. part of the type and the address operator C<&> should be considered part of
  96. the variable, as is demonstrated in the rpcb_gettime() function above. See
  97. the section on typemaps for more about handling qualifiers and unary
  98. operators in C types.
  99. The function name and the return type must be placed on
  100. separate lines.
  101. INCORRECT CORRECT
  102. double sin(x) double
  103. double x sin(x)
  104. double x
  105. The function body may be indented or left-adjusted. The following example
  106. shows a function with its body left-adjusted. Most examples in this
  107. document will indent the body.
  108. CORRECT
  109. double
  110. sin(x)
  111. double x
  112. =head2 The Argument Stack
  113. The argument stack is used to store the values which are
  114. sent as parameters to the XSUB and to store the XSUB's
  115. return value. In reality all Perl functions keep their
  116. values on this stack at the same time, each limited to its
  117. own range of positions on the stack. In this document the
  118. first position on that stack which belongs to the active
  119. function will be referred to as position 0 for that function.
  120. XSUBs refer to their stack arguments with the macro B<ST(x)>, where I<x>
  121. refers to a position in this XSUB's part of the stack. Position 0 for that
  122. function would be known to the XSUB as ST(0). The XSUB's incoming
  123. parameters and outgoing return values always begin at ST(0). For many
  124. simple cases the B<xsubpp> compiler will generate the code necessary to
  125. handle the argument stack by embedding code fragments found in the
  126. typemaps. In more complex cases the programmer must supply the code.
  127. =head2 The RETVAL Variable
  128. The RETVAL variable is a magic variable which always matches
  129. the return type of the C library function. The B<xsubpp> compiler will
  130. supply this variable in each XSUB and by default will use it to hold the
  131. return value of the C library function being called. In simple cases the
  132. value of RETVAL will be placed in ST(0) of the argument stack where it can
  133. be received by Perl as the return value of the XSUB.
  134. If the XSUB has a return type of C<void> then the compiler will
  135. not supply a RETVAL variable for that function. When using
  136. the PPCODE: directive the RETVAL variable is not needed, unless used
  137. explicitly.
  138. If PPCODE: directive is not used, C<void> return value should be used
  139. only for subroutines which do not return a value, I<even if> CODE:
  140. directive is used which sets ST(0) explicitly.
  141. Older versions of this document recommended to use C<void> return
  142. value in such cases. It was discovered that this could lead to
  143. segfaults in cases when XSUB was I<truly> C<void>. This practice is
  144. now deprecated, and may be not supported at some future version. Use
  145. the return value C<SV *> in such cases. (Currently C<xsubpp> contains
  146. some heuristic code which tries to disambiguate between "truly-void"
  147. and "old-practice-declared-as-void" functions. Hence your code is at
  148. mercy of this heuristics unless you use C<SV *> as return value.)
  149. =head2 The MODULE Keyword
  150. The MODULE keyword is used to start the XS code and to
  151. specify the package of the functions which are being
  152. defined. All text preceding the first MODULE keyword is
  153. considered C code and is passed through to the output
  154. untouched. Every XS module will have a bootstrap function
  155. which is used to hook the XSUBs into Perl. The package name
  156. of this bootstrap function will match the value of the last
  157. MODULE statement in the XS source files. The value of
  158. MODULE should always remain constant within the same XS
  159. file, though this is not required.
  160. The following example will start the XS code and will place
  161. all functions in a package named RPC.
  162. MODULE = RPC
  163. =head2 The PACKAGE Keyword
  164. When functions within an XS source file must be separated into packages
  165. the PACKAGE keyword should be used. This keyword is used with the MODULE
  166. keyword and must follow immediately after it when used.
  167. MODULE = RPC PACKAGE = RPC
  168. [ XS code in package RPC ]
  169. MODULE = RPC PACKAGE = RPCB
  170. [ XS code in package RPCB ]
  171. MODULE = RPC PACKAGE = RPC
  172. [ XS code in package RPC ]
  173. Although this keyword is optional and in some cases provides redundant
  174. information it should always be used. This keyword will ensure that the
  175. XSUBs appear in the desired package.
  176. =head2 The PREFIX Keyword
  177. The PREFIX keyword designates prefixes which should be
  178. removed from the Perl function names. If the C function is
  179. C<rpcb_gettime()> and the PREFIX value is C<rpcb_> then Perl will
  180. see this function as C<gettime()>.
  181. This keyword should follow the PACKAGE keyword when used.
  182. If PACKAGE is not used then PREFIX should follow the MODULE
  183. keyword.
  184. MODULE = RPC PREFIX = rpc_
  185. MODULE = RPC PACKAGE = RPCB PREFIX = rpcb_
  186. =head2 The OUTPUT: Keyword
  187. The OUTPUT: keyword indicates that certain function parameters should be
  188. updated (new values made visible to Perl) when the XSUB terminates or that
  189. certain values should be returned to the calling Perl function. For
  190. simple functions, such as the sin() function above, the RETVAL variable is
  191. automatically designated as an output value. In more complex functions
  192. the B<xsubpp> compiler will need help to determine which variables are output
  193. variables.
  194. This keyword will normally be used to complement the CODE: keyword.
  195. The RETVAL variable is not recognized as an output variable when the
  196. CODE: keyword is present. The OUTPUT: keyword is used in this
  197. situation to tell the compiler that RETVAL really is an output
  198. variable.
  199. The OUTPUT: keyword can also be used to indicate that function parameters
  200. are output variables. This may be necessary when a parameter has been
  201. modified within the function and the programmer would like the update to
  202. be seen by Perl.
  203. bool_t
  204. rpcb_gettime(host,timep)
  205. char *host
  206. time_t &timep
  207. OUTPUT:
  208. timep
  209. The OUTPUT: keyword will also allow an output parameter to
  210. be mapped to a matching piece of code rather than to a
  211. typemap.
  212. bool_t
  213. rpcb_gettime(host,timep)
  214. char *host
  215. time_t &timep
  216. OUTPUT:
  217. timep sv_setnv(ST(1), (double)timep);
  218. B<xsubpp> emits an automatic C<SvSETMAGIC()> for all parameters in the
  219. OUTPUT section of the XSUB, except RETVAL. This is the usually desired
  220. behavior, as it takes care of properly invoking 'set' magic on output
  221. parameters (needed for hash or array element parameters that must be
  222. created if they didn't exist). If for some reason, this behavior is
  223. not desired, the OUTPUT section may contain a C<SETMAGIC: DISABLE> line
  224. to disable it for the remainder of the parameters in the OUTPUT section.
  225. Likewise, C<SETMAGIC: ENABLE> can be used to reenable it for the
  226. remainder of the OUTPUT section. See L<perlguts> for more details
  227. about 'set' magic.
  228. =head2 The CODE: Keyword
  229. This keyword is used in more complicated XSUBs which require
  230. special handling for the C function. The RETVAL variable is
  231. available but will not be returned unless it is specified
  232. under the OUTPUT: keyword.
  233. The following XSUB is for a C function which requires special handling of
  234. its parameters. The Perl usage is given first.
  235. $status = rpcb_gettime( "localhost", $timep );
  236. The XSUB follows.
  237. bool_t
  238. rpcb_gettime(host,timep)
  239. char *host
  240. time_t timep
  241. CODE:
  242. RETVAL = rpcb_gettime( host, &timep );
  243. OUTPUT:
  244. timep
  245. RETVAL
  246. =head2 The INIT: Keyword
  247. The INIT: keyword allows initialization to be inserted into the XSUB before
  248. the compiler generates the call to the C function. Unlike the CODE: keyword
  249. above, this keyword does not affect the way the compiler handles RETVAL.
  250. bool_t
  251. rpcb_gettime(host,timep)
  252. char *host
  253. time_t &timep
  254. INIT:
  255. printf("# Host is %s\n", host );
  256. OUTPUT:
  257. timep
  258. =head2 The NO_INIT Keyword
  259. The NO_INIT keyword is used to indicate that a function
  260. parameter is being used only as an output value. The B<xsubpp>
  261. compiler will normally generate code to read the values of
  262. all function parameters from the argument stack and assign
  263. them to C variables upon entry to the function. NO_INIT
  264. will tell the compiler that some parameters will be used for
  265. output rather than for input and that they will be handled
  266. before the function terminates.
  267. The following example shows a variation of the rpcb_gettime() function.
  268. This function uses the timep variable only as an output variable and does
  269. not care about its initial contents.
  270. bool_t
  271. rpcb_gettime(host,timep)
  272. char *host
  273. time_t &timep = NO_INIT
  274. OUTPUT:
  275. timep
  276. =head2 Initializing Function Parameters
  277. Function parameters are normally initialized with their
  278. values from the argument stack. The typemaps contain the
  279. code segments which are used to transfer the Perl values to
  280. the C parameters. The programmer, however, is allowed to
  281. override the typemaps and supply alternate (or additional)
  282. initialization code.
  283. The following code demonstrates how to supply initialization code for
  284. function parameters. The initialization code is eval'd within double
  285. quotes by the compiler before it is added to the output so anything
  286. which should be interpreted literally [mainly C<$>, C<@>, or C<\\>]
  287. must be protected with backslashes. The variables C<$var>, C<$arg>,
  288. and C<$type> can be used as in typemaps.
  289. bool_t
  290. rpcb_gettime(host,timep)
  291. char *host = (char *)SvPV($arg,PL_na);
  292. time_t &timep = 0;
  293. OUTPUT:
  294. timep
  295. This should not be used to supply default values for parameters. One
  296. would normally use this when a function parameter must be processed by
  297. another library function before it can be used. Default parameters are
  298. covered in the next section.
  299. If the initialization begins with C<=>, then it is output on
  300. the same line where the input variable is declared. If the
  301. initialization begins with C<;> or C<+>, then it is output after
  302. all of the input variables have been declared. The C<=> and C<;>
  303. cases replace the initialization normally supplied from the typemap.
  304. For the C<+> case, the initialization from the typemap will precede
  305. the initialization code included after the C<+>. A global
  306. variable, C<%v>, is available for the truly rare case where
  307. information from one initialization is needed in another
  308. initialization.
  309. bool_t
  310. rpcb_gettime(host,timep)
  311. time_t &timep ; /*\$v{time}=@{[$v{time}=$arg]}*/
  312. char *host + SvOK($v{time}) ? SvPV($arg,PL_na) : NULL;
  313. OUTPUT:
  314. timep
  315. =head2 Default Parameter Values
  316. Default values can be specified for function parameters by
  317. placing an assignment statement in the parameter list. The
  318. default value may be a number or a string. Defaults should
  319. always be used on the right-most parameters only.
  320. To allow the XSUB for rpcb_gettime() to have a default host
  321. value the parameters to the XSUB could be rearranged. The
  322. XSUB will then call the real rpcb_gettime() function with
  323. the parameters in the correct order. Perl will call this
  324. XSUB with either of the following statements.
  325. $status = rpcb_gettime( $timep, $host );
  326. $status = rpcb_gettime( $timep );
  327. The XSUB will look like the code which follows. A CODE:
  328. block is used to call the real rpcb_gettime() function with
  329. the parameters in the correct order for that function.
  330. bool_t
  331. rpcb_gettime(timep,host="localhost")
  332. char *host
  333. time_t timep = NO_INIT
  334. CODE:
  335. RETVAL = rpcb_gettime( host, &timep );
  336. OUTPUT:
  337. timep
  338. RETVAL
  339. =head2 The PREINIT: Keyword
  340. The PREINIT: keyword allows extra variables to be declared before the
  341. typemaps are expanded. If a variable is declared in a CODE: block then that
  342. variable will follow any typemap code. This may result in a C syntax
  343. error. To force the variable to be declared before the typemap code, place
  344. it into a PREINIT: block. The PREINIT: keyword may be used one or more
  345. times within an XSUB.
  346. The following examples are equivalent, but if the code is using complex
  347. typemaps then the first example is safer.
  348. bool_t
  349. rpcb_gettime(timep)
  350. time_t timep = NO_INIT
  351. PREINIT:
  352. char *host = "localhost";
  353. CODE:
  354. RETVAL = rpcb_gettime( host, &timep );
  355. OUTPUT:
  356. timep
  357. RETVAL
  358. A correct, but error-prone example.
  359. bool_t
  360. rpcb_gettime(timep)
  361. time_t timep = NO_INIT
  362. CODE:
  363. char *host = "localhost";
  364. RETVAL = rpcb_gettime( host, &timep );
  365. OUTPUT:
  366. timep
  367. RETVAL
  368. =head2 The SCOPE: Keyword
  369. The SCOPE: keyword allows scoping to be enabled for a particular XSUB. If
  370. enabled, the XSUB will invoke ENTER and LEAVE automatically.
  371. To support potentially complex type mappings, if a typemap entry used
  372. by this XSUB contains a comment like C</*scope*/> then scoping will
  373. automatically be enabled for that XSUB.
  374. To enable scoping:
  375. SCOPE: ENABLE
  376. To disable scoping:
  377. SCOPE: DISABLE
  378. =head2 The INPUT: Keyword
  379. The XSUB's parameters are usually evaluated immediately after entering the
  380. XSUB. The INPUT: keyword can be used to force those parameters to be
  381. evaluated a little later. The INPUT: keyword can be used multiple times
  382. within an XSUB and can be used to list one or more input variables. This
  383. keyword is used with the PREINIT: keyword.
  384. The following example shows how the input parameter C<timep> can be
  385. evaluated late, after a PREINIT.
  386. bool_t
  387. rpcb_gettime(host,timep)
  388. char *host
  389. PREINIT:
  390. time_t tt;
  391. INPUT:
  392. time_t timep
  393. CODE:
  394. RETVAL = rpcb_gettime( host, &tt );
  395. timep = tt;
  396. OUTPUT:
  397. timep
  398. RETVAL
  399. The next example shows each input parameter evaluated late.
  400. bool_t
  401. rpcb_gettime(host,timep)
  402. PREINIT:
  403. time_t tt;
  404. INPUT:
  405. char *host
  406. PREINIT:
  407. char *h;
  408. INPUT:
  409. time_t timep
  410. CODE:
  411. h = host;
  412. RETVAL = rpcb_gettime( h, &tt );
  413. timep = tt;
  414. OUTPUT:
  415. timep
  416. RETVAL
  417. =head2 Variable-length Parameter Lists
  418. XSUBs can have variable-length parameter lists by specifying an ellipsis
  419. C<(...)> in the parameter list. This use of the ellipsis is similar to that
  420. found in ANSI C. The programmer is able to determine the number of
  421. arguments passed to the XSUB by examining the C<items> variable which the
  422. B<xsubpp> compiler supplies for all XSUBs. By using this mechanism one can
  423. create an XSUB which accepts a list of parameters of unknown length.
  424. The I<host> parameter for the rpcb_gettime() XSUB can be
  425. optional so the ellipsis can be used to indicate that the
  426. XSUB will take a variable number of parameters. Perl should
  427. be able to call this XSUB with either of the following statements.
  428. $status = rpcb_gettime( $timep, $host );
  429. $status = rpcb_gettime( $timep );
  430. The XS code, with ellipsis, follows.
  431. bool_t
  432. rpcb_gettime(timep, ...)
  433. time_t timep = NO_INIT
  434. PREINIT:
  435. char *host = "localhost";
  436. STRLEN n_a;
  437. CODE:
  438. if( items > 1 )
  439. host = (char *)SvPV(ST(1), n_a);
  440. RETVAL = rpcb_gettime( host, &timep );
  441. OUTPUT:
  442. timep
  443. RETVAL
  444. =head2 The C_ARGS: Keyword
  445. The C_ARGS: keyword allows creating of XSUBS which have different
  446. calling sequence from Perl than from C, without a need to write
  447. CODE: or CPPCODE: section. The contents of the C_ARGS: paragraph is
  448. put as the argument to the called C function without any change.
  449. For example, suppose that C function is declared as
  450. symbolic nth_derivative(int n, symbolic function, int flags);
  451. and that the default flags are kept in a global C variable
  452. C<default_flags>. Suppose that you want to create an interface which
  453. is called as
  454. $second_deriv = $function->nth_derivative(2);
  455. To do this, declare the XSUB as
  456. symbolic
  457. nth_derivative(function, n)
  458. symbolic function
  459. int n
  460. C_ARGS:
  461. n, function, default_flags
  462. =head2 The PPCODE: Keyword
  463. The PPCODE: keyword is an alternate form of the CODE: keyword and is used
  464. to tell the B<xsubpp> compiler that the programmer is supplying the code to
  465. control the argument stack for the XSUBs return values. Occasionally one
  466. will want an XSUB to return a list of values rather than a single value.
  467. In these cases one must use PPCODE: and then explicitly push the list of
  468. values on the stack. The PPCODE: and CODE: keywords are not used
  469. together within the same XSUB.
  470. The following XSUB will call the C rpcb_gettime() function
  471. and will return its two output values, timep and status, to
  472. Perl as a single list.
  473. void
  474. rpcb_gettime(host)
  475. char *host
  476. PREINIT:
  477. time_t timep;
  478. bool_t status;
  479. PPCODE:
  480. status = rpcb_gettime( host, &timep );
  481. EXTEND(SP, 2);
  482. PUSHs(sv_2mortal(newSViv(status)));
  483. PUSHs(sv_2mortal(newSViv(timep)));
  484. Notice that the programmer must supply the C code necessary
  485. to have the real rpcb_gettime() function called and to have
  486. the return values properly placed on the argument stack.
  487. The C<void> return type for this function tells the B<xsubpp> compiler that
  488. the RETVAL variable is not needed or used and that it should not be created.
  489. In most scenarios the void return type should be used with the PPCODE:
  490. directive.
  491. The EXTEND() macro is used to make room on the argument
  492. stack for 2 return values. The PPCODE: directive causes the
  493. B<xsubpp> compiler to create a stack pointer available as C<SP>, and it
  494. is this pointer which is being used in the EXTEND() macro.
  495. The values are then pushed onto the stack with the PUSHs()
  496. macro.
  497. Now the rpcb_gettime() function can be used from Perl with
  498. the following statement.
  499. ($status, $timep) = rpcb_gettime("localhost");
  500. When handling output parameters with a PPCODE section, be sure to handle
  501. 'set' magic properly. See L<perlguts> for details about 'set' magic.
  502. =head2 Returning Undef And Empty Lists
  503. Occasionally the programmer will want to return simply
  504. C<undef> or an empty list if a function fails rather than a
  505. separate status value. The rpcb_gettime() function offers
  506. just this situation. If the function succeeds we would like
  507. to have it return the time and if it fails we would like to
  508. have undef returned. In the following Perl code the value
  509. of $timep will either be undef or it will be a valid time.
  510. $timep = rpcb_gettime( "localhost" );
  511. The following XSUB uses the C<SV *> return type as a mnemonic only,
  512. and uses a CODE: block to indicate to the compiler
  513. that the programmer has supplied all the necessary code. The
  514. sv_newmortal() call will initialize the return value to undef, making that
  515. the default return value.
  516. SV *
  517. rpcb_gettime(host)
  518. char * host
  519. PREINIT:
  520. time_t timep;
  521. bool_t x;
  522. CODE:
  523. ST(0) = sv_newmortal();
  524. if( rpcb_gettime( host, &timep ) )
  525. sv_setnv( ST(0), (double)timep);
  526. The next example demonstrates how one would place an explicit undef in the
  527. return value, should the need arise.
  528. SV *
  529. rpcb_gettime(host)
  530. char * host
  531. PREINIT:
  532. time_t timep;
  533. bool_t x;
  534. CODE:
  535. ST(0) = sv_newmortal();
  536. if( rpcb_gettime( host, &timep ) ){
  537. sv_setnv( ST(0), (double)timep);
  538. }
  539. else{
  540. ST(0) = &PL_sv_undef;
  541. }
  542. To return an empty list one must use a PPCODE: block and
  543. then not push return values on the stack.
  544. void
  545. rpcb_gettime(host)
  546. char *host
  547. PREINIT:
  548. time_t timep;
  549. PPCODE:
  550. if( rpcb_gettime( host, &timep ) )
  551. PUSHs(sv_2mortal(newSViv(timep)));
  552. else{
  553. /* Nothing pushed on stack, so an empty */
  554. /* list is implicitly returned. */
  555. }
  556. Some people may be inclined to include an explicit C<return> in the above
  557. XSUB, rather than letting control fall through to the end. In those
  558. situations C<XSRETURN_EMPTY> should be used, instead. This will ensure that
  559. the XSUB stack is properly adjusted. Consult L<perlguts/"API LISTING"> for
  560. other C<XSRETURN> macros.
  561. =head2 The REQUIRE: Keyword
  562. The REQUIRE: keyword is used to indicate the minimum version of the
  563. B<xsubpp> compiler needed to compile the XS module. An XS module which
  564. contains the following statement will compile with only B<xsubpp> version
  565. 1.922 or greater:
  566. REQUIRE: 1.922
  567. =head2 The CLEANUP: Keyword
  568. This keyword can be used when an XSUB requires special cleanup procedures
  569. before it terminates. When the CLEANUP: keyword is used it must follow
  570. any CODE:, PPCODE:, or OUTPUT: blocks which are present in the XSUB. The
  571. code specified for the cleanup block will be added as the last statements
  572. in the XSUB.
  573. =head2 The BOOT: Keyword
  574. The BOOT: keyword is used to add code to the extension's bootstrap
  575. function. The bootstrap function is generated by the B<xsubpp> compiler and
  576. normally holds the statements necessary to register any XSUBs with Perl.
  577. With the BOOT: keyword the programmer can tell the compiler to add extra
  578. statements to the bootstrap function.
  579. This keyword may be used any time after the first MODULE keyword and should
  580. appear on a line by itself. The first blank line after the keyword will
  581. terminate the code block.
  582. BOOT:
  583. # The following message will be printed when the
  584. # bootstrap function executes.
  585. printf("Hello from the bootstrap!\n");
  586. =head2 The VERSIONCHECK: Keyword
  587. The VERSIONCHECK: keyword corresponds to B<xsubpp>'s C<-versioncheck> and
  588. C<-noversioncheck> options. This keyword overrides the command line
  589. options. Version checking is enabled by default. When version checking is
  590. enabled the XS module will attempt to verify that its version matches the
  591. version of the PM module.
  592. To enable version checking:
  593. VERSIONCHECK: ENABLE
  594. To disable version checking:
  595. VERSIONCHECK: DISABLE
  596. =head2 The PROTOTYPES: Keyword
  597. The PROTOTYPES: keyword corresponds to B<xsubpp>'s C<-prototypes> and
  598. C<-noprototypes> options. This keyword overrides the command line options.
  599. Prototypes are enabled by default. When prototypes are enabled XSUBs will
  600. be given Perl prototypes. This keyword may be used multiple times in an XS
  601. module to enable and disable prototypes for different parts of the module.
  602. To enable prototypes:
  603. PROTOTYPES: ENABLE
  604. To disable prototypes:
  605. PROTOTYPES: DISABLE
  606. =head2 The PROTOTYPE: Keyword
  607. This keyword is similar to the PROTOTYPES: keyword above but can be used to
  608. force B<xsubpp> to use a specific prototype for the XSUB. This keyword
  609. overrides all other prototype options and keywords but affects only the
  610. current XSUB. Consult L<perlsub/Prototypes> for information about Perl
  611. prototypes.
  612. bool_t
  613. rpcb_gettime(timep, ...)
  614. time_t timep = NO_INIT
  615. PROTOTYPE: $;$
  616. PREINIT:
  617. char *host = "localhost";
  618. STRLEN n_a;
  619. CODE:
  620. if( items > 1 )
  621. host = (char *)SvPV(ST(1), n_a);
  622. RETVAL = rpcb_gettime( host, &timep );
  623. OUTPUT:
  624. timep
  625. RETVAL
  626. =head2 The ALIAS: Keyword
  627. The ALIAS: keyword allows an XSUB to have two or more unique Perl names
  628. and to know which of those names was used when it was invoked. The Perl
  629. names may be fully-qualified with package names. Each alias is given an
  630. index. The compiler will setup a variable called C<ix> which contain the
  631. index of the alias which was used. When the XSUB is called with its
  632. declared name C<ix> will be 0.
  633. The following example will create aliases C<FOO::gettime()> and
  634. C<BAR::getit()> for this function.
  635. bool_t
  636. rpcb_gettime(host,timep)
  637. char *host
  638. time_t &timep
  639. ALIAS:
  640. FOO::gettime = 1
  641. BAR::getit = 2
  642. INIT:
  643. printf("# ix = %d\n", ix );
  644. OUTPUT:
  645. timep
  646. =head2 The INTERFACE: Keyword
  647. This keyword declares the current XSUB as a keeper of the given
  648. calling signature. If some text follows this keyword, it is
  649. considered as a list of functions which have this signature, and
  650. should be attached to XSUBs.
  651. Say, if you have 4 functions multiply(), divide(), add(), subtract() all
  652. having the signature
  653. symbolic f(symbolic, symbolic);
  654. you code them all by using XSUB
  655. symbolic
  656. interface_s_ss(arg1, arg2)
  657. symbolic arg1
  658. symbolic arg2
  659. INTERFACE:
  660. multiply divide
  661. add subtract
  662. The advantage of this approach comparing to ALIAS: keyword is that one
  663. can attach an extra function remainder() at runtime by using
  664. CV *mycv = newXSproto("Symbolic::remainder",
  665. XS_Symbolic_interface_s_ss, __FILE__, "$$");
  666. XSINTERFACE_FUNC_SET(mycv, remainder);
  667. (This example supposes that there was no INTERFACE_MACRO: section,
  668. otherwise one needs to use something else instead of
  669. C<XSINTERFACE_FUNC_SET>.)
  670. =head2 The INTERFACE_MACRO: Keyword
  671. This keyword allows one to define an INTERFACE using a different way
  672. to extract a function pointer from an XSUB. The text which follows
  673. this keyword should give the name of macros which would extract/set a
  674. function pointer. The extractor macro is given return type, C<CV*>,
  675. and C<XSANY.any_dptr> for this C<CV*>. The setter macro is given cv,
  676. and the function pointer.
  677. The default value is C<XSINTERFACE_FUNC> and C<XSINTERFACE_FUNC_SET>.
  678. An INTERFACE keyword with an empty list of functions can be omitted if
  679. INTERFACE_MACRO keyword is used.
  680. Suppose that in the previous example functions pointers for
  681. multiply(), divide(), add(), subtract() are kept in a global C array
  682. C<fp[]> with offsets being C<multiply_off>, C<divide_off>, C<add_off>,
  683. C<subtract_off>. Then one can use
  684. #define XSINTERFACE_FUNC_BYOFFSET(ret,cv,f) \
  685. ((XSINTERFACE_CVT(ret,))fp[CvXSUBANY(cv).any_i32])
  686. #define XSINTERFACE_FUNC_BYOFFSET_set(cv,f) \
  687. CvXSUBANY(cv).any_i32 = CAT2( f, _off )
  688. in C section,
  689. symbolic
  690. interface_s_ss(arg1, arg2)
  691. symbolic arg1
  692. symbolic arg2
  693. INTERFACE_MACRO:
  694. XSINTERFACE_FUNC_BYOFFSET
  695. XSINTERFACE_FUNC_BYOFFSET_set
  696. INTERFACE:
  697. multiply divide
  698. add subtract
  699. in XSUB section.
  700. =head2 The INCLUDE: Keyword
  701. This keyword can be used to pull other files into the XS module. The other
  702. files may have XS code. INCLUDE: can also be used to run a command to
  703. generate the XS code to be pulled into the module.
  704. The file F<Rpcb1.xsh> contains our C<rpcb_gettime()> function:
  705. bool_t
  706. rpcb_gettime(host,timep)
  707. char *host
  708. time_t &timep
  709. OUTPUT:
  710. timep
  711. The XS module can use INCLUDE: to pull that file into it.
  712. INCLUDE: Rpcb1.xsh
  713. If the parameters to the INCLUDE: keyword are followed by a pipe (C<|>) then
  714. the compiler will interpret the parameters as a command.
  715. INCLUDE: cat Rpcb1.xsh |
  716. =head2 The CASE: Keyword
  717. The CASE: keyword allows an XSUB to have multiple distinct parts with each
  718. part acting as a virtual XSUB. CASE: is greedy and if it is used then all
  719. other XS keywords must be contained within a CASE:. This means nothing may
  720. precede the first CASE: in the XSUB and anything following the last CASE: is
  721. included in that case.
  722. A CASE: might switch via a parameter of the XSUB, via the C<ix> ALIAS:
  723. variable (see L<"The ALIAS: Keyword">), or maybe via the C<items> variable
  724. (see L<"Variable-length Parameter Lists">). The last CASE: becomes the
  725. B<default> case if it is not associated with a conditional. The following
  726. example shows CASE switched via C<ix> with a function C<rpcb_gettime()>
  727. having an alias C<x_gettime()>. When the function is called as
  728. C<rpcb_gettime()> its parameters are the usual C<(char *host, time_t *timep)>,
  729. but when the function is called as C<x_gettime()> its parameters are
  730. reversed, C<(time_t *timep, char *host)>.
  731. long
  732. rpcb_gettime(a,b)
  733. CASE: ix == 1
  734. ALIAS:
  735. x_gettime = 1
  736. INPUT:
  737. # 'a' is timep, 'b' is host
  738. char *b
  739. time_t a = NO_INIT
  740. CODE:
  741. RETVAL = rpcb_gettime( b, &a );
  742. OUTPUT:
  743. a
  744. RETVAL
  745. CASE:
  746. # 'a' is host, 'b' is timep
  747. char *a
  748. time_t &b = NO_INIT
  749. OUTPUT:
  750. b
  751. RETVAL
  752. That function can be called with either of the following statements. Note
  753. the different argument lists.
  754. $status = rpcb_gettime( $host, $timep );
  755. $status = x_gettime( $timep, $host );
  756. =head2 The & Unary Operator
  757. The & unary operator is used to tell the compiler that it should dereference
  758. the object when it calls the C function. This is used when a CODE: block is
  759. not used and the object is a not a pointer type (the object is an C<int> or
  760. C<long> but not a C<int*> or C<long*>).
  761. The following XSUB will generate incorrect C code. The xsubpp compiler will
  762. turn this into code which calls C<rpcb_gettime()> with parameters C<(char
  763. *host, time_t timep)>, but the real C<rpcb_gettime()> wants the C<timep>
  764. parameter to be of type C<time_t*> rather than C<time_t>.
  765. bool_t
  766. rpcb_gettime(host,timep)
  767. char *host
  768. time_t timep
  769. OUTPUT:
  770. timep
  771. That problem is corrected by using the C<&> operator. The xsubpp compiler
  772. will now turn this into code which calls C<rpcb_gettime()> correctly with
  773. parameters C<(char *host, time_t *timep)>. It does this by carrying the
  774. C<&> through, so the function call looks like C<rpcb_gettime(host, &timep)>.
  775. bool_t
  776. rpcb_gettime(host,timep)
  777. char *host
  778. time_t &timep
  779. OUTPUT:
  780. timep
  781. =head2 Inserting Comments and C Preprocessor Directives
  782. C preprocessor directives are allowed within BOOT:, PREINIT: INIT:,
  783. CODE:, PPCODE:, and CLEANUP: blocks, as well as outside the functions.
  784. Comments are allowed anywhere after the MODULE keyword. The compiler
  785. will pass the preprocessor directives through untouched and will remove
  786. the commented lines.
  787. Comments can be added to XSUBs by placing a C<#> as the first
  788. non-whitespace of a line. Care should be taken to avoid making the
  789. comment look like a C preprocessor directive, lest it be interpreted as
  790. such. The simplest way to prevent this is to put whitespace in front of
  791. the C<#>.
  792. If you use preprocessor directives to choose one of two
  793. versions of a function, use
  794. #if ... version1
  795. #else /* ... version2 */
  796. #endif
  797. and not
  798. #if ... version1
  799. #endif
  800. #if ... version2
  801. #endif
  802. because otherwise xsubpp will believe that you made a duplicate
  803. definition of the function. Also, put a blank line before the
  804. #else/#endif so it will not be seen as part of the function body.
  805. =head2 Using XS With C++
  806. If a function is defined as a C++ method then it will assume
  807. its first argument is an object pointer. The object pointer
  808. will be stored in a variable called THIS. The object should
  809. have been created by C++ with the new() function and should
  810. be blessed by Perl with the sv_setref_pv() macro. The
  811. blessing of the object by Perl can be handled by a typemap. An example
  812. typemap is shown at the end of this section.
  813. If the method is defined as static it will call the C++
  814. function using the class::method() syntax. If the method is not static
  815. the function will be called using the THIS-E<gt>method() syntax.
  816. The next examples will use the following C++ class.
  817. class color {
  818. public:
  819. color();
  820. ~color();
  821. int blue();
  822. void set_blue( int );
  823. private:
  824. int c_blue;
  825. };
  826. The XSUBs for the blue() and set_blue() methods are defined with the class
  827. name but the parameter for the object (THIS, or "self") is implicit and is
  828. not listed.
  829. int
  830. color::blue()
  831. void
  832. color::set_blue( val )
  833. int val
  834. Both functions will expect an object as the first parameter. The xsubpp
  835. compiler will call that object C<THIS> and will use it to call the specified
  836. method. So in the C++ code the blue() and set_blue() methods will be called
  837. in the following manner.
  838. RETVAL = THIS->blue();
  839. THIS->set_blue( val );
  840. If the function's name is B<DESTROY> then the C++ C<delete> function will be
  841. called and C<THIS> will be given as its parameter.
  842. void
  843. color::DESTROY()
  844. The C++ code will call C<delete>.
  845. delete THIS;
  846. If the function's name is B<new> then the C++ C<new> function will be called
  847. to create a dynamic C++ object. The XSUB will expect the class name, which
  848. will be kept in a variable called C<CLASS>, to be given as the first
  849. argument.
  850. color *
  851. color::new()
  852. The C++ code will call C<new>.
  853. RETVAL = new color();
  854. The following is an example of a typemap that could be used for this C++
  855. example.
  856. TYPEMAP
  857. color * O_OBJECT
  858. OUTPUT
  859. # The Perl object is blessed into 'CLASS', which should be a
  860. # char* having the name of the package for the blessing.
  861. O_OBJECT
  862. sv_setref_pv( $arg, CLASS, (void*)$var );
  863. INPUT
  864. O_OBJECT
  865. if( sv_isobject($arg) && (SvTYPE(SvRV($arg)) == SVt_PVMG) )
  866. $var = ($type)SvIV((SV*)SvRV( $arg ));
  867. else{
  868. warn( \"${Package}::$func_name() -- $var is not a blessed SV reference\" );
  869. XSRETURN_UNDEF;
  870. }
  871. =head2 Interface Strategy
  872. When designing an interface between Perl and a C library a straight
  873. translation from C to XS is often sufficient. The interface will often be
  874. very C-like and occasionally nonintuitive, especially when the C function
  875. modifies one of its parameters. In cases where the programmer wishes to
  876. create a more Perl-like interface the following strategy may help to
  877. identify the more critical parts of the interface.
  878. Identify the C functions which modify their parameters. The XSUBs for
  879. these functions may be able to return lists to Perl, or may be
  880. candidates to return undef or an empty list in case of failure.
  881. Identify which values are used by only the C and XSUB functions
  882. themselves. If Perl does not need to access the contents of the value
  883. then it may not be necessary to provide a translation for that value
  884. from C to Perl.
  885. Identify the pointers in the C function parameter lists and return
  886. values. Some pointers can be handled in XS with the & unary operator on
  887. the variable name while others will require the use of the * operator on
  888. the type name. In general it is easier to work with the & operator.
  889. Identify the structures used by the C functions. In many
  890. cases it may be helpful to use the T_PTROBJ typemap for
  891. these structures so they can be manipulated by Perl as
  892. blessed objects.
  893. =head2 Perl Objects And C Structures
  894. When dealing with C structures one should select either
  895. B<T_PTROBJ> or B<T_PTRREF> for the XS type. Both types are
  896. designed to handle pointers to complex objects. The
  897. T_PTRREF type will allow the Perl object to be unblessed
  898. while the T_PTROBJ type requires that the object be blessed.
  899. By using T_PTROBJ one can achieve a form of type-checking
  900. because the XSUB will attempt to verify that the Perl object
  901. is of the expected type.
  902. The following XS code shows the getnetconfigent() function which is used
  903. with ONC+ TIRPC. The getnetconfigent() function will return a pointer to a
  904. C structure and has the C prototype shown below. The example will
  905. demonstrate how the C pointer will become a Perl reference. Perl will
  906. consider this reference to be a pointer to a blessed object and will
  907. attempt to call a destructor for the object. A destructor will be
  908. provided in the XS source to free the memory used by getnetconfigent().
  909. Destructors in XS can be created by specifying an XSUB function whose name
  910. ends with the word B<DESTROY>. XS destructors can be used to free memory
  911. which may have been malloc'd by another XSUB.
  912. struct netconfig *getnetconfigent(const char *netid);
  913. A C<typedef> will be created for C<struct netconfig>. The Perl
  914. object will be blessed in a class matching the name of the C
  915. type, with the tag C<Ptr> appended, and the name should not
  916. have embedded spaces if it will be a Perl package name. The
  917. destructor will be placed in a class corresponding to the
  918. class of the object and the PREFIX keyword will be used to
  919. trim the name to the word DESTROY as Perl will expect.
  920. typedef struct netconfig Netconfig;
  921. MODULE = RPC PACKAGE = RPC
  922. Netconfig *
  923. getnetconfigent(netid)
  924. char *netid
  925. MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
  926. void
  927. rpcb_DESTROY(netconf)
  928. Netconfig *netconf
  929. CODE:
  930. printf("Now in NetconfigPtr::DESTROY\n");
  931. free( netconf );
  932. This example requires the following typemap entry. Consult the typemap
  933. section for more information about adding new typemaps for an extension.
  934. TYPEMAP
  935. Netconfig * T_PTROBJ
  936. This example will be used with the following Perl statements.
  937. use RPC;
  938. $netconf = getnetconfigent("udp");
  939. When Perl destroys the object referenced by $netconf it will send the
  940. object to the supplied XSUB DESTROY function. Perl cannot determine, and
  941. does not care, that this object is a C struct and not a Perl object. In
  942. this sense, there is no difference between the object created by the
  943. getnetconfigent() XSUB and an object created by a normal Perl subroutine.
  944. =head2 The Typemap
  945. The typemap is a collection of code fragments which are used by the B<xsubpp>
  946. compiler to map C function parameters and values to Perl values. The
  947. typemap file may consist of three sections labeled C<TYPEMAP>, C<INPUT>, and
  948. C<OUTPUT>. Any unlabelled initial section is assumed to be a C<TYPEMAP>
  949. section if a name is not explicitly specified. The INPUT section tells
  950. the compiler how to translate Perl values
  951. into variables of certain C types. The OUTPUT section tells the compiler
  952. how to translate the values from certain C types into values Perl can
  953. understand. The TYPEMAP section tells the compiler which of the INPUT and
  954. OUTPUT code fragments should be used to map a given C type to a Perl value.
  955. The section labels C<TYPEMAP>, C<INPUT>, or C<OUTPUT> must begin
  956. in the first column on a line by themselves, and must be in uppercase.
  957. The default typemap in the C<ext> directory of the Perl source contains many
  958. useful types which can be used by Perl extensions. Some extensions define
  959. additional typemaps which they keep in their own directory. These
  960. additional typemaps may reference INPUT and OUTPUT maps in the main
  961. typemap. The B<xsubpp> compiler will allow the extension's own typemap to
  962. override any mappings which are in the default typemap.
  963. Most extensions which require a custom typemap will need only the TYPEMAP
  964. section of the typemap file. The custom typemap used in the
  965. getnetconfigent() example shown earlier demonstrates what may be the typical
  966. use of extension typemaps. That typemap is used to equate a C structure
  967. with the T_PTROBJ typemap. The typemap used by getnetconfigent() is shown
  968. here. Note that the C type is separated from the XS type with a tab and
  969. that the C unary operator C<*> is considered to be a part of the C type name.
  970. TYPEMAP
  971. Netconfig *<tab>T_PTROBJ
  972. Here's a more complicated example: suppose that you wanted C<struct
  973. netconfig> to be blessed into the class C<Net::Config>. One way to do
  974. this is to use underscores (_) to separate package names, as follows:
  975. typedef struct netconfig * Net_Config;
  976. And then provide a typemap entry C<T_PTROBJ_SPECIAL> that maps underscores to
  977. double-colons (::), and declare C<Net_Config> to be of that type:
  978. TYPEMAP
  979. Net_Config T_PTROBJ_SPECIAL
  980. INPUT
  981. T_PTROBJ_SPECIAL
  982. if (sv_derived_from($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")) {
  983. IV tmp = SvIV((SV*)SvRV($arg));
  984. $var = ($type) tmp;
  985. }
  986. else
  987. croak(\"$var is not of type ${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")
  988. OUTPUT
  989. T_PTROBJ_SPECIAL
  990. sv_setref_pv($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\",
  991. (void*)$var);
  992. The INPUT and OUTPUT sections substitute underscores for double-colons
  993. on the fly, giving the desired effect. This example demonstrates some
  994. of the power and versatility of the typemap facility.
  995. =head1 EXAMPLES
  996. File C<RPC.xs>: Interface to some ONC+ RPC bind library functions.
  997. #include "EXTERN.h"
  998. #include "perl.h"
  999. #include "XSUB.h"
  1000. #include <rpc/rpc.h>
  1001. typedef struct netconfig Netconfig;
  1002. MODULE = RPC PACKAGE = RPC
  1003. SV *
  1004. rpcb_gettime(host="localhost")
  1005. char *host
  1006. PREINIT:
  1007. time_t timep;
  1008. CODE:
  1009. ST(0) = sv_newmortal();
  1010. if( rpcb_gettime( host, &timep ) )
  1011. sv_setnv( ST(0), (double)timep );
  1012. Netconfig *
  1013. getnetconfigent(netid="udp")
  1014. char *netid
  1015. MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
  1016. void
  1017. rpcb_DESTROY(netconf)
  1018. Netconfig *netconf
  1019. CODE:
  1020. printf("NetconfigPtr::DESTROY\n");
  1021. free( netconf );
  1022. File C<typemap>: Custom typemap for RPC.xs.
  1023. TYPEMAP
  1024. Netconfig * T_PTROBJ
  1025. File C<RPC.pm>: Perl module for the RPC extension.
  1026. package RPC;
  1027. require Exporter;
  1028. require DynaLoader;
  1029. @ISA = qw(Exporter DynaLoader);
  1030. @EXPORT = qw(rpcb_gettime getnetconfigent);
  1031. bootstrap RPC;
  1032. 1;
  1033. File C<rpctest.pl>: Perl test program for the RPC extension.
  1034. use RPC;
  1035. $netconf = getnetconfigent();
  1036. $a = rpcb_gettime();
  1037. print "time = $a\n";
  1038. print "netconf = $netconf\n";
  1039. $netconf = getnetconfigent("tcp");
  1040. $a = rpcb_gettime("poplar");
  1041. print "time = $a\n";
  1042. print "netconf = $netconf\n";
  1043. =head1 XS VERSION
  1044. This document covers features supported by C<xsubpp> 1.935.
  1045. =head1 AUTHOR
  1046. Dean Roehrich <F<[email protected]>>
  1047. Jul 8, 1996