home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl501m.zip / patches / patch.1f < prev    next >
Text File  |  1995-05-31  |  114KB  |  3,621 lines

  1. # This is my patch  patch.1f for perl5.001.  See description below.
  2. #    Andy Dougherty        doughera@lafcol.lafayette.edu
  3. #
  4. exit 0
  5.  
  6. This is my patch  patch.1f  for perl5.001.
  7.  
  8. To apply, change to your perl directory, and apply with 
  9.     patch -p1 -N  < thispatch.
  10.  
  11. This patch only includes updates for perlapi.pod, perlbot.pod,
  12. perlcall.pod, and perlguts.pod from the authors.
  13.  
  14. After you apply this patch, you should apply patch.1g, patch.1h, and
  15. patch.1i, then reConfigure and build.
  16.  
  17. Patch and enjoy,
  18.  
  19.     Andy Dougherty            doughera@lafcol.lafayette.edu
  20.     Dept. of Physics
  21.     Lafayette College, Easton PA
  22.  
  23. Index: pod/perlapi.pod
  24. *** perl5.001e/pod/perlapi.pod    Wed Feb 22 18:32:28 1995
  25. --- perl5.001f/pod/perlapi.pod    Wed May 31 10:28:06 1995
  26. ***************
  27. *** 100,105 ****
  28. --- 100,110 ----
  29.   allow the programmer to create a more Perl-like interface to the C
  30.   function.
  31.   
  32. + It is recommended that the B<h2xs> tool be used when creating new
  33. + extensions.  This tool will generate template source files and Makefiles.
  34. + This is discussed in more detail in the section titled "Creating A New
  35. + Extension" and in the B<h2xs> manpage.
  36.   =head2 The Anatomy of an XSUB
  37.   
  38.   The following XSUB allows a Perl program to access a  C  library  function  called  sin().  The XSUB will imitate the C
  39. ***************
  40. *** 277,283 ****
  41.   
  42.   The XSUB follows. 
  43.   
  44. !     bool_t rpcb_gettime(host,timep)
  45.             char *  host
  46.             time_t  timep
  47.             CODE:
  48. --- 282,289 ----
  49.   
  50.   The XSUB follows. 
  51.   
  52. !      bool_t
  53. !      rpcb_gettime(host,timep)
  54.             char *  host
  55.             time_t  timep
  56.             CODE:
  57. ***************
  58. *** 294,300 ****
  59.   =head2 The NO_INIT Keyword
  60.   
  61.   The NO_INIT keyword is used to indicate that a function
  62. ! parameter is being used only as an output value.  The B<xsubpp>
  63.   compiler will normally generate code to read the values of
  64.   all function parameters from the argument stack and assign
  65.   them to C variables upon entry to the function.  NO_INIT
  66. --- 300,306 ----
  67.   =head2 The NO_INIT Keyword
  68.   
  69.   The NO_INIT keyword is used to indicate that a function
  70. ! parameter is being used as only an output value.  The B<xsubpp>
  71.   compiler will normally generate code to read the values of
  72.   all function parameters from the argument stack and assign
  73.   them to C variables upon entry to the function.  NO_INIT
  74. ***************
  75. *** 303,309 ****
  76.   before the function terminates.
  77.   
  78.   The following example shows a variation of the rpcb_gettime() function.
  79. ! This function uses the timep variable only as an output variable and does
  80.   not care about its initial contents.
  81.   
  82.        bool_t
  83. --- 309,315 ----
  84.   before the function terminates.
  85.   
  86.   The following example shows a variation of the rpcb_gettime() function.
  87. ! This function uses the timep variable as only an output variable and does
  88.   not care about its initial contents.
  89.   
  90.        bool_t
  91. ***************
  92. *** 382,388 ****
  93.   The I<host> parameter for the rpcb_gettime() XSUB can be
  94.   optional so the ellipsis can be used to indicate that the
  95.   XSUB will take a variable number of parameters.  Perl should
  96. ! be able to call this XSUB with either of the following statments.
  97.   
  98.        $status = rpcb_gettime( $timep, $host );
  99.   
  100. --- 388,394 ----
  101.   The I<host> parameter for the rpcb_gettime() XSUB can be
  102.   optional so the ellipsis can be used to indicate that the
  103.   XSUB will take a variable number of parameters.  Perl should
  104. ! be able to call this XSUB with either of the following statements.
  105.   
  106.        $status = rpcb_gettime( $timep, $host );
  107.   
  108. ***************
  109. *** 409,415 ****
  110.   
  111.   The PPCODE: keyword is an alternate form of the CODE: keyword and is used
  112.   to tell the B<xsubpp> compiler that the programmer is supplying the code to
  113. ! control the argument stack for the XSUBs return values.  Occassionally one
  114.   will want an XSUB to return a list of values rather than a single value.
  115.   In these cases one must use PPCODE: and then explicitly push the list of
  116.   values on the stack.  The PPCODE: and CODE:  keywords are not used
  117. --- 415,421 ----
  118.   
  119.   The PPCODE: keyword is an alternate form of the CODE: keyword and is used
  120.   to tell the B<xsubpp> compiler that the programmer is supplying the code to
  121. ! control the argument stack for the XSUBs return values.  Occasionally one
  122.   will want an XSUB to return a list of values rather than a single value.
  123.   In these cases one must use PPCODE: and then explicitly push the list of
  124.   values on the stack.  The PPCODE: and CODE:  keywords are not used
  125. ***************
  126. *** 419,425 ****
  127.   and will return its two output values, timep and status, to
  128.   Perl as a single list.
  129.   
  130. !     void rpcb_gettime(host)
  131.             char *  host
  132.             PPCODE:
  133.             {
  134. --- 425,432 ----
  135.   and will return its two output values, timep and status, to
  136.   Perl as a single list.
  137.   
  138. !      void
  139. !      rpcb_gettime(host)
  140.             char *  host
  141.             PPCODE:
  142.             {
  143. ***************
  144. *** 454,460 ****
  145.   
  146.   =head2 Returning Undef And Empty Lists
  147.   
  148. ! Occassionally the programmer will want to simply return
  149.   C<undef> or an empty list if a function fails rather than a
  150.   separate status value.  The rpcb_gettime() function offers
  151.   just this situation.  If the function succeeds we would like
  152. --- 461,467 ----
  153.   
  154.   =head2 Returning Undef And Empty Lists
  155.   
  156. ! Occasionally the programmer will want to simply return
  157.   C<undef> or an empty list if a function fails rather than a
  158.   separate status value.  The rpcb_gettime() function offers
  159.   just this situation.  If the function succeeds we would like
  160. ***************
  161. *** 611,617 ****
  162.   variable.  This can then be dereferenced with SvPVX(), SvNVX(), or
  163.   SvIVX().  The following XSUB will use SvRV().
  164.   
  165. !     void rpcb_gettime()
  166.             PPCODE:
  167.             {
  168.             char *host;
  169. --- 618,625 ----
  170.   variable.  This can then be dereferenced with SvPVX(), SvNVX(), or
  171.   SvIVX().  The following XSUB will use SvRV().
  172.   
  173. !      void
  174. !      rpcb_gettime()
  175.             PPCODE:
  176.             {
  177.             char *host;
  178. ***************
  179. *** 645,651 ****
  180.   XSUBs may use B<perl_get_av()>, B<perl_get_hv()>, and B<perl_get_cv()> to
  181.   access Perl arrays, hashes, and code values.
  182.   
  183. ! =head2 Interface Stategy
  184.   
  185.   When designing an interface between Perl and a C library a straight
  186.   translation from C to XS is often sufficient.  The interface will often be
  187. --- 653,659 ----
  188.   XSUBs may use B<perl_get_av()>, B<perl_get_hv()>, and B<perl_get_cv()> to
  189.   access Perl arrays, hashes, and code values.
  190.   
  191. ! =head2 Interface Strategy
  192.   
  193.   When designing an interface between Perl and a C library a straight
  194.   translation from C to XS is often sufficient.  The interface will often be
  195. ***************
  196. *** 658,664 ****
  197.   these functions may be able to return lists to Perl, or may be
  198.   candidates to return undef or an empty list in case of failure.
  199.   
  200. ! Identify which values are used only by the C and XSUB functions
  201.   themselves.  If Perl does not need to access the contents of the value
  202.   then it may not be necessary to provide a translation for that value
  203.   from C to Perl.
  204. --- 666,672 ----
  205.   these functions may be able to return lists to Perl, or may be
  206.   candidates to return undef or an empty list in case of failure.
  207.   
  208. ! Identify which values are used by only the C and XSUB functions
  209.   themselves.  If Perl does not need to access the contents of the value
  210.   then it may not be necessary to provide a translation for that value
  211.   from C to Perl.
  212. ***************
  213. *** 716,722 ****
  214.   T_PTRREF type will allow the Perl object to be unblessed
  215.   while the T_PTROBJ type requires that the object be blessed.
  216.   By using T_PTROBJ one can achieve a form of type-checking
  217. ! since the XSUB will attempt to verify that the Perl object
  218.   is of the expected type.
  219.   
  220.   The following XS code shows the getnetconfigent() function which is used
  221. --- 724,730 ----
  222.   T_PTRREF type will allow the Perl object to be unblessed
  223.   while the T_PTROBJ type requires that the object be blessed.
  224.   By using T_PTROBJ one can achieve a form of type-checking
  225. ! because the XSUB will attempt to verify that the Perl object
  226.   is of the expected type.
  227.   
  228.   The following XS code shows the getnetconfigent() function which is used
  229. ***************
  230. *** 947,951 ****
  231.   
  232.   =head1 AUTHOR
  233.   
  234. ! Dean Roehrich C<roehrich@cray.com>
  235. ! September 27, 1994
  236. --- 955,959 ----
  237.   
  238.   =head1 AUTHOR
  239.   
  240. ! Dean Roehrich F<E<lt>roehrich@cray.comE<gt>>
  241. ! May 3, 1995
  242. Index: pod/perlbot.pod
  243. *** perl5.001e/pod/perlbot.pod    Tue Oct 18 12:39:08 1994
  244. --- perl5.001f/pod/perlbot.pod    Wed May 31 10:28:06 1995
  245. ***************
  246. *** 248,254 ****
  247.       $a->bar;
  248.   
  249.   Now we try to override the BAZ() method.  We would like FOO::bar() to call
  250. ! GOOP::BAZ(), but this cannot happen since FOO::bar() explicitly calls
  251.   FOO::private::BAZ().
  252.   
  253.       package FOO;
  254. --- 248,254 ----
  255.       $a->bar;
  256.   
  257.   Now we try to override the BAZ() method.  We would like FOO::bar() to call
  258. ! GOOP::BAZ(), but this cannot happen because FOO::bar() explicitly calls
  259.   FOO::private::BAZ().
  260.   
  261.       package FOO;
  262. ***************
  263. *** 365,367 ****
  264. --- 365,443 ----
  265.       $a->enter;
  266.       $b->enter;
  267.   
  268. + =head1 INHERITING A CONSTRUCTOR
  269. + An inheritable constructor should use the second form of bless() which allows
  270. + blessing directly into a specified class.  Notice in this example that the
  271. + object will be a BAR not a FOO, even though the constructor is in class FOO.
  272. +     package FOO;
  273. +     sub new {
  274. +         my $type = shift;
  275. +         my $self = {};
  276. +         bless $self, $type;
  277. +     }
  278. +     sub baz {
  279. +         print "in FOO::baz()\n";
  280. +     }
  281. +     package BAR;
  282. +     @ISA = qw(FOO);
  283. +     sub baz {
  284. +         print "in BAR::baz()\n";
  285. +     }
  286. +     package main;
  287. +     $a = BAR->new;
  288. +     $a->baz;
  289. + =head1 DELEGATION
  290. + Some classes, such as SDBM_File, cannot be effectively subclassed because
  291. + they create foreign objects.  Such a class can be extended with some sort of
  292. + aggregation technique such as the "using" relationship mentioned earlier or
  293. + by delegation.
  294. + The following example demonstrates delegation using an AUTOLOAD() function to
  295. + perform message-forwarding.  This will allow the Mydbm object to behave
  296. + exactly like an SDBM_File object.  The Mydbm class could now extend the
  297. + behavior by adding custom FETCH() and STORE() methods, if this is desired.
  298. +     package Mydbm;
  299. +     require SDBM_File;
  300. +     require TieHash;
  301. +     @ISA = qw(TieHash);
  302. +     sub TIEHASH {
  303. +         my $type = shift;
  304. +         my $ref = SDBM_File->new(@_);
  305. +         bless {'delegate' => $ref};
  306. +     }
  307. +     sub AUTOLOAD {
  308. +         my $self = shift;
  309. +         # The Perl interpreter places the name of the
  310. +         # message in a variable called $AUTOLOAD.
  311. +         # DESTROY messages should never be propagated.
  312. +         return if $AUTOLOAD =~ /::DESTROY$/;
  313. +         # Remove the package name.
  314. +         $AUTOLOAD =~ s/^Mydbm:://;
  315. +         # Pass the message to the delegate.
  316. +         $self->{'delegate'}->$AUTOLOAD(@_);
  317. +     }
  318. +     package main;
  319. +     use Fcntl qw( O_RDWR O_CREAT );
  320. +     tie %foo, Mydbm, "adbm", O_RDWR|O_CREAT, 0640;
  321. +     $foo{'bar'} = 123;
  322. +     print "foo-bar = $foo{'bar'}\n";
  323. Index: pod/perlcall.pod
  324. *** perl5.001e/pod/perlcall.pod    Tue Oct 18 12:39:13 1994
  325. --- perl5.001f/pod/perlcall.pod    Wed May 31 10:28:06 1995
  326. ***************
  327. *** 4,258 ****
  328.   
  329.   =head1 DESCRIPTION
  330.   
  331. ! B<WARNING : This document is still under construction. 
  332. ! There are bound to be a number of inaccuracies, so tread very carefully for now.>
  333.   
  334. ! The purpose of this document is to show you how to write I<callbacks>, 
  335. ! i.e. how to call Perl from C. The main
  336. ! focus is on how to interface back to Perl from a bit of C code that has itself
  337. ! been run by Perl, i.e. the 'main' program is a Perl script; you are using it
  338. ! to execute
  339. ! a section of code written in C; that bit of C code wants you to do something
  340. ! with a particular event, so you want a Perl sub to be executed whenever it
  341. ! happens.
  342.   
  343. ! Examples where this is necessary include
  344.   
  345.   =over 5
  346.   
  347. ! =item * 
  348.   
  349.   You have created an XSUB interface to an application's C API.
  350.   
  351.   A fairly common feature in applications is to allow you to define a C
  352. ! function that will get called whenever something nasty occurs.
  353. ! What we would like is for a Perl sub to be called instead.
  354. ! =item *
  355. ! The classic example of where callbacks are used is in an event driven program 
  356. ! like for X-windows.
  357. ! In this case your register functions to be called whenever a specific events
  358. ! occur, e.g. a mouse button is pressed.
  359.   
  360.   =back
  361.   
  362. ! Although the techniques described are applicable to embedding Perl
  363. ! in a C program, this is not the primary goal of this document. For details
  364. ! on embedding Perl in C refer to L<perlembed> (currently unwritten).
  365. ! Before you launch yourself head first into the rest of this document, it would 
  366. ! be a good idea to have read the following two documents - L<perlapi> and L<perlguts>.
  367.   
  368. ! This stuff is easier to explain using examples. But first here are a few
  369. ! definitions anyway.
  370.   
  371. ! =head2 Definitions
  372.   
  373. ! Perl has a number of C functions which allow you to call Perl subs. They are
  374.   
  375.       I32 perl_call_sv(SV* sv, I32 flags) ;
  376.       I32 perl_call_pv(char *subname, I32 flags) ;
  377.       I32 perl_call_method(char *methname, I32 flags) ;
  378.       I32 perl_call_argv(char *subname, I32 flags, register char **argv) ;
  379.   
  380. ! The key function is I<perl_call_sv>. All the other functions make use of
  381. ! I<perl_call_sv> to do what they do.
  382.   
  383. ! I<perl_call_sv> takes two parameters, the first is an SV*. This allows you to 
  384. ! specify the Perl sub to be called either as a C string (which has first been 
  385. ! converted to an SV) or a reference to a 
  386. ! sub. Example 7, shows you how you can make use of I<perl_call_sv>.
  387. ! The second parameter, C<flags>, is a general purpose option command. 
  388. ! This parameter is common to all the I<perl_call_*> functions. 
  389. ! It is discussed in the next section.
  390.   
  391. ! The function, I<perl_call_pv>, is similar as I<perl_call_sv> except it 
  392. ! expects it's first parameter has to be a C char* which identifies the Perl 
  393. ! sub you want to call, e.g. C<perl_call_pv("fred", 0)>.
  394.   
  395. ! The function I<perl_call_method> expects its first argument to contain a 
  396. ! blessed reference to a class. Using that reference it looks up and calls C<methname> 
  397. ! from that class. See example 9.
  398.   
  399. ! I<perl_call_argv> calls the Perl sub specified by the C<subname> parameter. 
  400. ! It also takes the usual C<flags> parameter. 
  401. ! The final parameter, C<argv>, consists of a 
  402. ! list of C strings to be sent to the Perl sub. See example 8.
  403.   
  404. ! All the functions return a number. This is a count of the number of items
  405. ! returned by the Perl sub on the stack.
  406.   
  407. ! As a general rule you should I<always> check the return value from these 
  408. ! functions.
  409. ! Even if you are only expecting a particular number of values to be returned 
  410. ! from the Perl sub, there is nothing to stop someone from doing something
  411. ! unexpected - don't say you havn't been warned.
  412.   
  413. ! =head2 Flag Values
  414.   
  415. ! The C<flags> parameter in all the I<perl_call_*> functions consists of any 
  416. ! combination of the symbols defined below, OR'ed together.
  417.   
  418.   =over 5
  419.   
  420. ! =item  G_SCALAR    
  421.   
  422. ! Calls the Perl sub in a scalar context.
  423.   
  424. - Whatever the Perl sub actually returns, we only want a scalar. If the perl sub 
  425. - does return a scalar, the return value from the I<perl_call_*> function 
  426. - will be 1 or 0. If 1, then the value actually returned by the Perl sub will 
  427. - be contained
  428. - on the top of the stack. 
  429. - If 0, then the sub has probably called I<die> or you have 
  430. - used the G_DISCARD flag.
  431.   
  432. ! If the Perl sub returns a list, the I<perl_call_*> function will still
  433. ! only return 1 or 0. If 1, then the number of elements in the list 
  434. ! will be stored on top of the stack.
  435. ! The actual values of the list will not be accessable. 
  436.   
  437.   
  438. ! G_SCALAR is the default flag setting for all the functions.
  439.   
  440. ! =item G_ARRAY    
  441.   
  442. ! Calls the Perl sub in a list context.
  443.   
  444. ! The return code from the I<perl_call_*> functions will indicate how
  445. ! many elements of the stack are used to store the array.
  446.   
  447. ! =item G_DISCARD    
  448.   
  449. - If you are not interested in the values returned by the Perl sub then setting
  450. - this flag will make Perl get rid of them automatically for you. This will take
  451. - precedence to either G_SCALAR or G_ARRAY.
  452.   
  453. ! If you do 
  454. ! not set this flag then you may need to explicitly get rid of temporary values.
  455. ! See example 3 for details.
  456.   
  457. ! =item G_NOARGS    
  458.   
  459. ! If you are not passing any parameters to the Perl sub, you can save a bit of 
  460. ! time by setting this flag. It has the effect of of not creating the C<@_> array 
  461. ! for the Perl sub.
  462.   
  463. ! A point worth noting is that if this flag is specified the Perl sub called can 
  464. ! still access an C<@_> array from a previous Perl sub. 
  465. ! This functionality can be illustrated with the perl code below
  466.   
  467. !     sub fred
  468. !       { print "@_\n"  }
  469.   
  470. !     sub joe
  471. !       { &fred }
  472.   
  473. !     &joe(1,2,3) ;
  474.   
  475.   This will print
  476.   
  477. !     1 2 3
  478.   
  479. - What has happened is that C<fred> accesses the C<@_> array which belongs to C<joe>.
  480.   
  481. ! =item G_EVAL    
  482.   
  483. ! If the Perl sub you are calling has the ability to terminate 
  484. ! abnormally, e.g. by calling I<die> or by not actually existing, and 
  485. ! you want to catch this type of event, specify this flag setting. It will put 
  486. ! an I<eval { }> around the sub call.
  487.   
  488.   Whenever control returns from the I<perl_call_*> function you need to
  489. ! check the C<$@> variable as you would in a normal Perl script. 
  490. ! See example 6 for details of how to do this.
  491.   
  492.   
  493.   =back
  494.   
  495.   
  496.   =head1 EXAMPLES
  497.   
  498.   Enough of the definition talk, let's have a few examples.
  499.   
  500. ! Perl provides many macros to assist in accessing the Perl stack. 
  501. ! These macros should always be used when interfacing to Perl internals.
  502. ! Hopefully this should make the code less vulnerable to changes made to
  503. ! Perl in the future.
  504. ! Another point worth noting is that in the first series of examples I have 
  505. ! only made use of the I<perl_call_pv> function. 
  506. ! This has only been done to ease you into the 
  507. ! topic. Wherever possible, if the choice is between using I<perl_call_pv> 
  508. ! and I<perl_call_sv>, I would always try to use I<perl_call_sv>.
  509. ! The code for these examples is stored in the file F<perlcall.tar>. 
  510. ! (Once this document settles down, all the example code will be available in the file).
  511.   
  512. ! =head2 Example1: No Parameters, Nothing returned
  513.   
  514. ! This first trivial example will call a Perl sub, I<PrintUID>, to print 
  515. ! out the UID of the process. 
  516.   
  517.       sub PrintUID
  518.       {
  519.           print "UID is $<\n" ;
  520.       }
  521.   
  522. ! and here is the C to call it
  523.   
  524. !     void
  525.       call_PrintUID()
  526.       {
  527. !     dSP ;
  528.   
  529. !     PUSHMARK(sp) ;
  530.           perl_call_pv("PrintUID", G_DISCARD|G_NOARGS) ;
  531.       }
  532.   
  533. ! Simple, eh. 
  534.   
  535. ! A few points to note about this example. 
  536.   
  537.   =over 5
  538.   
  539. ! =item 1. 
  540.   
  541. ! We aren't passing any parameters to I<PrintUID> so G_NOARGS
  542. ! can be specified.
  543.   
  544.   =item 2.
  545.   
  546. ! Ignore C<dSP> and C<PUSHMARK(sp)> for now. They will be discussed in the next
  547. ! example.
  548.   
  549. ! =item 3. 
  550.   
  551.   We aren't interested in anything returned from I<PrintUID>, so
  552.   G_DISCARD is specified. Even if I<PrintUID> was changed to actually
  553.   return some value(s), having specified G_DISCARD will mean that they
  554.   will be wiped by the time control returns from I<perl_call_pv>.
  555.   
  556. ! =item 4. 
  557.   
  558. ! Because we specified G_DISCARD, it is not necessary to check 
  559. ! the value returned from I<perl_call_sv>. It will always be 0.
  560.   
  561.   =item 5.
  562.   
  563. ! As I<perl_call_pv> is being used, the Perl sub is specified as a C string.
  564.   
  565.   =back
  566.   
  567. ! =head2 Example 2: Passing Parameters
  568.   
  569. ! Now let's make a slightly more complex example. This time we want 
  570. ! to call a Perl sub
  571. ! which will take 2 parameters - a string (C<$s>) and an integer (C<$n>). 
  572. ! The sub will simply print the first C<$n> characters of the string.
  573.   
  574. ! So the Perl sub would look like this
  575.   
  576.       sub LeftString
  577.       {
  578. --- 4,457 ----
  579.   
  580.   =head1 DESCRIPTION
  581.   
  582. ! The purpose of this document is to show you how to call Perl subroutines
  583. ! directly from C, i.e. how to write I<callbacks>.
  584.   
  585. ! Apart from discussing the C interface provided by Perl for writing
  586. ! callbacks the document uses a series of examples to show how the
  587. ! interface actually works in practice.  In addition some techniques for
  588. ! coding callbacks are covered.
  589.   
  590. ! Examples where callbacks are necessary include
  591.   
  592.   =over 5
  593.   
  594. ! =item * An Error Handler
  595.   
  596.   You have created an XSUB interface to an application's C API.
  597.   
  598.   A fairly common feature in applications is to allow you to define a C
  599. ! function that will be called whenever something nasty occurs. What we
  600. ! would like is to be able to specify a Perl subroutine that will be
  601. ! called instead.
  602. ! =item * An Event Driven Program
  603. ! The classic example of where callbacks are used is when writing an
  604. ! event driven program like for an X windows application.  In this case
  605. ! your register functions to be called whenever specific events occur,
  606. ! e.g. a mouse button is pressed, the cursor moves into a window or a
  607. ! menu item is selected.
  608.   
  609.   =back
  610.   
  611. ! Although the techniques described here are applicable when embedding
  612. ! Perl in a C program, this is not the primary goal of this document.
  613. ! There are other details that must be considered and are specific to
  614. ! embedding Perl. For details on embedding Perl in C refer to
  615. ! L<perlembed>.
  616. ! Before you launch yourself head first into the rest of this document,
  617. ! it would be a good idea to have read the following two documents -
  618. ! L<perlapi> and L<perlguts>.
  619.   
  620. ! =head1 THE PERL_CALL FUNCTIONS
  621.   
  622. ! Although this stuff is easier to explain using examples, you first need
  623. ! be aware of a few important definitions.
  624.   
  625. ! Perl has a number of C functions that allow you to call Perl
  626. ! subroutines.  They are
  627.   
  628.       I32 perl_call_sv(SV* sv, I32 flags) ;
  629.       I32 perl_call_pv(char *subname, I32 flags) ;
  630.       I32 perl_call_method(char *methname, I32 flags) ;
  631.       I32 perl_call_argv(char *subname, I32 flags, register char **argv) ;
  632.   
  633. ! The key function is I<perl_call_sv>.  All the other functions are
  634. ! fairly simple wrappers which make it easier to call Perl subroutines in
  635. ! special cases. At the end of the day they will all call I<perl_call_sv>
  636. ! to actually invoke the Perl subroutine.
  637. ! All the I<perl_call_*> functions have a C<flags> parameter which is
  638. ! used to pass a bit mask of options to Perl.  This bit mask operates
  639. ! identically for each of the functions.  The settings available in the
  640. ! bit mask are discussed in L<FLAG VALUES>.
  641.   
  642. ! Each of the functions will now be discussed in turn.
  643.   
  644. ! =over 5
  645. ! =item B<perl_call_sv>
  646.   
  647. ! I<perl_call_sv> takes two parameters, the first, C<sv>, is an SV*.
  648. ! This allows you to specify the Perl subroutine to be called either as a
  649. ! C string (which has first been converted to an SV) or a reference to a
  650. ! subroutine. The section, I<Using perl_call_sv>, shows how you can make
  651. ! use of I<perl_call_sv>.
  652. ! =item B<perl_call_pv>
  653. ! The function, I<perl_call_pv>, is similar to I<perl_call_sv> except it
  654. ! expects its first parameter to be a C char* which identifies the Perl
  655. ! subroutine you want to call, e.g. C<perl_call_pv("fred", 0)>.  If the
  656. ! subroutine you want to call is in another package, just include the
  657. ! package name in the string, e.g. C<"pkg::fred">.
  658. ! =item B<perl_call_method>
  659. ! The function I<perl_call_method> is used to call a method from a Perl
  660. ! class.  The parameter C<methname> corresponds to the name of the method
  661. ! to be called.  Note that the class that the method belongs to is passed
  662. ! on the Perl stack rather than in the parameter list. This class can be
  663. ! either the name of the class (for a static method) or a reference to an
  664. ! object (for a virtual method).  See L<perlobj> for more information on
  665. ! static and virtual methods and L<Using perl_call_method> for an example
  666. ! of using I<perl_call_method>.
  667. ! =item B<perl_call_argv>
  668. ! I<perl_call_argv> calls the Perl subroutine specified by the C string
  669. ! stored in the C<subname> parameter. It also takes the usual C<flags>
  670. ! parameter.  The final parameter, C<argv>, consists of a NULL terminated
  671. ! list of C strings to be passed as parameters to the Perl subroutine.
  672. ! See I<Using perl_call_argv>.
  673.   
  674. ! =back
  675.   
  676. ! All the functions return an integer. This is a count of the number of
  677. ! items returned by the Perl subroutine. The actual items returned by the
  678. ! subroutine are stored on the Perl stack.
  679.   
  680. ! As a general rule you should I<always> check the return value from
  681. ! these functions.  Even if you are expecting only a particular number of
  682. ! values to be returned from the Perl subroutine, there is nothing to
  683. ! stop someone from doing something unexpected - don't say you haven't
  684. ! been warned.
  685.   
  686. ! =head1 FLAG VALUES
  687.   
  688. ! The C<flags> parameter in all the I<perl_call_*> functions is a bit mask
  689. ! which can consist of any combination of the symbols defined below,
  690. ! OR'ed together.
  691. ! =head2  G_SCALAR
  692. ! Calls the Perl subroutine in a scalar context.  This is the default
  693. ! context flag setting for all the I<perl_call_*> functions.
  694. ! This flag has 2 effects
  695.   
  696.   =over 5
  697.   
  698. ! =item 1.
  699.   
  700. ! it indicates to the subroutine being called that it is executing in a
  701. ! scalar context (if it executes I<wantarray> the result will be false).
  702.   
  703.   
  704. ! =item 2.
  705.   
  706. + it ensures that only a scalar is actually returned from the subroutine.
  707. + The subroutine can, of course,  ignore the I<wantarray> and return a
  708. + list anyway. If so, then only the last element of the list will be
  709. + returned.
  710.   
  711. ! =back
  712. ! The value returned by the I<perl_call_*> function indicates how may
  713. ! items have been returned by the Perl subroutine - in this case it will
  714. ! be either 0 or 1.
  715. ! If 0, then you have specified the G_DISCARD flag.
  716. ! If 1, then the item actually returned by the Perl subroutine will be
  717. ! stored on the Perl stack - the section I<Returning a Scalar> shows how
  718. ! to access this value on the stack.  Remember that regardless of how
  719. ! many items the Perl subroutine returns, only the last one will be
  720. ! accessible from the stack - think of the case where only one value is
  721. ! returned as being a list with only one element.  Any other items that
  722. ! were returned will not exist by the time control returns from the
  723. ! I<perl_call_*> function.  The section I<Returning a list in a scalar
  724. ! context> shows an example of this behaviour.
  725. ! =head2 G_ARRAY
  726.   
  727. ! Calls the Perl subroutine in a list context.
  728.   
  729. ! As with G_SCALAR, this flag has 2 effects
  730.   
  731. ! =over 5
  732. ! =item 1.
  733.   
  734. ! it indicates to the subroutine being called that it is executing in an
  735. ! array context (if it executes I<wantarray> the result will be true).
  736.   
  737.   
  738. ! =item 2.
  739. ! it ensures that all items returned from the subroutine will be
  740. ! accessible when control returns from the I<perl_call_*> function.
  741.   
  742. ! =back
  743.   
  744. ! The value returned by the I<perl_call_*> function indicates how may
  745. ! items have been returned by the Perl subroutine.
  746.   
  747. ! If 0, the you have specified the G_DISCARD flag.
  748.   
  749. ! If not 0, then it will be a count of the number of items returned by
  750. ! the subroutine. These items will be stored on the Perl stack.  The
  751. ! section I<Returning a list of values> gives an example of using the
  752. ! G_ARRAY flag and the mechanics of accessing the returned items from the
  753. ! Perl stack.
  754. ! =head2 G_DISCARD
  755. ! By default, the I<perl_call_*> functions place the items returned from
  756. ! by the Perl subroutine on the stack.  If you are not interested in
  757. ! these items, then setting this flag will make Perl get rid of them
  758. ! automatically for you.  Note that it is still possible to indicate a
  759. ! context to the Perl subroutine by using either G_SCALAR or G_ARRAY.
  760. ! If you do not set this flag then it is I<very> important that you make
  761. ! sure that any temporaries (i.e. parameters passed to the Perl
  762. ! subroutine and values returned from the subroutine) are disposed of
  763. ! yourself.  The section I<Returning a Scalar> gives details of how to
  764. ! explicitly dispose of these temporaries and the section I<Using Perl to
  765. ! dispose of temporaries> discusses the specific circumstances where you
  766. ! can ignore the problem and let Perl deal with it for you.
  767. ! =head2 G_NOARGS
  768. ! Whenever a Perl subroutine is called using one of the I<perl_call_*>
  769. ! functions, it is assumed by default that parameters are to be passed to
  770. ! the subroutine.  If you are not passing any parameters to the Perl
  771. ! subroutine, you can save a bit of time by setting this flag.  It has
  772. ! the effect of not creating the C<@_> array for the Perl subroutine.
  773. ! Although the functionality provided by this flag may seem
  774. ! straightforward, it should be used only if there is a good reason to do
  775. ! so.  The reason for being cautious is that even if you have specified
  776. ! the G_NOARGS flag, it is still possible for the Perl subroutine that
  777. ! has been called to think that you have passed it parameters.
  778. ! In fact, what can happen is that the Perl subroutine you have called
  779. ! can access the C<@_> array from a previous Perl subroutine.  This will
  780. ! occur when the code that is executing the I<perl_call_*> function has
  781. ! itself been called from another Perl subroutine. The code below
  782. ! illustrates this
  783.   
  784. !     sub fred
  785. !       { print "@_\n"  }
  786.   
  787. !     sub joe
  788. !       { &fred }
  789. !     &joe(1,2,3) ;
  790.   
  791.   This will print
  792.   
  793. !     1 2 3
  794. ! What has happened is that C<fred> accesses the C<@_> array which
  795. ! belongs to C<joe>.
  796.   
  797.   
  798. ! =head2 G_EVAL    
  799.   
  800. ! It is possible for the Perl subroutine you are calling to terminate
  801. ! abnormally, e.g. by calling I<die> explicitly or by not actually
  802. ! existing.  By default, when either of these of events occurs, the
  803. ! process will terminate immediately.  If though, you want to trap this
  804. ! type of event, specify the G_EVAL flag.  It will put an I<eval { }>
  805. ! around the subroutine call.
  806.   
  807.   Whenever control returns from the I<perl_call_*> function you need to
  808. ! check the C<$@> variable as you would in a normal Perl script.
  809. ! The value returned from the I<perl_call_*> function is dependent on
  810. ! what other flags have been specified and whether an error has
  811. ! occurred.  Here are all the different cases that can occur
  812. ! =over 5
  813. ! =item *
  814. ! If the I<perl_call_*> function returns normally, then the value
  815. ! returned is as specified in the previous sections.
  816. ! =item *
  817. ! If G_DISCARD is specified, the return value will always be 0.
  818. ! =item *
  819. ! If G_ARRAY is specified I<and> an error has occurred, the return value
  820. ! will always be 0.
  821. ! =item *
  822.   
  823. + If G_SCALAR is specified I<and> an error has occurred, the return value
  824. + will be 1 and the value on the top of the stack will be I<undef>. This
  825. + means that if you have already detected the error by checking C<$@> and
  826. + you want the program to continue, you must remember to pop the I<undef>
  827. + from the stack.
  828.   
  829.   =back
  830.   
  831. + See I<Using G_EVAL> for details of using G_EVAL.
  832. + =head2 Determining the Context 
  833. + As mentioned above, you can determine the context of the currently
  834. + executing subroutine in Perl with I<wantarray>. The equivalent test can
  835. + be made in C by using the C<GIMME> macro. This will return C<G_SCALAR>
  836. + if you have been called in a scalar context and C<G_ARRAY> if in an
  837. + array context. An example of using the C<GIMME> macro is shown in
  838. + section I<Using GIMME>.
  839. + =head1 KNOWN PROBLEMS
  840. + This section outlines all known problems that exist in the
  841. + I<perl_call_*> functions.
  842. + =over 5
  843. + =item 1.
  844. + If you are intending to make use of both the G_EVAL and G_SCALAR flags
  845. + in your code, use a version of Perl greater than 5.000.  There is a bug
  846. + in version 5.000 of Perl which means that the combination of these two
  847. + flags will not work as described in the section I<FLAG VALUES>.
  848. + Specifically, if the two flags are used when calling a subroutine and
  849. + that subroutine does not call I<die>, the value returned by
  850. + I<perl_call_*> will be wrong.
  851. + =item 2.
  852. + In Perl 5.000 and 5.001 there is a problem with using I<perl_call_*> if
  853. + the Perl sub you are calling attempts to trap a I<die>.
  854. + The symptom of this problem is that the called Perl sub will continue
  855. + to completion, but whenever it attempts to pass control back to the
  856. + XSUB, the program will immediately terminate.
  857. + For example, say you want to call this Perl sub
  858. +     sub fred
  859. +     {
  860. +         eval { die "Fatal Error" ; }
  861. +         print "Trapped error: $@\n" 
  862. +             if $@ ;
  863. +     }
  864. + via this XSUB
  865. +     void
  866. +     Call_fred()
  867. +         CODE:
  868. +         PUSHMARK(sp) ;
  869. +         perl_call_pv("fred", G_DISCARD|G_NOARGS) ;
  870. +         fprintf(stderr, "back in Call_fred\n") ;
  871. + When C<Call_fred> is executed it will print
  872. +     Trapped error: Fatal Error
  873. + As control never returns to C<Call_fred>, the C<"back in Call_fred">
  874. + string will not get printed.
  875. + To work around this problem, you can either upgrade to Perl 5.002 (or
  876. + later), or use the G_EVAL flag with I<perl_call_*> as shown below
  877. +     void
  878. +     Call_fred()
  879. +         CODE:
  880. +         PUSHMARK(sp) ;
  881. +         perl_call_pv("fred", G_EVAL|G_DISCARD|G_NOARGS) ;
  882. +         fprintf(stderr, "back in Call_fred\n") ;
  883. + =back
  884.   
  885.   =head1 EXAMPLES
  886.   
  887.   Enough of the definition talk, let's have a few examples.
  888.   
  889. ! Perl provides many macros to assist in accessing the Perl stack.
  890. ! Wherever possible, these macros should always be used when interfacing
  891. ! to Perl internals.  Hopefully this should make the code less vulnerable
  892. ! to any changes made to Perl in the future.
  893. ! Another point worth noting is that in the first series of examples I
  894. ! have made use of only the I<perl_call_pv> function.  This has been done
  895. ! to keep the code simpler and ease you into the topic.  Wherever
  896. ! possible, if the choice is between using I<perl_call_pv> and
  897. ! I<perl_call_sv>, you should always try to use I<perl_call_sv>.  See
  898. ! I<Using perl_call_sv> for details.
  899.   
  900. ! =head2 No Parameters, Nothing returned
  901.   
  902. ! This first trivial example will call a Perl subroutine, I<PrintUID>, to
  903. ! print out the UID of the process.
  904.   
  905.       sub PrintUID
  906.       {
  907.           print "UID is $<\n" ;
  908.       }
  909.   
  910. ! and here is a C function to call it
  911.   
  912. !     static void
  913.       call_PrintUID()
  914.       {
  915. !         dSP ;
  916.   
  917. !         PUSHMARK(sp) ;
  918.           perl_call_pv("PrintUID", G_DISCARD|G_NOARGS) ;
  919.       }
  920.   
  921. ! Simple, eh.
  922.   
  923. ! A few points to note about this example.
  924.   
  925.   =over 5
  926.   
  927. ! =item 1.
  928.   
  929. ! Ignore C<dSP> and C<PUSHMARK(sp)> for now. They will be discussed in
  930. ! the next example.
  931.   
  932.   =item 2.
  933.   
  934. ! We aren't passing any parameters to I<PrintUID> so G_NOARGS can be
  935. ! specified.
  936.   
  937. ! =item 3.
  938.   
  939.   We aren't interested in anything returned from I<PrintUID>, so
  940.   G_DISCARD is specified. Even if I<PrintUID> was changed to actually
  941.   return some value(s), having specified G_DISCARD will mean that they
  942.   will be wiped by the time control returns from I<perl_call_pv>.
  943.   
  944. ! =item 4.
  945.   
  946. ! As I<perl_call_pv> is being used, the Perl subroutine is specified as a
  947. ! C string. In this case the subroutine name has been 'hard-wired' into the
  948. ! code.
  949.   
  950.   =item 5.
  951.   
  952. ! Because we specified G_DISCARD, it is not necessary to check the value
  953. ! returned from I<perl_call_pv>. It will always be 0.
  954.   
  955.   =back
  956.   
  957. ! =head2 Passing Parameters
  958.   
  959. ! Now let's make a slightly more complex example. This time we want to
  960. ! call a Perl subroutine, C<LeftString>, which will take 2 parameters - a
  961. ! string (C<$s>) and an integer (C<$n>).  The subroutine will simply
  962. ! print the first C<$n> characters of the string.
  963.   
  964. ! So the Perl subroutine would look like this
  965.   
  966.       sub LeftString
  967.       {
  968. ***************
  969. *** 277,351 ****
  970.           perl_call_pv("LeftString", G_DISCARD);
  971.       }
  972.   
  973.   Here are a few notes on the C function I<call_LeftString>.
  974.   
  975.   =over 5
  976.   
  977. ! =item 1. 
  978. ! The only flag specified this time is G_DISCARD. As we are passing 2 
  979. ! parameters to the Perl sub this time, we have not specified G_NOARGS.
  980. ! =item 2. 
  981.   
  982. ! Parameters are passed to the Perl sub using the Perl stack.
  983. ! This is the purpose of the code beginning with the line C<dSP> and ending
  984. ! with the line C<PUTBACK>.
  985.   
  986.   
  987. ! =item 3.
  988.   
  989.   If you are going to put something onto the Perl stack, you need to know
  990. ! where to put it. This is the purpose of the macro C<dSP> -
  991. ! it declares and initialises a local copy of the Perl stack pointer.
  992.   
  993.   All the other macros which will be used in this example require you to
  994. ! have used this macro. 
  995.   
  996. ! If you are calling a Perl sub directly from an XSUB function, it is 
  997. ! not necessary to explicitly use the C<dSP> macro - it will be declared for you.
  998.   
  999. ! =item 4.
  1000.   
  1001.   Any parameters to be pushed onto the stack should be bracketed by the
  1002. ! C<PUSHMARK> and C<PUTBACK> macros. 
  1003. ! The purpose of these two macros, in this context, is to automatically count
  1004. ! the number of parameters you are pushing. Then whenever Perl is creating
  1005. ! the C<@_> array for the sub, it knows how big to make it.
  1006. ! The C<PUSHMARK> macro tells Perl to make a mental note of the current stack
  1007. ! pointer. Even if you aren't passing any parameters (like in Example 1) you must 
  1008. ! still call the C<PUSHMARK> macro before you can call any of 
  1009. ! the I<perl_call_*> functions - Perl still needs to know that there are 
  1010. ! no parameters.
  1011. ! The C<PUTBACK> macro sets the global copy of the stack pointer to be the
  1012. ! same as our local copy. If we didn't do this I<perl_call_pv> wouldn't
  1013. ! know where the two parameters we pushed were - remember that up to now
  1014. ! all the stack pointer manipulation we have done is with our local copy,
  1015. ! I<not> the global copy.
  1016.   
  1017.   =item 5.
  1018.   
  1019.   Next, we come to XPUSHs. This is where the parameters actually get
  1020. ! pushed onto the stack. In this case we are pushing a string and an integer.
  1021.   
  1022. ! See the section I<XSUB's AND  THE ARGUMENT STACK> in L<perlguts> for
  1023. ! details on how the XPUSH macros work.
  1024.   
  1025.   =item 6.
  1026.   
  1027. ! Finally, I<LeftString> can now be called via the I<perl_call_pv> function.
  1028.   
  1029.   =back
  1030.   
  1031. ! =head2 Example 3: Returning a Scalar
  1032.   
  1033. ! Now for an example of dealing with the values returned from a Perl sub.
  1034.   
  1035. ! Here is a Perl sub, I<Adder>,  which takes 2 integer parameters and simply 
  1036. ! returns their sum.
  1037.   
  1038.       sub Adder
  1039.       {
  1040. --- 476,556 ----
  1041.           perl_call_pv("LeftString", G_DISCARD);
  1042.       }
  1043.   
  1044.   Here are a few notes on the C function I<call_LeftString>.
  1045.   
  1046.   =over 5
  1047.   
  1048. ! =item 1.
  1049.   
  1050. ! Parameters are passed to the Perl subroutine using the Perl stack.
  1051. ! This is the purpose of the code beginning with the line C<dSP> and
  1052. ! ending with the line C<PUTBACK>.
  1053.   
  1054.   
  1055. ! =item 2.
  1056.   
  1057.   If you are going to put something onto the Perl stack, you need to know
  1058. ! where to put it. This is the purpose of the macro C<dSP> - it declares
  1059. ! and initializes a I<local> copy of the Perl stack pointer.
  1060.   
  1061.   All the other macros which will be used in this example require you to
  1062. ! have used this macro.
  1063.   
  1064. ! The exception to this rule is if you are calling a Perl subroutine
  1065. ! directly from an XSUB function. In this case it is not necessary to
  1066. ! explicitly use the C<dSP> macro - it will be declared for you
  1067. ! automatically.
  1068.   
  1069. ! =item 3.
  1070.   
  1071.   Any parameters to be pushed onto the stack should be bracketed by the
  1072. ! C<PUSHMARK> and C<PUTBACK> macros.  The purpose of these two macros, in
  1073. ! this context, is to automatically count the number of parameters you
  1074. ! are pushing. Then whenever Perl is creating the C<@_> array for the
  1075. ! subroutine, it knows how big to make it.
  1076. ! The C<PUSHMARK> macro tells Perl to make a mental note of the current
  1077. ! stack pointer. Even if you aren't passing any parameters (like the
  1078. ! example shown in the section I<No Parameters, Nothing returned>) you
  1079. ! must still call the C<PUSHMARK> macro before you can call any of the
  1080. ! I<perl_call_*> functions - Perl still needs to know that there are no
  1081. ! parameters.
  1082. ! The C<PUTBACK> macro sets the global copy of the stack pointer to be
  1083. ! the same as our local copy. If we didn't do this I<perl_call_pv>
  1084. ! wouldn't know where the two parameters we pushed were - remember that
  1085. ! up to now all the stack pointer manipulation we have done is with our
  1086. ! local copy, I<not> the global copy.
  1087. ! =item 4.
  1088. ! The only flag specified this time is G_DISCARD. Since we are passing 2
  1089. ! parameters to the Perl subroutine this time, we have not specified
  1090. ! G_NOARGS.
  1091.   
  1092.   =item 5.
  1093.   
  1094.   Next, we come to XPUSHs. This is where the parameters actually get
  1095. ! pushed onto the stack. In this case we are pushing a string and an
  1096. ! integer.
  1097.   
  1098. ! See the section L<perlguts/"XSUB'S and the Argument Stack"> for details
  1099. ! on how the XPUSH macros work.
  1100.   
  1101.   =item 6.
  1102.   
  1103. ! Finally, I<LeftString> can now be called via the I<perl_call_pv>
  1104. ! function.
  1105.   
  1106.   =back
  1107.   
  1108. ! =head2 Returning a Scalar
  1109.   
  1110. ! Now for an example of dealing with the items returned from a Perl
  1111. ! subroutine.
  1112.   
  1113. ! Here is a Perl subroutine, I<Adder>,  which takes 2 integer parameters
  1114. ! and simply returns their sum.
  1115.   
  1116.       sub Adder
  1117.       {
  1118. ***************
  1119. *** 353,360 ****
  1120.           $a + $b ;
  1121.       }
  1122.   
  1123. ! As we are now concerned with the return value from I<Adder>, the C function
  1124. ! is now a bit more complex.
  1125.   
  1126.       static void
  1127.       call_Adder(a, b)
  1128. --- 558,565 ----
  1129.           $a + $b ;
  1130.       }
  1131.   
  1132. ! Since we are now concerned with the return value from I<Adder>, the C
  1133. ! function required to call it is now a bit more complex.
  1134.   
  1135.       static void
  1136.       call_Adder(a, b)
  1137. ***************
  1138. *** 376,482 ****
  1139.   
  1140.           SPAGAIN ;
  1141.   
  1142. !     if (count != 1)
  1143. !         croak("Big trouble\n") ;
  1144.   
  1145. !     printf ("The sum of %d and %d is %d\n", a, b, POPi) ;
  1146.   
  1147.           PUTBACK ;
  1148.           FREETMPS ;
  1149.           LEAVE ;
  1150.       }
  1151.   
  1152.   Points to note this time are
  1153.   
  1154.   =over 5
  1155.   
  1156.   =item 1. 
  1157.   
  1158. ! The only flag specified this time was G_SCALAR. That means the @_ array
  1159. ! will be created and that the value returned by I<Adder> will still
  1160. ! exist after the call to I<perl_call_pv>.
  1161.   
  1162.   
  1163.   
  1164.   =item 2.
  1165.   
  1166. ! Because we are interested in what is returned from I<Adder> we cannot specify
  1167. ! G_DISCARD. This means that we will have to tidy up the Perl stack and dispose
  1168. ! of any temporary values ourselves. This is the purpose of 
  1169.   
  1170. !     ENTER ;
  1171. !     SAVETMPS ;
  1172.   
  1173.   at the start of the function, and
  1174.   
  1175. !     FREETMPS ;
  1176. !     LEAVE ;
  1177.   
  1178. ! at the end. The C<ENTER>/C<SAVETMPS> pair creates a boundary for any 
  1179. ! temporaries we create. 
  1180. ! This means that the temporaries we get rid of will be limited to those which
  1181. ! were created after these calls.
  1182. ! The C<FREETMPS>/C<LEAVE> pair will get rid of any values returned by the Perl 
  1183. ! sub, plus it will also dump the mortal SV's we created. 
  1184. ! Having C<ENTER>/C<SAVETMPS> at the beginning
  1185. ! of the code makes sure that no other mortals are destroyed.
  1186.   
  1187.   =item 3.
  1188.   
  1189.   The purpose of the macro C<SPAGAIN> is to refresh the local copy of the
  1190.   stack pointer. This is necessary because it is possible that the memory
  1191. ! allocated to the Perl stack has been re-allocated whilst in the I<perl_call_pv>
  1192. ! call.
  1193.   
  1194. ! If you are making use of the Perl stack pointer in your code you must always
  1195. ! refresh the your local copy using SPAGAIN whenever you make use of
  1196.   of the I<perl_call_*> functions or any other Perl internal function.
  1197.   
  1198. ! =item 4. 
  1199. ! Although only a single value was expected to be returned from I<Adder>, it is
  1200. ! still good practice to check the return code from I<perl_call_pv> anyway.
  1201.   
  1202. ! Expecting a single value is not quite the same as knowing that there will
  1203. ! be one. If someone modified I<Adder> to return a list and we didn't check
  1204. ! for that possibility and take appropriate action the Perl stack would end 
  1205. ! up in an inconsistant state. That is something you I<really> don't want
  1206. ! to ever happen.
  1207.   
  1208.   =item 5.
  1209.   
  1210. ! The C<POPi> macro is used here to pop the return value from the stack. In this
  1211. ! case we wanted an integer, so C<POPi> was used.
  1212.   
  1213.   
  1214. ! Here is the complete list of POP macros available, along with the types they 
  1215. ! return.
  1216.   
  1217. !     POPs    SV
  1218. !     POPp    pointer
  1219. !     POPn    double
  1220. !     POPi    integer
  1221. !     POPl    long
  1222.   
  1223.   =item 6.
  1224.   
  1225. ! The final C<PUTBACK> is used to leave the Perl stack in a consistant state 
  1226. ! before exiting the function. This is
  1227. ! necessary because when we popped the return value from the stack with C<POPi> it
  1228. ! only updated our local copy of the stack pointer. Remember, C<PUTBACK> sets the
  1229. ! global stack pointer to be the same as our local copy.
  1230.   
  1231.   =back
  1232.   
  1233.   
  1234. ! =head2 Example 4: Returning a list of values
  1235.   
  1236. ! Now, let's extend the previous example to return both the sum of the parameters 
  1237. ! and the difference.
  1238.   
  1239. ! Here is the Perl sub
  1240.   
  1241.       sub AddSubtract
  1242.       {
  1243. --- 581,693 ----
  1244.   
  1245.           SPAGAIN ;
  1246.   
  1247. !         if (count != 1)
  1248. !             croak("Big trouble\n") ;
  1249.   
  1250. !         printf ("The sum of %d and %d is %d\n", a, b, POPi) ;
  1251.   
  1252.           PUTBACK ;
  1253.           FREETMPS ;
  1254.           LEAVE ;
  1255.       }
  1256.   
  1257.   Points to note this time are
  1258.   
  1259.   =over 5
  1260.   
  1261.   =item 1. 
  1262.   
  1263. ! The only flag specified this time was G_SCALAR. That means the C<@_>
  1264. ! array will be created and that the value returned by I<Adder> will
  1265. ! still exist after the call to I<perl_call_pv>.
  1266.   
  1267.   
  1268.   
  1269.   =item 2.
  1270.   
  1271. ! Because we are interested in what is returned from I<Adder> we cannot
  1272. ! specify G_DISCARD. This means that we will have to tidy up the Perl
  1273. ! stack and dispose of any temporary values ourselves. This is the
  1274. ! purpose of
  1275.   
  1276. !     ENTER ;
  1277. !     SAVETMPS ;
  1278.   
  1279.   at the start of the function, and
  1280.   
  1281. !     FREETMPS ;
  1282. !     LEAVE ;
  1283. ! at the end. The C<ENTER>/C<SAVETMPS> pair creates a boundary for any
  1284. ! temporaries we create.  This means that the temporaries we get rid of
  1285. ! will be limited to those which were created after these calls.
  1286. ! The C<FREETMPS>/C<LEAVE> pair will get rid of any values returned by
  1287. ! the Perl subroutine, plus it will also dump the mortal SV's we have
  1288. ! created.  Having C<ENTER>/C<SAVETMPS> at the beginning of the code
  1289. ! makes sure that no other mortals are destroyed.
  1290. ! Think of these macros as working a bit like using C<{> and C<}> in Perl
  1291. ! to limit the scope of local variables.
  1292.   
  1293. ! See the section I<Using Perl to dispose of temporaries> for details of
  1294. ! an alternative to using these macros.
  1295.   
  1296.   =item 3.
  1297.   
  1298.   The purpose of the macro C<SPAGAIN> is to refresh the local copy of the
  1299.   stack pointer. This is necessary because it is possible that the memory
  1300. ! allocated to the Perl stack has been re-allocated whilst in the
  1301. ! I<perl_call_pv> call.
  1302.   
  1303. ! If you are making use of the Perl stack pointer in your code you must
  1304. ! always refresh the your local copy using SPAGAIN whenever you make use
  1305.   of the I<perl_call_*> functions or any other Perl internal function.
  1306.   
  1307. ! =item 4.
  1308.   
  1309. ! Although only a single value was expected to be returned from I<Adder>,
  1310. ! it is still good practice to check the return code from I<perl_call_pv>
  1311. ! anyway.
  1312. ! Expecting a single value is not quite the same as knowing that there
  1313. ! will be one. If someone modified I<Adder> to return a list and we
  1314. ! didn't check for that possibility and take appropriate action the Perl
  1315. ! stack would end up in an inconsistent state. That is something you
  1316. ! I<really> don't want to ever happen.
  1317.   
  1318.   =item 5.
  1319.   
  1320. ! The C<POPi> macro is used here to pop the return value from the stack.
  1321. ! In this case we wanted an integer, so C<POPi> was used.
  1322.   
  1323.   
  1324. ! Here is the complete list of POP macros available, along with the types
  1325. ! they return.
  1326.   
  1327. !     POPs    SV
  1328. !     POPp    pointer
  1329. !     POPn    double
  1330. !     POPi    integer
  1331. !     POPl    long
  1332.   
  1333.   =item 6.
  1334.   
  1335. ! The final C<PUTBACK> is used to leave the Perl stack in a consistent
  1336. ! state before exiting the function.  This is necessary because when we
  1337. ! popped the return value from the stack with C<POPi> it updated only our
  1338. ! local copy of the stack pointer.  Remember, C<PUTBACK> sets the global
  1339. ! stack pointer to be the same as our local copy.
  1340.   
  1341.   =back
  1342.   
  1343.   
  1344. ! =head2 Returning a list of values
  1345.   
  1346. ! Now, let's extend the previous example to return both the sum of the
  1347. ! parameters and the difference.
  1348.   
  1349. ! Here is the Perl subroutine
  1350.   
  1351.       sub AddSubtract
  1352.       {
  1353. ***************
  1354. *** 484,490 ****
  1355.          ($a+$b, $a-$b) ;
  1356.       }
  1357.   
  1358.   and this is the C function
  1359.   
  1360.       static void
  1361. --- 695,700 ----
  1362. ***************
  1363. *** 507,523 ****
  1364.   
  1365.           SPAGAIN ;
  1366.   
  1367. !     if (count != 2)
  1368. !         croak("Big trouble\n") ;
  1369.   
  1370. !     printf ("%d - %d = %d\n", a, b, POPi) ;
  1371. !     printf ("%d + %d = %d\n", a, b, POPi) ;
  1372.   
  1373.           PUTBACK ;
  1374.           FREETMPS ;
  1375.           LEAVE ;
  1376.       }
  1377.   
  1378.   
  1379.   Notes
  1380.   
  1381. --- 717,741 ----
  1382.   
  1383.           SPAGAIN ;
  1384.   
  1385. !         if (count != 2)
  1386. !             croak("Big trouble\n") ;
  1387.   
  1388. !         printf ("%d - %d = %d\n", a, b, POPi) ;
  1389. !         printf ("%d + %d = %d\n", a, b, POPi) ;
  1390.   
  1391.           PUTBACK ;
  1392.           FREETMPS ;
  1393.           LEAVE ;
  1394.       }
  1395.   
  1396. + If I<call_AddSubtract> is called like this
  1397. +     call_AddSubtract(7, 4) ;
  1398. + then here is the output
  1399. +     7 - 4 = 3
  1400. +     7 + 4 = 11
  1401.   
  1402.   Notes
  1403.   
  1404. ***************
  1405. *** 525,546 ****
  1406.   
  1407.   =item 1.
  1408.   
  1409. ! We wanted array context, so we used G_ARRAY.
  1410.   
  1411.   =item 2.
  1412.   
  1413. ! Not surprisingly there are 2 POPi's this time  because we were retrieving 2
  1414. ! values from the stack. The main point to note is that they came off the stack in
  1415. ! reverse order.
  1416.   
  1417.   =back
  1418.   
  1419. ! =head2 Example 5: Returning Data from Perl via the parameter list
  1420.   
  1421.   It is also possible to return values directly via the parameter list -
  1422.   whether it is actually desirable to do it is another matter entirely.
  1423.   
  1424. ! The Perl sub, I<Inc>, below takes 2 parameters and increments each.
  1425.   
  1426.       sub Inc
  1427.       {
  1428. --- 743,819 ----
  1429.   
  1430.   =item 1.
  1431.   
  1432. ! We wanted array context, so G_ARRAY was used.
  1433.   
  1434.   =item 2.
  1435.   
  1436. ! Not surprisingly C<POPi> is used twice this time because we were
  1437. ! retrieving 2 values from the stack. The important thing to note is that
  1438. ! when using the C<POP*> macros they come off the stack in I<reverse>
  1439. ! order.
  1440.   
  1441.   =back
  1442.   
  1443. ! =head2 Returning a list in a scalar context
  1444. ! Say the Perl subroutine in the previous section was called in a scalar
  1445. ! context, like this
  1446. !     static void
  1447. !     call_AddSubScalar(a, b)
  1448. !     int a ;
  1449. !     int b ;
  1450. !     {
  1451. !         dSP ;
  1452. !         int count ;
  1453. !         int i ;
  1454. !         ENTER ;
  1455. !         SAVETMPS;
  1456. !         PUSHMARK(sp) ;
  1457. !         XPUSHs(sv_2mortal(newSViv(a)));
  1458. !         XPUSHs(sv_2mortal(newSViv(b)));
  1459. !         PUTBACK ;
  1460. !         count = perl_call_pv("AddSubtract", G_SCALAR);
  1461. !         SPAGAIN ;
  1462. !         printf ("Items Returned = %d\n", count) ;
  1463. !         for (i = 1 ; i <= count ; ++i)
  1464. !             printf ("Value %d = %d\n", i, POPi) ;
  1465. !         PUTBACK ;
  1466. !         FREETMPS ;
  1467. !         LEAVE ;
  1468. !     }
  1469. ! The other modification made is that I<call_AddSubScalar> will print the
  1470. ! number of items returned from the Perl subroutine and their value (for
  1471. ! simplicity it assumes that they are integer).  So if
  1472. ! I<call_AddSubScalar> is called
  1473. !     call_AddSubScalar(7, 4) ;
  1474. ! then the output will be
  1475. !     Items Returned = 1
  1476. !     Value 1 = 3
  1477. ! In this case the main point to note is that only the last item in the
  1478. ! list returned from the subroutine, I<Adder> actually made it back to
  1479. ! I<call_AddSubScalar>.
  1480. ! =head2 Returning Data from Perl via the parameter list
  1481.   
  1482.   It is also possible to return values directly via the parameter list -
  1483.   whether it is actually desirable to do it is another matter entirely.
  1484.   
  1485. ! The Perl subroutine, I<Inc>, below takes 2 parameters and increments
  1486. ! each directly.
  1487.   
  1488.       sub Inc
  1489.       {
  1490. ***************
  1491. *** 574,616 ****
  1492.           count = perl_call_pv("Inc", G_DISCARD);
  1493.   
  1494.           if (count != 0)
  1495. !             croak ("call_Inc : expected 0 return value from 'Inc', got %d\n", count) ;
  1496.   
  1497.           printf ("%d + 1 = %d\n", a, SvIV(sva)) ;
  1498.           printf ("%d + 1 = %d\n", b, SvIV(svb)) ;
  1499.   
  1500.           FREETMPS ;
  1501. !     LEAVE ; 
  1502.       }
  1503.   
  1504.   
  1505. ! To be able to access the two parameters that were pushed onto the stack 
  1506. ! after they return from I<perl_call_pv> it is necessary to make a note of
  1507. ! their addresses - thus the two variables C<sva> and C<svb>. 
  1508. ! The reason this is necessary is that
  1509. ! the area of the Perl stack which held them
  1510. ! will very likely have been overwritten by something else by the time control
  1511. ! returns from I<perl_call_pv>.
  1512.   
  1513.   
  1514.   
  1515.   
  1516. ! =head2 Example 6: Using G_EVAL
  1517. ! Now an example using G_EVAL. Below is a Perl sub which computes the 
  1518. ! difference of its 2 parameters. If this would result in a negative result,
  1519. ! the sub calls I<die>.
  1520.   
  1521.   
  1522.       sub Subtract
  1523.       {
  1524. !     my ($a, $b) = @_ ;
  1525.   
  1526.           die "death can be fatal\n" if $a < $b ;
  1527.   
  1528. !     $a - $b ;
  1529.       }
  1530.   
  1531.   and some C to call it
  1532. --- 847,886 ----
  1533.           count = perl_call_pv("Inc", G_DISCARD);
  1534.   
  1535.           if (count != 0)
  1536. !             croak ("call_Inc: expected 0 values from 'Inc', got %d\n",
  1537. !                    count) ;
  1538.   
  1539.           printf ("%d + 1 = %d\n", a, SvIV(sva)) ;
  1540.           printf ("%d + 1 = %d\n", b, SvIV(svb)) ;
  1541.   
  1542.           FREETMPS ;
  1543. !         LEAVE ;
  1544.       }
  1545.   
  1546. + To be able to access the two parameters that were pushed onto the stack
  1547. + after they return from I<perl_call_pv> it is necessary to make a note
  1548. + of their addresses - thus the two variables C<sva> and C<svb>.
  1549.   
  1550. ! The reason this is necessary is that the area of the Perl stack which
  1551. ! held them will very likely have been overwritten by something else by
  1552. ! the time control returns from I<perl_call_pv>.
  1553.   
  1554.   
  1555.   
  1556.   
  1557. ! =head2 Using G_EVAL
  1558.   
  1559. + Now an example using G_EVAL. Below is a Perl subroutine which computes
  1560. + the difference of its 2 parameters. If this would result in a negative
  1561. + result, the subroutine calls I<die>.
  1562.   
  1563.       sub Subtract
  1564.       {
  1565. !         my ($a, $b) = @_ ;
  1566.   
  1567.           die "death can be fatal\n" if $a < $b ;
  1568.   
  1569. !         $a - $b ;
  1570.       }
  1571.   
  1572.   and some C to call it
  1573. ***************
  1574. *** 622,628 ****
  1575.       {
  1576.           dSP ;
  1577.           int count ;
  1578. !     SV * sv ;
  1579.   
  1580.           ENTER ;
  1581.           SAVETMPS;
  1582. --- 892,898 ----
  1583.       {
  1584.           dSP ;
  1585.           int count ;
  1586. !         SV * sv ;
  1587.   
  1588.           ENTER ;
  1589.           SAVETMPS;
  1590. ***************
  1591. *** 634,665 ****
  1592.   
  1593.           count = perl_call_pv("Subtract", G_EVAL|G_SCALAR);
  1594.   
  1595. !     /* Check the eval first */
  1596.           sv = GvSV(gv_fetchpv("@", TRUE, SVt_PV));
  1597.           if (SvTRUE(sv))
  1598.               printf ("Uh oh - %s\n", SvPV(sv, na)) ;
  1599.   
  1600. !         SPAGAIN ;
  1601. !         if (count != 1)
  1602. !             croak ("call_Subtract : expected 1 return value from 'Subtract', got %d\n", count) ;
  1603. !     printf ("%d - %d = %d\n", a, b, POPi) ;
  1604.   
  1605.           PUTBACK ;
  1606.           FREETMPS ;
  1607.           LEAVE ;
  1608.       }
  1609.   
  1610.   If I<call_Subtract> is called thus
  1611.   
  1612. !     call_Subtract(4, 5)
  1613.   
  1614.   the following will be printed
  1615.   
  1616. !     Uh oh - death can be fatal
  1617.   
  1618.   Notes
  1619.   
  1620. --- 904,939 ----
  1621.   
  1622.           count = perl_call_pv("Subtract", G_EVAL|G_SCALAR);
  1623.   
  1624. !         SPAGAIN ;
  1625. !         /* Check the eval first */
  1626.           sv = GvSV(gv_fetchpv("@", TRUE, SVt_PV));
  1627.           if (SvTRUE(sv))
  1628. +         {
  1629.               printf ("Uh oh - %s\n", SvPV(sv, na)) ;
  1630. +             POPs ;
  1631. +         }
  1632. +         else
  1633. +         {
  1634. +             if (count != 1)
  1635. +                croak("call_Subtract: wanted 1 value from 'Subtract', got %d\n",
  1636. +                         count) ;
  1637.   
  1638. !             printf ("%d - %d = %d\n", a, b, POPi) ;
  1639. !         }
  1640.   
  1641.           PUTBACK ;
  1642.           FREETMPS ;
  1643.           LEAVE ;
  1644.       }
  1645.   
  1646.   If I<call_Subtract> is called thus
  1647.   
  1648. !     call_Subtract(4, 5)
  1649.   
  1650.   the following will be printed
  1651.   
  1652. !     Uh oh - death can be fatal
  1653.   
  1654.   Notes
  1655.   
  1656. ***************
  1657. *** 667,822 ****
  1658.   
  1659.   =item 1.
  1660.   
  1661. ! We want to be able to catch the I<die> so we have used the G_EVAL flag.
  1662. ! Not specifying this flag would mean that the program would terminate.
  1663.   
  1664.   =item 2.
  1665.   
  1666.   The code 
  1667.   
  1668. !         sv = GvSV(gv_fetchpv("@", TRUE, SVt_PV));
  1669. !         if (SvTRUE(sv))
  1670. !             printf ("Uh oh - %s\n", SvPVx(sv, na)) ;
  1671.   
  1672. ! is the equivalent of this bit of Perl
  1673.   
  1674. !     print "Uh oh - $@\n" if $@ ;
  1675.   
  1676.   
  1677.   
  1678.   =back
  1679.   
  1680.   
  1681. ! =head2 Example 7: Using perl_call_sv
  1682.   
  1683. ! In all the previous examples I have 'hard-wried' the name of the Perl sub to
  1684. ! be called from C. 
  1685. ! Sometimes though, it is necessary to be able to specify the name
  1686. ! of the Perl sub from within the Perl script.
  1687.   
  1688.   Consider the Perl code below
  1689.   
  1690. !     sub fred
  1691. !     {
  1692. !         print "Hello there\n" ;
  1693. !     }
  1694.   
  1695. !     CallSub("fred") ;
  1696.   
  1697.   
  1698. ! here is a snippet of XSUB which defines I<CallSub>.
  1699.   
  1700. !     void
  1701. !     CallSub(name)
  1702. !         char *    name
  1703. !         CODE:
  1704. !         PUSHMARK(sp) ;
  1705. !         perl_call_pv(name, G_DISCARD|G_NOARGS) ;
  1706.   
  1707. ! That is fine as far as it goes. The thing is, it only allows the Perl sub to be
  1708. ! specified as a string. 
  1709. ! For perl 4 this was adequate, but Perl 5 allows references to 
  1710. ! subs and anonymous subs. This is where I<perl_call_sv> is useful.
  1711.   
  1712. ! The code below for I<CallSub> is identical to the previous time except that the
  1713. ! C<name> parameter is now defined as an SV* and we use I<perl_call_sv> instead of
  1714. ! I<perl_call_pv>.
  1715.   
  1716. !     void
  1717. !     CallSub(name)
  1718. !         SV*    name
  1719. !         CODE:
  1720. !         PUSHMARK(sp) ;
  1721. !         perl_call_sv(name, G_DISCARD|G_NOARGS) ;
  1722.   
  1723. ! As we are using an SV to call I<fred> the following can all be used
  1724.   
  1725. !     CallSub("fred") ;
  1726. !     Callsub(\&fred) ;
  1727. !     $ref = \&fred ;
  1728. !     CallSub($ref) ;
  1729. !     CallSub( sub { print "Hello there\n" } ) ;
  1730.   
  1731. ! As you can see, I<perl_call_sv> gives you greater flexibility in how you 
  1732. ! can specify the Perl sub.
  1733.   
  1734. ! =head2 Example 8: Using perl_call_argv
  1735.   
  1736. ! Here is a Perl sub which prints whatever parameters are passed to it.
  1737.   
  1738. !     sub PrintList
  1739. !     {
  1740. !         my(@list) = @_ ;
  1741.   
  1742. !         foreach (@list) { print "$_\n" }
  1743. !     }
  1744.   
  1745. ! and here is an example of I<perl_call_argv> which will call I<PrintList>.
  1746.   
  1747. !     call_PrintList
  1748. !     {
  1749. !         dSP ;
  1750. !         char * words[] = {"alpha", "beta", "gamma", "delta", NULL } ;
  1751.   
  1752. !         perl_call_argv("PrintList", words, G_DISCARD) ;
  1753. !     }
  1754.   
  1755. ! Note that it is not necessary to call C<PUSHMARK> in this instance. This is
  1756. ! because I<perl_call_argv> will do it for you.
  1757.   
  1758. ! =head2 Example 9: Using perl_call_method
  1759.   
  1760. ! [This section is under construction]
  1761.   
  1762.   Consider the following Perl code
  1763.   
  1764. !     {
  1765. !       package Mine ;
  1766.   
  1767. !       sub new     { bless [@_] }
  1768. !       sub Display { print $_[0][1], "\n" }
  1769. !     }
  1770.   
  1771. !     $a = new Mine ('red', 'green', 'blue') ;
  1772. !     call_Display($a, 'Display') ;
  1773.   
  1774. ! The method C<Display> just prints out the first element of the list.
  1775. ! Here is a XSUB implementation of I<call_Display>.
  1776.   
  1777. !     void
  1778. !     call_Display(ref, method)
  1779. !             SV *    ref
  1780. !             char *  method
  1781. !             CODE:
  1782. !             PUSHMARK(sp);
  1783. !             XPUSHs(ref);
  1784. !             PUTBACK;
  1785.   
  1786. !             perl_call_method(method, G_DISCARD) ;
  1787.   
  1788.   
  1789.   
  1790.   
  1791. ! =head2 Strategies for storing Context Information
  1792.   
  1793. ! [This section is under construction]
  1794.   
  1795. ! One of the trickiest problems to overcome when designing a callback interface 
  1796. ! is figuring 
  1797. ! out how to store the mapping between the C callback functions and the 
  1798. ! Perl equivalent.
  1799.   
  1800. - Consider the following example.
  1801.   
  1802.   =head2 Alternate Stack Manipulation
  1803.   
  1804. - [This section is under construction]
  1805.   
  1806. ! Although I have only made use of the POP* macros to access values returned 
  1807. ! from Perl subs, it is also possible to bypass these macros and read the 
  1808. ! stack directly.
  1809.   
  1810. ! The code below is example 4 recoded to 
  1811.   
  1812.   =head1 SEE ALSO
  1813.   
  1814. --- 941,1822 ----
  1815.   
  1816.   =item 1.
  1817.   
  1818. ! We want to be able to catch the I<die> so we have used the G_EVAL
  1819. ! flag.  Not specifying this flag would mean that the program would
  1820. ! terminate immediately at the I<die> statement in the subroutine
  1821. ! I<Subtract>.
  1822.   
  1823.   =item 2.
  1824.   
  1825.   The code 
  1826.   
  1827. !     sv = GvSV(gv_fetchpv("@", TRUE, SVt_PV));
  1828. !     if (SvTRUE(sv))
  1829. !     {
  1830. !         printf ("Uh oh - %s\n", SvPVx(sv, na)) ;
  1831. !         POPs ;
  1832. !     }
  1833.   
  1834. ! is the direct equivalent of this bit of Perl
  1835.   
  1836. !     print "Uh oh - $@\n" if $@ ;
  1837.   
  1838. + =item 3.
  1839.   
  1840. + Note that the stack is popped using C<POPs> in the block where
  1841. + C<SvTRUE(sv)> is true.  This is necessary because whenever a
  1842. + I<perl_call_*> function invoked with G_EVAL|G_SCALAR returns an error,
  1843. + the top of the stack holds the value I<undef>. Since we want the
  1844. + program to continue after detecting this error, it is essential that
  1845. + the stack is tidied up by removing the I<undef>.
  1846.   
  1847.   =back
  1848.   
  1849.   
  1850. ! =head2 Using perl_call_sv
  1851.   
  1852. ! In all the previous examples I have 'hard-wired' the name of the Perl
  1853. ! subroutine to be called from C.  Most of the time though, it is more
  1854. ! convenient to be able to specify the name of the Perl subroutine from
  1855. ! within the Perl script.
  1856.   
  1857.   Consider the Perl code below
  1858.   
  1859. !     sub fred
  1860. !     {
  1861. !         print "Hello there\n" ;
  1862. !     }
  1863. !     CallSubPV("fred") ;
  1864. ! Here is a snippet of XSUB which defines I<CallSubPV>.
  1865. !     void
  1866. !     CallSubPV(name)
  1867. !         char *    name
  1868. !         CODE:
  1869. !         PUSHMARK(sp) ;
  1870. !         perl_call_pv(name, G_DISCARD|G_NOARGS) ;
  1871. ! That is fine as far as it goes. The thing is, the Perl subroutine 
  1872. ! can be specified only as a string.  For Perl 4 this was adequate,
  1873. ! but Perl 5 allows references to subroutines and anonymous subroutines.
  1874. ! This is where I<perl_call_sv> is useful.
  1875. ! The code below for I<CallSubSV> is identical to I<CallSubPV> except
  1876. ! that the C<name> parameter is now defined as an SV* and we use
  1877. ! I<perl_call_sv> instead of I<perl_call_pv>.
  1878. !     void
  1879. !     CallSubSV(name)
  1880. !         SV *    name
  1881. !         CODE:
  1882. !         PUSHMARK(sp) ;
  1883. !         perl_call_sv(name, G_DISCARD|G_NOARGS) ;
  1884. ! Since we are using an SV to call I<fred> the following can all be used
  1885. !     CallSubSV("fred") ;
  1886. !     CallSubSV(\&fred) ;
  1887. !     $ref = \&fred ;
  1888. !     CallSubSV($ref) ;
  1889. !     CallSubSV( sub { print "Hello there\n" } ) ;
  1890. ! As you can see, I<perl_call_sv> gives you much greater flexibility in
  1891. ! how you can specify the Perl subroutine.
  1892. ! You should note that if it is necessary to store the SV (C<name> in the
  1893. ! example above) which corresponds to the Perl subroutine so that it can
  1894. ! be used later in the program, it not enough to just store a copy of the
  1895. ! pointer to the SV. Say the code above had been like this
  1896. !     static SV * rememberSub ;
  1897. !     void
  1898. !     SaveSub1(name)
  1899. !         SV *    name
  1900. !         CODE:
  1901. !         rememberSub = name ;
  1902. !     void
  1903. !     CallSavedSub1()
  1904. !         CODE:
  1905. !         PUSHMARK(sp) ;
  1906. !         perl_call_sv(rememberSub, G_DISCARD|G_NOARGS) ;
  1907. ! The reason this is wrong is that by the time you come to use the
  1908. ! pointer C<rememberSub> in C<CallSavedSub1>, it may or may not still refer
  1909. ! to the Perl subroutine that was recorded in C<SaveSub1>.  This is
  1910. ! particularly true for these cases
  1911. !     SaveSub1(\&fred) ;
  1912. !     CallSavedSub1() ;
  1913. !     SaveSub1( sub { print "Hello there\n" } ) ;
  1914. !     CallSavedSub1() ;
  1915. ! By the time each of the C<SaveSub1> statements above have been executed,
  1916. ! the SV*'s which corresponded to the parameters will no longer exist.
  1917. ! Expect an error message from Perl of the form
  1918. !     Can't use an undefined value as a subroutine reference at ...
  1919. ! for each of the C<CallSavedSub1> lines.
  1920.   
  1921. ! Similarly, with this code 
  1922.   
  1923. +     $ref = \&fred ;
  1924. +     SaveSub1($ref) ;
  1925. +     $ref = 47 ;
  1926. +     CallSavedSub1() ;
  1927.   
  1928. ! you can expect one of these messages (which you actually get is dependant on 
  1929. ! the version of Perl you are using) 
  1930.   
  1931. !     Not a CODE reference at ...
  1932. !     Undefined subroutine &main::47 called ...
  1933.   
  1934. ! The variable C<$ref> may have referred to the subroutine C<fred>
  1935. ! whenever the call to C<SaveSub1> was made but by the time
  1936. ! C<CallSavedSub1> gets called it now holds the number C<47>. Since we
  1937. ! saved only a pointer to the original SV in C<SaveSub1>, any changes to
  1938. ! C<$ref> will be tracked by the pointer C<rememberSub>. This means that
  1939. ! whenever C<CallSavedSub1> gets called, it will attempt to execute the
  1940. ! code which is referenced by the SV* C<rememberSub>.  In this case
  1941. ! though, it now refers to the integer C<47>, so expect Perl to complain
  1942. ! loudly.
  1943.   
  1944. ! A similar but more subtle problem is illustrated with this code
  1945.   
  1946. !     $ref = \&fred ;
  1947. !     SaveSub1($ref) ;
  1948. !     $ref = \&joe ;
  1949. !     CallSavedSub1() ;
  1950.   
  1951. ! This time whenever C<CallSavedSub1> get called it will execute the Perl
  1952. ! subroutine C<joe> (assuming it exists) rather than C<fred> as was 
  1953. ! originally requested in the call to C<SaveSub1>.
  1954.   
  1955. ! To get around these problems it is necessary to take a full copy of the
  1956. ! SV.  The code below shows C<SaveSub2> modified to do that
  1957.   
  1958. !     static SV * keepSub = (SV*)NULL ;
  1959.   
  1960. !     void
  1961. !     SaveSub2(name)
  1962. !         SV *    name
  1963. !         CODE:
  1964. !          /* Take a copy of the callback */
  1965. !         if (keepSub == (SV*)NULL)
  1966. !             /* First time, so create a new SV */
  1967. !             keepSub = newSVsv(name) ;
  1968. !         else
  1969. !             /* Been here before, so overwrite */
  1970. !             SvSetSV(keepSub, name) ;
  1971. !     void
  1972. !     CallSavedSub2()
  1973. !         CODE:
  1974. !         PUSHMARK(sp) ;
  1975. !         perl_call_sv(keepSub, G_DISCARD|G_NOARGS) ;
  1976. ! In order to avoid creating a new SV every time C<SaveSub2> is called,
  1977. ! the function first checks to see if it has been called before.  If not,
  1978. ! then space for a new SV is allocated and the reference to the Perl
  1979. ! subroutine, C<name> is copied to the variable C<keepSub> in one
  1980. ! operation using C<newSVsv>.  Thereafter, whenever C<SaveSub2> is called
  1981. ! the existing SV, C<keepSub>, is overwritten with the new value using
  1982. ! C<SvSetSV>.
  1983.   
  1984. ! =head2 Using perl_call_argv
  1985.   
  1986. ! Here is a Perl subroutine which prints whatever parameters are passed
  1987. ! to it.
  1988.   
  1989. !     sub PrintList
  1990. !     {
  1991. !         my(@list) = @_ ;
  1992. !         foreach (@list) { print "$_\n" }
  1993. !     }
  1994.   
  1995. ! and here is an example of I<perl_call_argv> which will call
  1996. ! I<PrintList>.
  1997.   
  1998. !     static char * words[] = {"alpha", "beta", "gamma", "delta", NULL} ;
  1999.   
  2000. !     static void
  2001. !     call_PrintList()
  2002. !     {
  2003. !         dSP ;
  2004.   
  2005. !         perl_call_argv("PrintList", G_DISCARD, words) ;
  2006. !     }
  2007.   
  2008. ! Note that it is not necessary to call C<PUSHMARK> in this instance.
  2009. ! This is because I<perl_call_argv> will do it for you.
  2010.   
  2011. ! =head2 Using perl_call_method
  2012.   
  2013.   Consider the following Perl code
  2014.   
  2015. !     {
  2016. !         package Mine ;
  2017. !         sub new
  2018. !         {
  2019. !             my($type) = shift ;
  2020. !             bless [@_]
  2021. !         }
  2022. !         sub Display
  2023. !         {
  2024. !             my ($self, $index) = @_ ;
  2025. !             print "$index: $$self[$index]\n" ;
  2026. !         }
  2027. !         sub PrintID
  2028. !         {
  2029. !             my($class) = @_ ;
  2030. !             print "This is Class $class version 1.0\n" ;
  2031. !         }
  2032. !     }
  2033.   
  2034. ! It just implements a very simple class to manage an array.  Apart from
  2035. ! the constructor, C<new>, it declares methods, one static and one
  2036. ! virtual. The static method, C<PrintID>, simply prints out the class
  2037. ! name and a version number. The virtual method, C<Display>, prints out a
  2038. ! single element of the array.  Here is an all Perl example of using it.
  2039. !     $a = new Mine ('red', 'green', 'blue') ;
  2040. !     $a->Display(1) ;
  2041. !     PrintID Mine;
  2042.   
  2043. ! will print
  2044.   
  2045. !     1: green
  2046. !     This is Class Mine version 1.0 
  2047.   
  2048. ! Calling a Perl method from C is fairly straightforward. The following
  2049. ! things are required
  2050.   
  2051. ! =over 5
  2052.   
  2053. + =item *
  2054.   
  2055. + a reference to the object for a virtual method or the name of the class
  2056. + for a static method.
  2057.   
  2058. + =item *
  2059.   
  2060. ! the name of the method.
  2061.   
  2062. ! =item *
  2063.   
  2064. ! any other parameters specific to the method.
  2065. ! =back
  2066. ! Here is a simple XSUB which illustrates the mechanics of calling both
  2067. ! the C<PrintID> and C<Display> methods from C.
  2068. !     void
  2069. !     call_Method(ref, method, index)
  2070. !         SV *    ref
  2071. !         char *    method
  2072. !         int        index
  2073. !         CODE:
  2074. !         PUSHMARK(sp);
  2075. !         XPUSHs(ref);
  2076. !         XPUSHs(sv_2mortal(newSViv(index))) ;
  2077. !         PUTBACK;
  2078. !         perl_call_method(method, G_DISCARD) ;
  2079. !     void
  2080. !     call_PrintID(class, method)
  2081. !         char *    class
  2082. !         char *    method
  2083. !         CODE:
  2084. !         PUSHMARK(sp);
  2085. !         XPUSHs(sv_2mortal(newSVpv(class, 0))) ;
  2086. !         PUTBACK;
  2087. !         perl_call_method(method, G_DISCARD) ;
  2088. ! So the methods C<PrintID> and C<Display> can be invoked like this
  2089. !     $a = new Mine ('red', 'green', 'blue') ;
  2090. !     call_Method($a, 'Display', 1) ;
  2091. !     call_PrintID('Mine', 'PrintID') ;
  2092. ! The only thing to note is that in both the static and virtual methods,
  2093. ! the method name is not passed via the stack - it is used as the first
  2094. ! parameter to I<perl_call_method>.
  2095. ! =head2 Using GIMME
  2096. ! Here is a trivial XSUB which prints the context in which it is 
  2097. ! currently executing.
  2098. !     void
  2099. !     PrintContext()
  2100. !         CODE:
  2101. !         if (GIMME == G_SCALAR)
  2102. !             printf ("Context is Scalar\n") ;
  2103. !         else
  2104. !             printf ("Context is Array\n") ;
  2105. ! and here is some Perl to test it
  2106. !     $a = PrintContext ;
  2107. !     @a = PrintContext ;
  2108. ! The output from that will be
  2109. !     Context is Scalar
  2110. !     Context is Array
  2111. ! =head2 Using Perl to dispose of temporaries
  2112. ! In the examples given to date, any temporaries created in the callback
  2113. ! (i.e. parameters passed on the stack to the I<perl_call_*> function or
  2114. ! values returned via the stack) have been freed by one of these methods
  2115. ! =over 5
  2116. ! =item *
  2117. ! specifying the G_DISCARD flag with I<perl_call_*>.
  2118. ! =item *
  2119. ! explicitly disposed of using the C<ENTER>/C<SAVETMPS> -
  2120. ! C<FREETMPS>/C<LEAVE> pairing.
  2121. ! =back
  2122. ! There is another method which can be used, namely letting Perl do it
  2123. ! for you automatically whenever it regains control after the callback
  2124. ! has terminated.  This is done by simply not using the
  2125. !     ENTER ;
  2126. !     SAVETMPS ;
  2127. !     ...
  2128. !     FREETMPS ;
  2129. !     LEAVE ;
  2130. ! sequence in the callback (and not, of course, specifying the G_DISCARD
  2131. ! flag).
  2132. ! If you are going to use this method you have to be aware of a possible
  2133. ! memory leak which can arise under very specific circumstances.  To
  2134. ! explain these circumstances you need to know a bit about the flow of
  2135. ! control between Perl and the callback routine.
  2136. ! The examples given at the start of the document (an error handler and
  2137. ! an event driven program) are typical of the two main sorts of flow
  2138. ! control that you are likely to encounter with callbacks.  There is a
  2139. ! very important distinction between them, so pay attention.
  2140. ! In the first example, an error handler, the flow of control could be as
  2141. ! follows.  You have created an interface to an external library.
  2142. ! Control can reach the external library like this
  2143. !     perl --> XSUB --> external library
  2144. ! Whilst control is in the library, an error condition occurs. You have
  2145. ! previously set up a Perl callback to handle this situation, so it will
  2146. ! get executed. Once the callback has finished, control will drop back to
  2147. ! Perl again.  Here is what the flow of control will be like in that
  2148. ! situation
  2149. !     perl --> XSUB --> external library
  2150. !                       ...
  2151. !                       error occurs
  2152. !                       ...
  2153. !                       external library --> perl_call --> perl
  2154. !                                                           |
  2155. !     perl <-- XSUB <-- external library <-- perl_call <----+
  2156. ! After processing of the error using I<perl_call_*> is completed,
  2157. ! control reverts back to Perl more or less immediately.
  2158. ! In the diagram, the further right you go the more deeply nested the
  2159. ! scope is.  It is only when control is back with perl on the extreme
  2160. ! left of the diagram that you will have dropped back to the enclosing
  2161. ! scope and any temporaries you have left hanging around will be freed.
  2162. ! In the second example, an event driven program, the flow of control
  2163. ! will be more like this
  2164. !     perl --> XSUB --> event handler
  2165. !                       ...
  2166. !                       event handler --> perl_call --> perl 
  2167. !                                                        |
  2168. !                       event handler <-- perl_call --<--+
  2169. !                       ...
  2170. !                       event handler --> perl_call --> perl 
  2171. !                                                        |
  2172. !                       event handler <-- perl_call --<--+
  2173. !                       ...
  2174. !                       event handler --> perl_call --> perl 
  2175. !                                                        |
  2176. !                       event handler <-- perl_call --<--+
  2177. ! In this case the flow of control can consist of only the repeated
  2178. ! sequence
  2179. !     event handler --> perl_call --> perl
  2180. ! for the practically the complete duration of the program.  This means
  2181. ! that control may I<never> drop back to the surrounding scope in Perl at
  2182. ! the extreme left.
  2183. ! So what is the big problem? Well, if you are expecting Perl to tidy up
  2184. ! those temporaries for you, you might be in for a long wait.  For Perl
  2185. ! to actually dispose of your temporaries, control must drop back to the
  2186. ! enclosing scope at some stage.  In the event driven scenario that may
  2187. ! never happen.  This means that as time goes on, your program will
  2188. ! create more and more temporaries, none of which will ever be freed. As
  2189. ! each of these temporaries consumes some memory your program will
  2190. ! eventually consume all the available memory in your system - kapow!
  2191. ! So here is the bottom line - if you are sure that control will revert
  2192. ! back to the enclosing Perl scope fairly quickly after the end of your
  2193. ! callback, then it isn't absolutely necessary to explicitly dispose of
  2194. ! any temporaries you may have created. Mind you, if you are at all
  2195. ! uncertain about what to do, it doesn't do any harm to tidy up anyway.
  2196. ! =head2 Strategies for storing Callback Context Information
  2197. ! Potentially one of the trickiest problems to overcome when designing a
  2198. ! callback interface can be figuring out how to store the mapping between
  2199. ! the C callback function and the Perl equivalent.
  2200. ! To help understand why this can be a real problem first consider how a
  2201. ! callback is set up in an all C environment.  Typically a C API will
  2202. ! provide a function to register a callback.  This will expect a pointer
  2203. ! to a function as one of its parameters.  Below is a call to a
  2204. ! hypothetical function C<register_fatal> which registers the C function
  2205. ! to get called when a fatal error occurs.
  2206. !     register_fatal(cb1) ;
  2207. ! The single parameter C<cb1> is a pointer to a function, so you must
  2208. ! have defined C<cb1> in your code, say something like this
  2209. !     static void
  2210. !     cb1()
  2211. !     {
  2212. !         printf ("Fatal Error\n") ;
  2213. !         exit(1) ;
  2214. !     }
  2215. ! Now change that to call a Perl subroutine instead
  2216. !     static SV * callback = (SV*)NULL;
  2217. !     static void
  2218. !     cb1()
  2219. !     {
  2220. !         dSP ;
  2221. !         PUSHMARK(sp) ;
  2222. !         /* Call the Perl sub to process the callback */
  2223. !         perl_call_sv(callback, G_DISCARD) ;
  2224. !     }
  2225. !     void
  2226. !     register_fatal(fn)
  2227. !         SV *    fn
  2228. !         CODE:
  2229. !         /* Remember the Perl sub */
  2230. !         if (callback == (SV*)NULL)
  2231. !             callback = newSVsv(fn) ;
  2232. !         else
  2233. !             SvSetSV(callback, fn) ;
  2234. !         /* register the callback with the external library */
  2235. !         register_fatal(cb1) ;
  2236. ! where the Perl equivalent of C<register_fatal> and the callback it
  2237. ! registers, C<pcb1>, might look like this
  2238. !     # Register the sub pcb1
  2239. !     register_fatal(\&pcb1) ;
  2240. !     sub pcb1
  2241. !     {
  2242. !         die "I'm dying...\n" ;
  2243. !     }
  2244. ! The mapping between the C callback and the Perl equivalent is stored in
  2245. ! the global variable C<callback>.
  2246. ! This will be adequate if you ever need to have only 1 callback
  2247. ! registered at any time. An example could be an error handler like the
  2248. ! code sketched out above. Remember though, repeated calls to
  2249. ! C<register_fatal> will replace the previously registered callback
  2250. ! function with the new one.
  2251. ! Say for example you want to interface to a library which allows asynchronous
  2252. ! file i/o.  In this case you may be able to register a callback whenever
  2253. ! a read operation has completed. To be of any use we want to be able to
  2254. ! call separate Perl subroutines for each file that is opened.  As it
  2255. ! stands, the error handler example above would not be adequate as it
  2256. ! allows only a single callback to be defined at any time. What we
  2257. ! require is a means of storing the mapping between the opened file and
  2258. ! the Perl subroutine we want to be called for that file.
  2259. ! Say the i/o library has a function C<asynch_read> which associates a C
  2260. ! function C<ProcessRead> with a file handle C<fh> - this assumes that it
  2261. ! has also provided some routine to open the file and so obtain the file
  2262. ! handle.
  2263. !     asynch_read(fh, ProcessRead)
  2264. ! This may expect the C I<ProcessRead> function of this form
  2265. !     void
  2266. !     ProcessRead(fh, buffer)
  2267. !     int    fh ;
  2268. !     char *    buffer ;
  2269. !     {
  2270. !          ... 
  2271. !     }
  2272. ! To provide a Perl interface to this library we need to be able to map
  2273. ! between the C<fh> parameter and the Perl subroutine we want called.  A
  2274. ! hash is a convenient mechanism for storing this mapping.  The code
  2275. ! below shows a possible implementation
  2276. !     static HV * Mapping = (HV*)NULL ;
  2277. !     void
  2278. !     asynch_read(fh, callback)
  2279. !         int    fh
  2280. !         SV *    callback
  2281. !         CODE:
  2282. !         /* If the hash doesn't already exist, create it */
  2283. !         if (Mapping == (HV*)NULL)
  2284. !             Mapping = newHV() ;
  2285. !         /* Save the fh -> callback mapping */
  2286. !         hv_store(Mapping, (char*)&fh, sizeof(fh), newSVsv(callback), 0) ;
  2287. !         /* Register with the C Library */
  2288. !         asynch_read(fh, asynch_read_if) ;
  2289. ! and C<asynch_read_if> could look like this
  2290. !     static void
  2291. !     asynch_read_if(fh, buffer)
  2292. !     int    fh ;
  2293. !     char *    buffer ;
  2294. !     {
  2295. !         dSP ;
  2296. !         SV ** sv ;
  2297. !         /* Get the callback associated with fh */
  2298. !         sv =  hv_fetch(Mapping, (char*)&fh , sizeof(fh), FALSE) ;
  2299. !         if (sv == (SV**)NULL)
  2300. !             croak("Internal error...\n") ;
  2301. !         PUSHMARK(sp) ;
  2302. !         XPUSHs(sv_2mortal(newSViv(fh))) ;
  2303. !         XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
  2304. !         PUTBACK ;
  2305. !         /* Call the Perl sub */
  2306. !         perl_call_sv(*sv, G_DISCARD) ;
  2307. !     }
  2308. ! For completeness, here is C<asynch_close>.  This shows how to remove
  2309. ! the entry from the hash C<Mapping>.
  2310. !     void
  2311. !     asynch_close(fh)
  2312. !         int    fh
  2313. !         CODE:
  2314. !         /* Remove the entry from the hash */
  2315. !         (void) hv_delete(Mapping, (char*)&fh, sizeof(fh), G_DISCARD) ;
  2316. !         /* Now call the real asynch_close */
  2317. !         asynch_close(fh) ;
  2318. ! So the Perl interface would look like this
  2319. !     sub callback1
  2320. !     {
  2321. !         my($handle, $buffer) = @_ ;
  2322. !     }
  2323. !     # Register the Perl callback
  2324. !     asynch_read($fh, \&callback1) ;
  2325. !     asynch_close($fh) ;
  2326. ! The mapping between the C callback and Perl is stored in the global
  2327. ! hash C<Mapping> this time. Using a hash has the distinct advantage that
  2328. ! it allows an unlimited number of callbacks to be registered.
  2329. ! What if the interface provided by the C callback doesn't contain a
  2330. ! parameter which allows the file handle to Perl subroutine mapping?  Say
  2331. ! in the asynchronous i/o package, the callback function gets passed only
  2332. ! the C<buffer> parameter like this
  2333. !     void
  2334. !     ProcessRead(buffer)
  2335. !     char *    buffer ;
  2336. !     {
  2337. !         ...
  2338. !     }
  2339. ! Without the file handle there is no straightforward way to map from the
  2340. ! C callback to the Perl subroutine.
  2341. ! In this case a possible way around this problem is to pre-define a
  2342. ! series of C functions to act as the interface to Perl, thus
  2343. !     #define MAX_CB        3
  2344. !     #define NULL_HANDLE    -1
  2345. !     typedef void (*FnMap)() ;
  2346. !     struct MapStruct {
  2347. !         FnMap    Function ;
  2348. !         SV *     PerlSub ;
  2349. !         int      Handle ;
  2350. !       } ;
  2351. !     static void  fn1() ;
  2352. !     static void  fn2() ;
  2353. !     static void  fn3() ;
  2354. !     static struct MapStruct Map [MAX_CB] =
  2355. !         {
  2356. !             { fn1, NULL, NULL_HANDLE },
  2357. !             { fn2, NULL, NULL_HANDLE },
  2358. !             { fn3, NULL, NULL_HANDLE }
  2359. !         } ;
  2360. !     static void
  2361. !     Pcb(index, buffer)
  2362. !     int index ;
  2363. !     char * buffer ;
  2364. !     {
  2365. !         dSP ;
  2366. !         PUSHMARK(sp) ;
  2367. !         XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
  2368. !         PUTBACK ;
  2369. !         /* Call the Perl sub */
  2370. !         perl_call_sv(Map[index].PerlSub, G_DISCARD) ;
  2371. !     }
  2372. !     static void
  2373. !     fn1(buffer)
  2374. !     char * buffer ;
  2375. !     {
  2376. !         Pcb(0, buffer) ;
  2377. !     }
  2378. !     static void
  2379. !     fn2(buffer)
  2380. !     char * buffer ;
  2381. !     {
  2382. !         Pcb(1, buffer) ;
  2383. !     }
  2384. !     static void
  2385. !     fn3(buffer)
  2386. !     char * buffer ;
  2387. !     {
  2388. !         Pcb(2, buffer) ;
  2389. !     }
  2390. !     void
  2391. !     array_asynch_read(fh, callback)
  2392. !         int        fh
  2393. !         SV *    callback
  2394. !         CODE:
  2395. !         int index ;
  2396. !         int null_index = MAX_CB ;
  2397. !         /* Find the same handle or an empty entry */
  2398. !         for (index = 0 ; index < MAX_CB ; ++index)
  2399. !         {
  2400. !             if (Map[index].Handle == fh)
  2401. !                 break ;
  2402. !             if (Map[index].Handle == NULL_HANDLE)
  2403. !                 null_index = index ;
  2404. !         }
  2405. !         if (index == MAX_CB && null_index == MAX_CB)
  2406. !             croak ("Too many callback functions registered\n") ;
  2407. !         if (index == MAX_CB)
  2408. !             index = null_index ;
  2409. !         /* Save the file handle */
  2410. !         Map[index].Handle = fh ;
  2411. !         /* Remember the Perl sub */
  2412. !         if (Map[index].PerlSub == (SV*)NULL)
  2413. !             Map[index].PerlSub = newSVsv(callback) ;
  2414. !         else
  2415. !             SvSetSV(Map[index].PerlSub, callback) ;
  2416. !         asynch_read(fh, Map[index].Function) ;
  2417. !     void
  2418. !     array_asynch_close(fh)
  2419. !         int    fh
  2420. !         CODE:
  2421. !         int index ;
  2422. !         /* Find the file handle */
  2423. !         for (index = 0; index < MAX_CB ; ++ index)
  2424. !             if (Map[index].Handle == fh)
  2425. !                 break ;
  2426. !         if (index == MAX_CB)
  2427. !             croak ("could not close fh %d\n", fh) ;
  2428. !         Map[index].Handle = NULL_HANDLE ;
  2429. !         SvREFCNT_dec(Map[index].PerlSub) ;
  2430. !         Map[index].PerlSub = (SV*)NULL ;
  2431. !         asynch_close(fh) ;
  2432. ! In this case the functions C<fn1>, C<fn2> and C<fn3> are used to
  2433. ! remember the Perl subroutine to be called. Each of the functions holds
  2434. ! a separate hard-wired index which is used in the function C<Pcb> to
  2435. ! access the C<Map> array and actually call the Perl subroutine.
  2436. ! There are some obvious disadvantages with this technique.
  2437. ! Firstly, the code is considerably more complex than with the previous
  2438. ! example.
  2439. ! Secondly, there is a hard-wired limit (in this case 3) to the number of
  2440. ! callbacks that can exist simultaneously. The only way to increase the
  2441. ! limit is by modifying the code to add more functions and then
  2442. ! re-compiling.  None the less, as long as the number of functions is
  2443. ! chosen with some care, it is still a workable solution and in some
  2444. ! cases is the only one available.
  2445. ! To summarize, here are a number of possible methods for you to consider
  2446. ! for storing the mapping between C and the Perl callback
  2447. ! =over 5
  2448. ! =item 1. Ignore the problem - Allow only 1 callback
  2449. ! For a lot of situations, like interfacing to an error handler, this may
  2450. ! be a perfectly adequate solution.
  2451. ! =item 2. Create a sequence of callbacks - hard wired limit
  2452. ! If it is impossible to tell from the parameters passed back from the C
  2453. ! callback what the context is, then you may need to create a sequence of C
  2454. ! callback interface functions, and store pointers to each in an array.
  2455. ! =item 3. Use a parameter to map to the Perl callback
  2456. ! A hash is an ideal mechanism to store the mapping between C and Perl.
  2457. ! =back
  2458.   
  2459.   
  2460.   =head2 Alternate Stack Manipulation
  2461.   
  2462.   
  2463. ! Although I have made use of only the C<POP*> macros to access values
  2464. ! returned from Perl subroutines, it is also possible to bypass these
  2465. ! macros and read the stack using the C<ST> macro (See L<perlapi> for a
  2466. ! full description of the C<ST> macro).
  2467. ! Most of the time the C<POP*> macros should be adequate, the main
  2468. ! problem with them is that they force you to process the returned values
  2469. ! in sequence. This may not be the most suitable way to process the
  2470. ! values in some cases. What we want is to be able to access the stack in
  2471. ! a random order. The C<ST> macro as used when coding an XSUB is ideal
  2472. ! for this purpose.
  2473. ! The code below is the example given in the section I<Returning a list
  2474. ! of values> recoded to use C<ST> instead of C<POP*>.
  2475. !     static void
  2476. !     call_AddSubtract2(a, b)
  2477. !     int a ;
  2478. !     int b ;
  2479. !     {
  2480. !         dSP ;
  2481. !         I32 ax ;
  2482. !         int count ;
  2483. !         ENTER ;
  2484. !         SAVETMPS;
  2485. !         PUSHMARK(sp) ;
  2486. !         XPUSHs(sv_2mortal(newSViv(a)));
  2487. !         XPUSHs(sv_2mortal(newSViv(b)));
  2488. !         PUTBACK ;
  2489. !         count = perl_call_pv("AddSubtract", G_ARRAY);
  2490. !         SPAGAIN ;
  2491. !         sp -= count ;
  2492. !         ax = (sp - stack_base) + 1 ;
  2493. !         if (count != 2)
  2494. !             croak("Big trouble\n") ;
  2495. !         printf ("%d + %d = %d\n", a, b, SvIV(ST(0))) ;
  2496. !         printf ("%d - %d = %d\n", a, b, SvIV(ST(1))) ;
  2497.   
  2498. !         PUTBACK ;
  2499. !         FREETMPS ;
  2500. !         LEAVE ;
  2501. !     }
  2502. ! Notes
  2503. ! =over 5
  2504. ! =item 1.
  2505. ! Notice that it was necessary to define the variable C<ax>.  This is
  2506. ! because the C<ST> macro expects it to exist.  If we were in an XSUB it
  2507. ! would not be necessary to define C<ax> as it is already defined for
  2508. ! you.
  2509. ! =item 2.
  2510. ! The code
  2511. !         SPAGAIN ;
  2512. !         sp -= count ;
  2513. !         ax = (sp - stack_base) + 1 ;
  2514. ! sets the stack up so that we can use the C<ST> macro.
  2515. ! =item 3.
  2516. ! Unlike the original coding of this example, the returned
  2517. ! values are not accessed in reverse order.  So C<ST(0)> refers to the
  2518. ! first value returned by the Perl subroutine and C<ST(count-1)> 
  2519. ! refers to the last.
  2520. ! =back
  2521.   
  2522.   =head1 SEE ALSO
  2523.   
  2524. ***************
  2525. *** 826,838 ****
  2526.   
  2527.   Paul Marquess <pmarquess@bfsec.bt.co.uk>
  2528.   
  2529. ! Special thanks to the following people who assisted in the creation of the 
  2530. ! document.
  2531.   
  2532. ! Jeff Okamoto, Tim Bunce.
  2533.   
  2534.   =head1 DATE
  2535.   
  2536. ! Version 0.4, 17th October 1994
  2537. --- 1826,1836 ----
  2538.   
  2539.   Paul Marquess <pmarquess@bfsec.bt.co.uk>
  2540.   
  2541. ! Special thanks to the following people who assisted in the creation of
  2542. ! the document.
  2543.   
  2544. ! Jeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem and Larry Wall. 
  2545.   
  2546.   =head1 DATE
  2547.   
  2548. ! Version 1.1, 17th May 1995
  2549. Index: pod/perlguts.pod
  2550. *** perl5.001e/pod/perlguts.pod    Tue Oct 18 12:39:36 1994
  2551. --- perl5.001f/pod/perlguts.pod    Wed May 31 10:28:07 1995
  2552. ***************
  2553. *** 16,29 ****
  2554.       AV  Array Value
  2555.       HV  Hash Value
  2556.   
  2557. ! Each typedef has specific routines that manipulate the various data type.
  2558.   
  2559.   =head2 What is an "IV"?
  2560.   
  2561.   Perl uses a special typedef IV which is large enough to hold either an
  2562.   integer or a pointer.
  2563.   
  2564. ! Perl also uses a special typedef I32 which will always be a 32-bit integer.
  2565.   
  2566.   =head2 Working with SV's
  2567.   
  2568. --- 16,30 ----
  2569.       AV  Array Value
  2570.       HV  Hash Value
  2571.   
  2572. ! Each typedef has specific routines that manipulate the various data types.
  2573.   
  2574.   =head2 What is an "IV"?
  2575.   
  2576.   Perl uses a special typedef IV which is large enough to hold either an
  2577.   integer or a pointer.
  2578.   
  2579. ! Perl also uses two special typedefs, I32 and I16, which will always be at
  2580. ! least 32-bits and 16-bits long, respectively.
  2581.   
  2582.   =head2 Working with SV's
  2583.   
  2584. ***************
  2585. *** 47,54 ****
  2586.       void  sv_setsv(SV*, SV*);
  2587.   
  2588.   Notice that you can choose to specify the length of the string to be
  2589. ! assigned by using C<sv_setpvn>, or allow Perl to calculate the length by
  2590. ! using C<sv_setpv>.  Be warned, though, that C<sv_setpv> determines the
  2591.   string's length by using C<strlen>, which depends on the string terminating
  2592.   with a NUL character.
  2593.   
  2594. --- 48,56 ----
  2595.       void  sv_setsv(SV*, SV*);
  2596.   
  2597.   Notice that you can choose to specify the length of the string to be
  2598. ! assigned by using C<sv_setpvn> or C<newSVpv>, or you may allow Perl to
  2599. ! calculate the length by using C<sv_setpv> or specifying 0 as the second
  2600. ! argument to C<newSVpv>.  Be warned, though, that Perl will determine the
  2601.   string's length by using C<strlen>, which depends on the string terminating
  2602.   with a NUL character.
  2603.   
  2604. ***************
  2605. *** 95,100 ****
  2606. --- 97,115 ----
  2607.   
  2608.   But note that these are valid only if C<SvPOK()> is true.
  2609.   
  2610. + If you want to append something to the end of string stored in an C<SV*>,
  2611. + you can use the following functions:
  2612. +     void  sv_catpv(SV*, char*);
  2613. +     void  sv_catpvn(SV*, char*, int);
  2614. +     void  sv_catsv(SV*, SV*);
  2615. + The first function calculates the length of the string to be appended by
  2616. + using C<strlen>.  In the second, you specify the length of the string
  2617. + yourself.  The third function extends the string stored in the first SV
  2618. + with the string stored in the second SV.  It also forces the second SV to
  2619. + be interpreted as a string.
  2620.   If you know the name of a scalar variable, you can get a pointer to its SV
  2621.   by using the following:
  2622.   
  2623. ***************
  2624. *** 102,108 ****
  2625.   
  2626.   This returns NULL if the variable does not exist.
  2627.   
  2628. ! If you want to know if this variable (or any other SV) is actually defined,
  2629.   you can call:
  2630.   
  2631.       SvOK(SV*)
  2632. --- 117,123 ----
  2633.   
  2634.   This returns NULL if the variable does not exist.
  2635.   
  2636. ! If you want to know if this variable (or any other SV) is actually C<defined>,
  2637.   you can call:
  2638.   
  2639.       SvOK(SV*)
  2640. ***************
  2641. *** 132,142 ****
  2642.   To free an SV that you've created, call C<SvREFCNT_dec(SV*)>.  Normally this
  2643.   call is not necessary.  See the section on B<MORTALITY>.
  2644.   
  2645. ! =head2 Private and Public Values
  2646.   
  2647.   Recall that the usual method of determining the type of scalar you have is
  2648. ! to use C<Sv[INP]OK> macros.  Since a scalar can be both a number and a string,
  2649. ! usually these macros will always return TRUE and calling the C<Sv[INP]V>
  2650.   macros will do the appropriate conversion of string to integer/double or
  2651.   integer/double to string.
  2652.   
  2653. --- 147,157 ----
  2654.   To free an SV that you've created, call C<SvREFCNT_dec(SV*)>.  Normally this
  2655.   call is not necessary.  See the section on B<MORTALITY>.
  2656.   
  2657. ! =head2 What's Really Stored in an SV?
  2658.   
  2659.   Recall that the usual method of determining the type of scalar you have is
  2660. ! to use C<Sv*OK> macros.  Since a scalar can be both a number and a string,
  2661. ! usually these macros will always return TRUE and calling the C<Sv*V>
  2662.   macros will do the appropriate conversion of string to integer/double or
  2663.   integer/double to string.
  2664.   
  2665. ***************
  2666. *** 148,156 ****
  2667.       SvPOKp(SV*)
  2668.   
  2669.   These will tell you if you truly have an integer, double, or string pointer
  2670. ! stored in your SV.
  2671.   
  2672. ! In general, though, it's best to just use the C<Sv[INP]V> macros.
  2673.   
  2674.   =head2 Working with AV's
  2675.   
  2676. --- 163,171 ----
  2677.       SvPOKp(SV*)
  2678.   
  2679.   These will tell you if you truly have an integer, double, or string pointer
  2680. ! stored in your SV.  The "p" stands for private.
  2681.   
  2682. ! In general, though, it's best to just use the C<Sv*V> macros.
  2683.   
  2684.   =head2 Working with AV's
  2685.   
  2686. ***************
  2687. *** 163,169 ****
  2688.   
  2689.       AV*  av_make(I32 num, SV **ptr);
  2690.   
  2691. ! The second argument points to an array containing C<num> C<SV*>'s.
  2692.   
  2693.   Once the AV has been created, the following operations are possible on AV's:
  2694.   
  2695. --- 178,185 ----
  2696.   
  2697.       AV*  av_make(I32 num, SV **ptr);
  2698.   
  2699. ! The second argument points to an array containing C<num> C<SV*>'s.  Once the
  2700. ! AV has been created, the SV's can be destroyed, if so desired.
  2701.   
  2702.   Once the AV has been created, the following operations are possible on AV's:
  2703.   
  2704. ***************
  2705. *** 179,192 ****
  2706.   
  2707.   Here are some other functions:
  2708.   
  2709. !     I32   av_len(AV*); /* Returns length of array */
  2710.   
  2711.       SV**  av_fetch(AV*, I32 key, I32 lval);
  2712. !             /* Fetches value at key offset, but it seems to
  2713. !            set the value to lval if lval is non-zero */
  2714.       SV**  av_store(AV*, I32 key, SV* val);
  2715.               /* Stores val at offset key */
  2716.   
  2717.       void  av_clear(AV*);
  2718.               /* Clear out all elements, but leave the array */
  2719.       void  av_undef(AV*);
  2720. --- 195,210 ----
  2721.   
  2722.   Here are some other functions:
  2723.   
  2724. !     I32   av_len(AV*); /* Returns highest index value in array */
  2725.   
  2726.       SV**  av_fetch(AV*, I32 key, I32 lval);
  2727. !             /* Fetches value at key offset, but it stores an undef value
  2728. !                at the offset if lval is non-zero */
  2729.       SV**  av_store(AV*, I32 key, SV* val);
  2730.               /* Stores val at offset key */
  2731.   
  2732. + Take note that these two functions return C<SV**>'s, not C<SV*>'s.
  2733.       void  av_clear(AV*);
  2734.               /* Clear out all elements, but leave the array */
  2735.       void  av_undef(AV*);
  2736. ***************
  2737. *** 224,230 ****
  2738.   These two functions check if a hash table entry exists, and deletes it.
  2739.   
  2740.       bool  hv_exists(HV*, char* key, U32 klen);
  2741. !     SV*   hv_delete(HV*, char* key, U32 klen);
  2742.   
  2743.   And more miscellaneous functions:
  2744.   
  2745. --- 242,248 ----
  2746.   These two functions check if a hash table entry exists, and deletes it.
  2747.   
  2748.       bool  hv_exists(HV*, char* key, U32 klen);
  2749. !     SV*   hv_delete(HV*, char* key, U32 klen, I32 flags);
  2750.   
  2751.   And more miscellaneous functions:
  2752.   
  2753. ***************
  2754. *** 233,238 ****
  2755. --- 251,262 ----
  2756.       void   hv_undef(HV*);
  2757.               /* Undefines the hash table */
  2758.   
  2759. + Perl keeps the actual data in linked list of structures with a typedef of HE.
  2760. + These contain the actual key and value pointers (plus extra administrative
  2761. + overhead).  The key is a string pointer; the value is an C<SV*>.  However,
  2762. + once you have an C<HE*>, to get the actual key and value, use the routines
  2763. + specified below.
  2764.       I32    hv_iterinit(HV*);
  2765.               /* Prepares starting point to traverse hash table */
  2766.       HE*    hv_iternext(HV*);
  2767. ***************
  2768. *** 244,249 ****
  2769. --- 268,278 ----
  2770.       SV*     hv_iterval(HV*, HE* entry);
  2771.               /* Return a SV pointer to the value of the HE
  2772.                  structure */
  2773. +     SV*     hv_iternextsv(HV*, char** key, I32* retlen);
  2774. +             /* This convenience routine combines hv_iternext,
  2775. +            hv_iterkey, and hv_iterval.  The key and retlen
  2776. +            arguments are return values for the key and its
  2777. +            length.  The value is returned in the SV* argument */
  2778.   
  2779.   If you know the name of a hash variable, you can get a pointer to its HV
  2780.   by using the following:
  2781. ***************
  2782. *** 260,289 ****
  2783.       while (i--)
  2784.       hash = hash * 33 + *s++;
  2785.   
  2786.   =head2 References
  2787.   
  2788. ! References are a special type of scalar that point to other scalar types
  2789. ! (including references).  To treat an AV or HV as a scalar, it is simply
  2790. ! a matter of casting an AV or HV to an SV.
  2791.   
  2792.   To create a reference, use the following command:
  2793.   
  2794. !     SV*  newRV((SV*) pointer);
  2795.   
  2796. ! Once you have a reference, you can use the following macro with a cast to
  2797. ! the appropriate typedef (SV, AV, HV):
  2798.   
  2799.       SvRV(SV*)
  2800.   
  2801.   then call the appropriate routines, casting the returned C<SV*> to either an
  2802. ! C<AV*> or C<HV*>.
  2803.   
  2804. ! To determine, after dereferencing a reference, if you still have a reference,
  2805. ! you can use the following macro:
  2806.   
  2807.       SvROK(SV*)
  2808.   
  2809. ! =head1 XSUB'S and the Argument Stack
  2810.   
  2811.   The XSUB mechanism is a simple way for Perl programs to access C subroutines.
  2812.   An XSUB routine will have a stack that contains the arguments from the Perl
  2813. --- 289,357 ----
  2814.       while (i--)
  2815.       hash = hash * 33 + *s++;
  2816.   
  2817. + =head1 Creating New Variables
  2818. + To create a new Perl variable, which can be accessed from your Perl script,
  2819. + use the following routines, depending on the variable type.
  2820. +     SV*  perl_get_sv("varname", TRUE);
  2821. +     AV*  perl_get_av("varname", TRUE);
  2822. +     HV*  perl_get_hv("varname", TRUE);
  2823. + Notice the use of TRUE as the second parameter.  The new variable can now
  2824. + be set, using the routines appropriate to the data type.
  2825. + There are additional bits that may be OR'ed with the TRUE argument to enable
  2826. + certain extra features.  Those bits are:
  2827. +     0x02  Marks the variable as multiply defined, thus preventing the
  2828. +       "Indentifier <varname> used only once: possible typo" warning.
  2829. +     0x04  Issues a "Had to create <varname> unexpectedly" warning if
  2830. +       the variable didn't actually exist.  This is useful if
  2831. +       you expected the variable to already exist and want to propagate
  2832. +       this warning back to the user.
  2833. +     
  2834. + If the C<varname> argument does not contain a package specifier, it is
  2835. + created in the current package.
  2836.   =head2 References
  2837.   
  2838. ! References are a special type of scalar that point to other data types
  2839. ! (including references).
  2840.   
  2841.   To create a reference, use the following command:
  2842.   
  2843. !     SV*  newRV((SV*) thing);
  2844.   
  2845. ! The C<thing> argument can be any of an C<SV*>, C<AV*>, or C<HV*>.  Once
  2846. ! you have a reference, you can use the following macro to dereference the
  2847. ! reference:
  2848.   
  2849.       SvRV(SV*)
  2850.   
  2851.   then call the appropriate routines, casting the returned C<SV*> to either an
  2852. ! C<AV*> or C<HV*>, if required.
  2853.   
  2854. ! To determine if an SV is a reference, you can use the following macro:
  2855.   
  2856.       SvROK(SV*)
  2857.   
  2858. ! To actually discover what the reference refers to, you must use the following
  2859. ! macro and then check the value returned.
  2860. !     SvTYPE(SvRV(SV*))
  2861. ! The most useful types that will be returned are:
  2862. !     SVt_IV    Scalar
  2863. !     SVt_NV    Scalar
  2864. !     SVt_PV    Scalar
  2865. !     SVt_PVAV  Array
  2866. !     SVt_PVHV  Hash
  2867. !     SVt_PVCV  Code
  2868. !     SVt_PVMG  Blessed Scalar
  2869. ! =head1 XSUB's and the Argument Stack
  2870.   
  2871.   The XSUB mechanism is a simple way for Perl programs to access C subroutines.
  2872.   An XSUB routine will have a stack that contains the arguments from the Perl
  2873. ***************
  2874. *** 331,342 ****
  2875. --- 399,414 ----
  2876.   
  2877.   These macros automatically adjust the stack for you, if needed.
  2878.   
  2879. + For more information, consult L<perlapi>.
  2880.   =head1 Mortality
  2881.   
  2882.   In Perl, values are normally "immortal" -- that is, they are not freed unless
  2883.   explicitly done so (via the Perl C<undef> call or other routines in Perl
  2884.   itself).
  2885.   
  2886. + Add cruft about reference counts.
  2887.   In the above example with C<tzname>, we needed to create two new SV's to push
  2888.   onto the argument stack, that being the two strings.  However, we don't want
  2889.   these new SV's to stick around forever because they will eventually be
  2890. ***************
  2891. *** 361,387 ****
  2892.   by passing their address (and casting them to C<SV*>) to the C<sv_2mortal> or
  2893.   C<sv_mortalcopy> routines.
  2894.   
  2895. ! =head1 Creating New Variables
  2896. ! To create a new Perl variable, which can be accessed from your Perl script,
  2897. ! use the following routines, depending on the variable type.
  2898. !     SV*  perl_get_sv("varname", TRUE);
  2899. !     AV*  perl_get_av("varname", TRUE);
  2900. !     HV*  perl_get_hv("varname", TRUE);
  2901. ! Notice the use of TRUE as the second parameter.  The new variable can now
  2902. ! be set, using the routines appropriate to the data type.
  2903.   
  2904.   =head1 Stashes and Objects
  2905.   
  2906.   A stash is a hash table (associative array) that contains all of the
  2907.   different objects that are contained within a package.  Each key of the
  2908. ! hash table is a symbol name (shared by all the different types of
  2909. ! objects that have the same name), and each value in the hash table is
  2910. ! called a GV (for Glob Value).  The GV in turn contains references to
  2911. ! the various objects of that name, including (but not limited to) the
  2912. ! following:
  2913.       
  2914.       Scalar Value
  2915.       Array Value
  2916. --- 433,459 ----
  2917.   by passing their address (and casting them to C<SV*>) to the C<sv_2mortal> or
  2918.   C<sv_mortalcopy> routines.
  2919.   
  2920. ! From Ilya:
  2921. ! Beware that the sv_2mortal() call is eventually equivalent to
  2922. ! svREFCNT_dec(). A value can happily be mortal in two different contexts,
  2923. ! and it will be svREFCNT_dec()ed twice, once on exit from these
  2924. ! contexts. It can also be mortal twice in the same context. This means
  2925. ! that you should be very careful to make a value mortal exactly as many
  2926. ! times as it is needed. The value that go to the Perl stack I<should>
  2927. ! be mortal.
  2928. ! You should be careful about creating mortal variables.  It is possible for
  2929. ! strange things to happen should you make the same value mortal within
  2930. ! multiple contexts.
  2931.   
  2932.   =head1 Stashes and Objects
  2933.   
  2934.   A stash is a hash table (associative array) that contains all of the
  2935.   different objects that are contained within a package.  Each key of the
  2936. ! stash is a symbol name (shared by all the different types of objects
  2937. ! that have the same name), and each value in the hash table is called a
  2938. ! GV (for Glob Value).  This GV in turn contains references to the various
  2939. ! objects of that name, including (but not limited to) the following:
  2940.       
  2941.       Scalar Value
  2942.       Array Value
  2943. ***************
  2944. *** 391,411 ****
  2945.       Format
  2946.       Subroutine
  2947.   
  2948. ! Perl stores various stashes in a GV structure (for global variable) but
  2949. ! represents them with an HV structure.
  2950.   
  2951. ! To get the HV pointer for a particular package, use the function:
  2952.   
  2953.       HV*  gv_stashpv(char* name, I32 create)
  2954.       HV*  gv_stashsv(SV*, I32 create)
  2955.   
  2956.   The first function takes a literal string, the second uses the string stored
  2957. ! in the SV.
  2958.   
  2959.   The name that C<gv_stash*v> wants is the name of the package whose symbol table
  2960.   you want.  The default package is called C<main>.  If you have multiply nested
  2961. ! packages, it is legal to pass their names to C<gv_stash*v>, separated by
  2962. ! C<::> as in the Perl language itself.
  2963.   
  2964.   Alternately, if you have an SV that is a blessed reference, you can find
  2965.   out the stash pointer by using:
  2966. --- 463,487 ----
  2967.       Format
  2968.       Subroutine
  2969.   
  2970. ! Perl stores various stashes in a separate GV structure (for global
  2971. ! variable) but represents them with an HV structure.  The keys in this
  2972. ! larger GV are the various package names; the values are the C<GV*>'s
  2973. ! which are stashes.  It may help to think of a stash purely as an HV,
  2974. ! and that the term "GV" means the global variable hash.
  2975.   
  2976. ! To get the stash pointer for a particular package, use the function:
  2977.   
  2978.       HV*  gv_stashpv(char* name, I32 create)
  2979.       HV*  gv_stashsv(SV*, I32 create)
  2980.   
  2981.   The first function takes a literal string, the second uses the string stored
  2982. ! in the SV.  Remember that a stash is just a hash table, so you get back an
  2983. ! C<HV*>.
  2984.   
  2985.   The name that C<gv_stash*v> wants is the name of the package whose symbol table
  2986.   you want.  The default package is called C<main>.  If you have multiply nested
  2987. ! packages, pass their names to C<gv_stash*v>, separated by C<::> as in the Perl
  2988. ! language itself.
  2989.   
  2990.   Alternately, if you have an SV that is a blessed reference, you can find
  2991.   out the stash pointer by using:
  2992. ***************
  2993. *** 425,433 ****
  2994.   argument is a stash.  The returned C<SV*> can now be used in the same way
  2995.   as any other SV.
  2996.   
  2997.   =head1 Magic
  2998.   
  2999. ! [This section under construction]
  3000.   
  3001.   =head1 Double-Typed SV's
  3002.   
  3003. --- 501,648 ----
  3004.   argument is a stash.  The returned C<SV*> can now be used in the same way
  3005.   as any other SV.
  3006.   
  3007. + For more information on references and blessings, consult L<perlref>.
  3008.   =head1 Magic
  3009.   
  3010. ! [This section still under construction.  Ignore everything here.  Post no
  3011. ! bills.  Everything not permitted is forbidden.]
  3012. ! # Version 6, 1995/1/27
  3013. ! Any SV may be magical, that is, it has special features that a normal
  3014. ! SV does not have.  These features are stored in the SV structure in a
  3015. ! linked list of C<struct magic>'s, typedef'ed to C<MAGIC>.
  3016. !     struct magic {
  3017. !         MAGIC*      mg_moremagic;
  3018. !         MGVTBL*     mg_virtual;
  3019. !         U16         mg_private;
  3020. !         char        mg_type;
  3021. !         U8          mg_flags;
  3022. !         SV*         mg_obj;
  3023. !         char*       mg_ptr;
  3024. !         I32         mg_len;
  3025. !     };
  3026. ! Note this is current as of patchlevel 0, and could change at any time.
  3027. ! =head2 Assigning Magic
  3028. ! Perl adds magic to an SV using the sv_magic function:
  3029. !     void sv_magic(SV* sv, SV* obj, int how, char* name, I32 namlen);
  3030. ! The C<sv> argument is a pointer to the SV that is to acquire a new magical
  3031. ! feature.
  3032. ! If C<sv> is not already magical, Perl uses the C<SvUPGRADE> macro to
  3033. ! set the C<SVt_PVMG> flag for the C<sv>.  Perl then continues by adding
  3034. ! it to the beginning of the linked list of magical features.  Any prior
  3035. ! entry of the same type of magic is deleted.  Note that this can be
  3036. ! overriden, and multiple instances of the same type of magic can be
  3037. ! associated with an SV.
  3038. ! The C<name> and C<namlem> arguments are used to associate a string with
  3039. ! the magic, typically the name of a variable. C<namlem> is stored in the
  3040. ! C<mg_len> field and if C<name> is non-null and C<namlem> >= 0 a malloc'd
  3041. ! copy of the name is stored in C<mg_ptr> field.
  3042. ! The sv_magic function uses C<how> to determine which, if any, predefined
  3043. ! "Magic Virtual Table" should be assigned to the C<mg_virtual> field.
  3044. ! See the "Magic Virtual Table" section below.
  3045. ! The C<obj> argument is stored in the C<mg_obj> field of the C<MAGIC>
  3046. ! structure.  If it is not the same as the C<sv> argument, the reference
  3047. ! count of the C<obj> object is incremented.  If it is the same, or if
  3048. ! the C<how> argument is "#", or if it is a null pointer, then C<obj> is
  3049. ! merely stored, without the reference count being incremented.
  3050. ! =head2 Magic Virtual Tables
  3051. ! The C<mg_virtual> field in the C<MAGIC> structure is a pointer to a
  3052. ! C<MGVTBL>, which is a structure of function pointers and stands for
  3053. ! "Magic Virtual Table" to handle the various operations that might be
  3054. ! applied to that variable.
  3055. ! The C<MGVTBL> has five pointers to the following routine types:
  3056. !     int  (*svt_get)(SV* sv, MAGIC* mg);
  3057. !     int  (*svt_set)(SV* sv, MAGIC* mg);
  3058. !     U32  (*svt_len)(SV* sv, MAGIC* mg);
  3059. !     int  (*svt_clear)(SV* sv, MAGIC* mg);
  3060. !     int  (*svt_free)(SV* sv, MAGIC* mg);
  3061. ! This MGVTBL structure is set at compile-time in C<perl.h> and there are
  3062. ! currently 19 types (or 21 with overloading turned on).  These different
  3063. ! structures contain pointers to various routines that perform additional
  3064. ! actions depending on which function is being called.
  3065. !     Function pointer    Action taken
  3066. !     ----------------    ------------
  3067. !     svt_get             Do something after the value of the SV is retrieved.
  3068. !     svt_set             Do something after the SV is assigned a value.
  3069. !     svt_len             Report on the SV's length.
  3070. !     svt_clear        Clear something the SV represents.
  3071. !     svt_free            Free any extra storage associated with the SV.
  3072. ! For instance, the MGVTBL structure called C<vtbl_sv> (which corresponds
  3073. ! to an C<mg_type> of '\0') contains:
  3074. !     { magic_get, magic_set, magic_len, 0, 0 }
  3075. ! Thus, when an SV is determined to be magical and of type '\0', if a get
  3076. ! operation is being performed, the routine C<magic_get> is called.  All
  3077. ! the various routines for the various magical types begin with C<magic_>.
  3078. ! The current kinds of Magic Virtual Tables are:
  3079. !     mg_type  MGVTBL              Type of magicalness
  3080. !     -------  ------              -------------------
  3081. !     \0       vtbl_sv             Regexp???
  3082. !     A        vtbl_amagic         Operator Overloading
  3083. !     a        vtbl_amagicelem     Operator Overloading
  3084. !     c        0                   Used in Operator Overloading
  3085. !     B        vtbl_bm             Boyer-Moore???
  3086. !     E        vtbl_env            %ENV hash
  3087. !     e        vtbl_envelem        %ENV hash element
  3088. !     g        vtbl_mglob          Regexp /g flag???
  3089. !     I        vtbl_isa            @ISA array
  3090. !     i        vtbl_isaelem        @ISA array element
  3091. !     L        0 (but sets RMAGICAL)     Perl Module/Debugger???
  3092. !     l        vtbl_dbline         Debugger?
  3093. !     P        vtbl_pack           Tied Array or Hash
  3094. !     p        vtbl_packelem       Tied Array or Hash element
  3095. !     q        vtbl_packelem       Tied Scalar or Handle
  3096. !     S        vtbl_sig            Signal Hash
  3097. !     s        vtbl_sigelem        Signal Hash element
  3098. !     t        vtbl_taint          Taintedness
  3099. !     U        vtbl_uvar             ???
  3100. !     v        vtbl_vec             Vector
  3101. !     x        vtbl_substr         Substring???
  3102. !     *        vtbl_glob           GV???
  3103. !     #        vtbl_arylen         Array Length
  3104. !     .        vtbl_pos             $. scalar variable
  3105. !     ~        Reserved for extensions, but multiple extensions may clash
  3106. ! When an upper-case and lower-case letter both exist in the table, then the
  3107. ! upper-case letter is used to represent some kind of composite type (a list
  3108. ! or a hash), and the lower-case letter is used to represent an element of
  3109. ! that composite type.
  3110. ! =head2 Finding Magic
  3111. !     MAGIC* mg_find(SV*, int type); /* Finds the magic pointer of that type */
  3112. ! This routine returns a pointer to the C<MAGIC> structure stored in the SV.
  3113. ! If the SV does not have that magical feature, C<NULL> is returned.  Also,
  3114. ! if the SV is not of type SVt_PVMG, Perl may core-dump.
  3115. !     int mg_copy(SV* sv, SV* nsv, char* key, STRLEN klen);
  3116. ! This routine checks to see what types of magic C<sv> has.  If the mg_type
  3117. ! field is an upper-case letter, then the mg_obj is copied to C<nsv>, but
  3118. ! the mg_type field is changed to be the lower-case letter.
  3119.   
  3120.   =head1 Double-Typed SV's
  3121.   
  3122. ***************
  3123. *** 437,443 ****
  3124.   
  3125.   Some scalar variables contain more than one type of scalar data.  For
  3126.   example, the variable C<$!> contains either the numeric value of C<errno>
  3127. ! or its string equivalent from C<sys_errlist[]>.
  3128.   
  3129.   To force multiple data values into an SV, you must do two things: use the
  3130.   C<sv_set*v> routines to add the additional scalar type, then set a flag
  3131. --- 652,658 ----
  3132.   
  3133.   Some scalar variables contain more than one type of scalar data.  For
  3134.   example, the variable C<$!> contains either the numeric value of C<errno>
  3135. ! or its string equivalent from either C<strerror> or C<sys_errlist[]>.
  3136.   
  3137.   To force multiple data values into an SV, you must do two things: use the
  3138.   C<sv_set*v> routines to add the additional scalar type, then set a flag
  3139. ***************
  3140. *** 479,494 ****
  3141.       I32  perl_call_method(char*, I32);
  3142.       I32  perl_call_argv(char*, I32, register char**);
  3143.   
  3144. ! The routine most often used should be C<perl_call_sv>.  The C<SV*> argument
  3145. ! contains either the name of the Perl subroutine to be called, or a reference
  3146. ! to the subroutine.  The second argument tells the appropriate routine what,
  3147. ! if any, variables are being returned by the Perl subroutine.
  3148.   
  3149.   All four routines return the number of arguments that the subroutine returned
  3150.   on the Perl stack.
  3151.   
  3152. ! When using these four routines, the programmer must manipulate the Perl stack.
  3153. ! These include the following macros and functions:
  3154.   
  3155.       dSP
  3156.       PUSHMARK()
  3157. --- 694,712 ----
  3158.       I32  perl_call_method(char*, I32);
  3159.       I32  perl_call_argv(char*, I32, register char**);
  3160.   
  3161. ! The routine most often used is C<perl_call_sv>.  The C<SV*> argument
  3162. ! contains either the name of the Perl subroutine to be called, or a
  3163. ! reference to the subroutine.  The second argument consists of flags
  3164. ! that control the context in which the subroutine is called, whether
  3165. ! or not the subroutine is being passed arguments, how errors should be
  3166. ! trapped, and how to treat return values.
  3167.   
  3168.   All four routines return the number of arguments that the subroutine returned
  3169.   on the Perl stack.
  3170.   
  3171. ! When using any of these routines (except C<perl_call_argv>), the programmer
  3172. ! must manipulate the Perl stack.  These include the following macros and
  3173. ! functions:
  3174.   
  3175.       dSP
  3176.       PUSHMARK()
  3177. ***************
  3178. *** 504,521 ****
  3179.   
  3180.   =head1 Memory Allocation
  3181.   
  3182. ! [This section under construction]
  3183.   
  3184.   =head1 AUTHOR
  3185.   
  3186.   Jeff Okamoto <okamoto@corp.hp.com>
  3187.   
  3188.   With lots of help and suggestions from Dean Roehrich, Malcolm Beattie,
  3189. ! Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, and Neil
  3190. ! Bowers.
  3191.   
  3192.   =head1 DATE
  3193.   
  3194. ! Version 12: 1994/10/16
  3195. --- 722,779 ----
  3196.   
  3197.   =head1 Memory Allocation
  3198.   
  3199. ! It is strongly suggested that you use the version of malloc that is distributed
  3200. ! with Perl.  It keeps pools of various sizes of unallocated memory in order to
  3201. ! more quickly satisfy allocation requests.
  3202. ! However, on some platforms, it may cause spurious malloc or free errors.
  3203. !     New(x, pointer, number, type);
  3204. !     Newc(x, pointer, number, type, cast);
  3205. !     Newz(x, pointer, number, type);
  3206. ! These three macros are used to initially allocate memory.  The first argument
  3207. ! C<x> was a "magic cookie" that was used to keep track of who called the macro,
  3208. ! to help when debugging memory problems.  However, the current code makes no
  3209. ! use of this feature (Larry has switched to using a run-time memory checker),
  3210. ! so this argument can be any number.
  3211. ! The second argument C<pointer> will point to the newly allocated memory.
  3212. ! The third and fourth arguments C<number> and C<type> specify how many of
  3213. ! the specified type of data structure should be allocated.  The argument
  3214. ! C<type> is passed to C<sizeof>.  The final argument to C<Newc>, C<cast>,
  3215. ! should be used if the C<pointer> argument is different from the C<type>
  3216. ! argument.
  3217. ! Unlike the C<New> and C<Newc> macros, the C<Newz> macro calls C<memzero>
  3218. ! to zero out all the newly allocated memory.
  3219. !     Renew(pointer, number, type);
  3220. !     Renewc(pointer, number, type, cast);
  3221. !     Safefree(pointer)
  3222. ! These three macros are used to change a memory buffer size or to free a
  3223. ! piece of memory no longer needed.  The arguments to C<Renew> and C<Renewc>
  3224. ! match those of C<New> and C<Newc> with the exception of not needing the
  3225. ! "magic cookie" argument.
  3226. !     Move(source, dest, number, type);
  3227. !     Copy(source, dest, number, type);
  3228. !     Zero(dest, number, type);
  3229. ! These three macros are used to move, copy, or zero out previously allocated
  3230. ! memory.  The C<source> and C<dest> arguments point to the source and
  3231. ! destination starting points.  Perl will move, copy, or zero out C<number>
  3232. ! instances of the size of the C<type> data structure (using the C<sizeof>
  3233. ! function).
  3234.   
  3235.   =head1 AUTHOR
  3236.   
  3237.   Jeff Okamoto <okamoto@corp.hp.com>
  3238.   
  3239.   With lots of help and suggestions from Dean Roehrich, Malcolm Beattie,
  3240. ! Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil
  3241. ! Bowers, Matthew Green, Tim Bunce, and Spider Boardman.
  3242.   
  3243.   =head1 DATE
  3244.   
  3245. ! Version 19: 1995/4/26
  3246.  
  3247.  
  3248. End of patch.
  3249.