home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl501m.zip / pod / perlcall.pod < prev    next >
Text File  |  1995-07-03  |  38KB  |  1,365 lines

  1. =head1 NAME
  2.  
  3. perlcall - Perl calling conventions from C
  4.  
  5. =head1 DESCRIPTION
  6.  
  7. The purpose of this document is to show you how to write I<callbacks>, 
  8. i.e. how to call Perl from C. The main
  9. focus is on how to interface back to Perl from a bit of C code that has itself
  10. been run by Perl, i.e. the 'main' program is a Perl script; you are using it
  11. to execute
  12. a section of code written in C; that bit of C code wants you to do something
  13. with a particular event, so you want a Perl sub to be executed whenever it
  14. happens.
  15.  
  16. Examples where this is necessary include
  17.  
  18. =over 5
  19.  
  20. =item * 
  21.  
  22. You have created an XSUB interface to an application's C API.
  23.  
  24. A fairly common feature in applications is to allow you to define a C
  25. function that will get called whenever something nasty occurs.
  26. What we would like is for a Perl sub to be called instead.
  27.  
  28. =item *
  29.  
  30. The classic example of where callbacks are used is in an event driven program 
  31. like for X-windows.
  32. In this case your register functions to be called whenever a specific events
  33. occur, e.g. a mouse button is pressed.
  34.  
  35. =back
  36.  
  37. Although the techniques described are applicable to embedding Perl
  38. in a C program, this is not the primary goal of this document. For details
  39. on embedding Perl in C refer to L<perlembed> (currently unwritten).
  40.  
  41. Before you launch yourself head first into the rest of this document, it would 
  42. be a good idea to have read the following two documents - L<perlapi> and L<perlguts>.
  43.  
  44. This stuff is easier to explain using examples. But first here are a few
  45. definitions anyway.
  46.  
  47. =head2 Definitions
  48.  
  49. Perl has a number of C functions which allow you to call Perl subs. They are
  50.  
  51.     I32 perl_call_sv(SV* sv, I32 flags) ;
  52.     I32 perl_call_pv(char *subname, I32 flags) ;
  53.     I32 perl_call_method(char *methname, I32 flags) ;
  54.     I32 perl_call_argv(char *subname, I32 flags, register char **argv) ;
  55.  
  56. The key function is I<perl_call_sv>. All the other functions make use of
  57. I<perl_call_sv> to do what they do.
  58.  
  59. I<perl_call_sv> takes two parameters, the first is an SV*. This allows you to 
  60. specify the Perl sub to be called either as a C string (which has first been 
  61. converted to an SV) or a reference to a 
  62. sub. Example 7, shows you how you can make use of I<perl_call_sv>.
  63. The second parameter, C<flags>, is a general purpose option command. 
  64. This parameter is common to all the I<perl_call_*> functions. 
  65. It is discussed in the next section.
  66.  
  67. The function, I<perl_call_pv>, is similar as I<perl_call_sv> except it 
  68. expects it's first parameter to be a C char* which identifies the Perl 
  69. sub you want to call, e.g. C<perl_call_pv("fred", 0)>.
  70.  
  71. The function I<perl_call_method> expects its first argument to contain a 
  72. blessed reference to a class. Using that reference it looks up and calls C<methname> 
  73. from that class. See example 9.
  74.  
  75. I<perl_call_argv> calls the Perl sub specified by the C<subname> parameter. 
  76. It also takes the usual C<flags> parameter. 
  77. The final parameter, C<argv>, consists of a 
  78. list of C strings to be sent to the Perl sub. See example 8.
  79.  
  80. All the functions return a number. This is a count of the number of items
  81. returned by the Perl sub on the stack.
  82.  
  83. As a general rule you should I<always> check the return value from these 
  84. functions.
  85. Even if you are only expecting a particular number of values to be returned 
  86. from the Perl sub, there is nothing to stop someone from doing something
  87. unexpected - don't say you haven't been warned.
  88.  
  89. =head2 Flag Values
  90.  
  91. The C<flags> parameter in all the I<perl_call_*> functions consists of any 
  92. combination of the symbols defined below, OR'ed together.
  93.  
  94. =over 5
  95.  
  96. =item  G_SCALAR    
  97.  
  98. Calls the Perl sub in a scalar context.
  99.  
  100. Whatever the Perl sub actually returns, we only want a scalar. If the perl sub 
  101. does return a scalar, the return value from the I<perl_call_*> function 
  102. will be 1 or 0. If 1, then the value actually returned by the Perl sub will 
  103. be contained on the top of the stack. 
  104. If 0, then you have used the G_DISCARD flag.
  105.  
  106. It is important to note that
  107. if the Perl sub returns a list, the I<perl_call_*> function will still
  108. only return 1 or 0. If 1, then the number of elements in the list 
  109. will be stored on top of the stack.
  110. The actual values which were contained in the list will not be accessible. 
  111.  
  112.  
  113. G_SCALAR is the default flag setting for all the functions.
  114.  
  115. =item G_ARRAY    
  116.  
  117. Calls the Perl sub in a list context.
  118.  
  119. The return code from the I<perl_call_*> functions will indicate how
  120. many elements of the stack are used to store the array. See example 4.
  121.  
  122. =item G_DISCARD    
  123.  
  124. If you are not interested in the values returned by the Perl sub then setting
  125. this flag will make Perl get rid of them automatically for you. This will take
  126. precedence to either G_SCALAR or G_ARRAY.
  127.  
  128. If you do not set this flag then you need to make sure that any temporaries 
  129. (i.e. parameters passed to the Perl sub and values returned from the sub) 
  130. are disposed of yourself.
  131. Example 3 gives details of how to explicitly dispose of these temporaries 
  132. and the section I<Using Perl to dispose of temporaries> discusses the 
  133. specific circumstances where you can ignore the problem and let Perl 
  134. deal with it for you.
  135.  
  136. =item G_NOARGS    
  137.  
  138. If you are not passing any parameters to the Perl sub, you can save a bit of 
  139. time by setting this flag. It has the effect of not creating the C<@_> array 
  140. for the Perl sub.
  141.  
  142. A point worth noting is that if this flag is specified the Perl sub you have
  143. called can still access an C<@_> array from a previous Perl sub. 
  144. This functionality can be illustrated with the perl code below
  145.  
  146.     sub fred
  147.       { print "@_\n"  }
  148.  
  149.     sub joe
  150.       { &fred }
  151.  
  152.     &joe(1,2,3) ;
  153.  
  154. This will print
  155.  
  156.     1 2 3
  157.  
  158. What has happened is that C<fred> accesses the C<@_> array which belongs to C<joe>.
  159.  
  160. =item G_EVAL    
  161.  
  162. It is possible for the Perl sub you are calling to terminate
  163. abnormally, e.g. by calling I<die> explicitly  or by not actually existing. If 
  164. you want to trap this type of event, specify the G_EVAL flag. 
  165. It will put an I<eval { }> around the sub call.
  166.  
  167. Whenever control returns from the I<perl_call_*> function you need to
  168. check the C<$@> variable as you would in a normal Perl script. 
  169.  
  170. The value returned from the I<perl_call_*> function is dependent on what other
  171. flags have been specified and whether an error has occurred. 
  172.  
  173. If the I<perl_call_*> function returns normally, then the value returned is 
  174. as specified in the previous sections.
  175.  
  176. If G_DISCARD is specified, the return value will always be 0 - this will 
  177. override both G_SCALAR and G_ARRAY.
  178.  
  179. If G_ARRAY is specified I<and> an error has occurred, the return value will 
  180. always be 0.
  181.  
  182. If G_SCALAR is specified I<and> an error has occurred, the return value will 
  183. be 1 and the value on the top of the stack will be I<undef>. This means that if
  184. you have already detected the error by checking C<$@> and you want the program
  185. to continue, you must remember to pop the I<undef> from the stack.
  186.  
  187. See example 6 for details of using G_EVAL.
  188.  
  189. Please Note: If you are intending to make use of the G_EVAL flag in your
  190. code use a version of Perl greater than 5.000.
  191. There is a known bug in version 5.000 of Perl which means that G_EVAL will
  192. not work as described above.
  193.  
  194.  
  195.  
  196. =back
  197.  
  198.  
  199. =head1 EXAMPLES
  200.  
  201. Enough of the definition talk, let's have a few examples.
  202.  
  203. Perl provides many macros to assist in accessing the Perl stack. 
  204. Wherever possible, these macros should always be used when interfacing to 
  205. Perl internals.
  206. Hopefully this should make the code less vulnerable to any changes made to
  207. Perl in the future.
  208.  
  209. Another point worth noting is that in the first series of examples I have 
  210. only made use of the I<perl_call_pv> function. 
  211. This has only been done to ease you into the 
  212. topic. Wherever possible, if the choice is between using I<perl_call_pv> 
  213. and I<perl_call_sv>, you should always try to use I<perl_call_sv>. 
  214. See example 7 for details.
  215.  
  216. =head2 Example1: No Parameters, Nothing returned
  217.  
  218. This first trivial example will call a Perl sub, I<PrintUID>, to print 
  219. out the UID of the process. 
  220.  
  221.     sub PrintUID
  222.     {
  223.         print "UID is $<\n" ;
  224.     }
  225.  
  226. and here is the C to call it
  227.  
  228.     void
  229.     call_PrintUID()
  230.     {
  231.     dSP ;
  232.  
  233.     PUSHMARK(sp) ;
  234.         perl_call_pv("PrintUID", G_DISCARD|G_NOARGS) ;
  235.     }
  236.  
  237. Simple, eh. 
  238.  
  239. A few points to note about this example. 
  240.  
  241. =over 5
  242.  
  243. =item 1. 
  244.  
  245. We aren't passing any parameters to I<PrintUID> so G_NOARGS
  246. can be specified.
  247.  
  248. =item 2.
  249.  
  250. Ignore C<dSP> and C<PUSHMARK(sp)> for now. They will be discussed in the next
  251. example.
  252.  
  253. =item 3. 
  254.  
  255. We aren't interested in anything returned from I<PrintUID>, so
  256. G_DISCARD is specified. Even if I<PrintUID> was changed to actually
  257. return some value(s), having specified G_DISCARD will mean that they
  258. will be wiped by the time control returns from I<perl_call_pv>.
  259.  
  260. =item 4. 
  261.  
  262. Because we specified G_DISCARD, it is not necessary to check 
  263. the value returned from I<perl_call_pv>. It will always be 0.
  264.  
  265. =item 5.
  266.  
  267. As I<perl_call_pv> is being used, the Perl sub is specified as a C string.
  268.  
  269. =back
  270.  
  271. =head2 Example 2: Passing Parameters
  272.  
  273. Now let's make a slightly more complex example. This time we want 
  274. to call a Perl sub, C<LeftString>,
  275. which will take 2 parameters - a string (C<$s>) and an integer (C<$n>). 
  276. The sub will simply print the first C<$n> characters of the string.
  277.  
  278. So the Perl sub would look like this
  279.  
  280.     sub LeftString
  281.     {
  282.         my($s, $n) = @_ ;
  283.         print substr($s, 0, $n), "\n" ;
  284.     }
  285.  
  286. The C function required to call I<LeftString> would look like this.
  287.  
  288.     static void
  289.     call_LeftString(a, b)
  290.     char * a ;
  291.     int b ;
  292.     {
  293.         dSP ;
  294.  
  295.         PUSHMARK(sp) ;
  296.         XPUSHs(sv_2mortal(newSVpv(a, 0)));
  297.         XPUSHs(sv_2mortal(newSViv(b)));
  298.         PUTBACK ;
  299.  
  300.         perl_call_pv("LeftString", G_DISCARD);
  301.     }
  302.  
  303.  
  304. Here are a few notes on the C function I<call_LeftString>.
  305.  
  306. =over 5
  307.  
  308. =item 1. 
  309.  
  310. The only flag specified this time is G_DISCARD. As we are passing 2 
  311. parameters to the Perl sub this time, we have not specified G_NOARGS.
  312.  
  313. =item 2. 
  314.  
  315. Parameters are passed to the Perl sub using the Perl stack.
  316. This is the purpose of the code beginning with the line C<dSP> and ending
  317. with the line C<PUTBACK>.
  318.  
  319.  
  320. =item 3.
  321.  
  322. If you are going to put something onto the Perl stack, you need to know
  323. where to put it. This is the purpose of the macro C<dSP> -
  324. it declares and initializes a I<local> copy of the Perl stack pointer.
  325.  
  326. All the other macros which will be used in this example require you to
  327. have used this macro. 
  328.  
  329. If you are calling a Perl sub directly from an XSUB function, it is 
  330. not necessary to explicitly use the C<dSP> macro - it will be declared for you.
  331.  
  332. =item 4.
  333.  
  334. Any parameters to be pushed onto the stack should be bracketed by the
  335. C<PUSHMARK> and C<PUTBACK> macros. 
  336. The purpose of these two macros, in this context, is to automatically count
  337. the number of parameters you are pushing. Then whenever Perl is creating
  338. the C<@_> array for the sub, it knows how big to make it.
  339.  
  340. The C<PUSHMARK> macro tells Perl to make a mental note of the current stack
  341. pointer. Even if you aren't passing any parameters (like in Example 1) you must 
  342. still call the C<PUSHMARK> macro before you can call any of 
  343. the I<perl_call_*> functions - Perl still needs to know that there are 
  344. no parameters.
  345.  
  346. The C<PUTBACK> macro sets the global copy of the stack pointer to be the
  347. same as our local copy. If we didn't do this I<perl_call_pv> wouldn't
  348. know where the two parameters we pushed were - remember that up to now
  349. all the stack pointer manipulation we have done is with our local copy,
  350. I<not> the global copy.
  351.  
  352. =item 5.
  353.  
  354. Next, we come to XPUSHs. This is where the parameters actually get
  355. pushed onto the stack. In this case we are pushing a string and an integer.
  356.  
  357. See the section I<XSUB's AND  THE ARGUMENT STACK> in L<perlguts> for
  358. details on how the XPUSH macros work.
  359.  
  360. =item 6.
  361.  
  362. Finally, I<LeftString> can now be called via the I<perl_call_pv> function.
  363.  
  364. =back
  365.  
  366. =head2 Example 3: Returning a Scalar
  367.  
  368. Now for an example of dealing with the values returned from a Perl sub.
  369.  
  370. Here is a Perl sub, I<Adder>,  which takes 2 integer parameters and simply 
  371. returns their sum.
  372.  
  373.     sub Adder
  374.     {
  375.         my($a, $b) = @_ ;
  376.         $a + $b ;
  377.     }
  378.  
  379. Since we are now concerned with the return value from I<Adder>, the C
  380. function required to call it is now a bit more complex.
  381.  
  382.     static void
  383.     call_Adder(a, b)
  384.     int a ;
  385.     int b ;
  386.     {
  387.         dSP ;
  388.         int count ;
  389.  
  390.         ENTER ;
  391.         SAVETMPS;
  392.  
  393.         PUSHMARK(sp) ;
  394.         XPUSHs(sv_2mortal(newSViv(a)));
  395.         XPUSHs(sv_2mortal(newSViv(b)));
  396.         PUTBACK ;
  397.  
  398.         count = perl_call_pv("Adder", G_SCALAR);
  399.  
  400.         SPAGAIN ;
  401.  
  402.     if (count != 1)
  403.         croak("Big trouble\n") ;
  404.  
  405.     printf ("The sum of %d and %d is %d\n", a, b, POPi) ;
  406.  
  407.         PUTBACK ;
  408.         FREETMPS ;
  409.         LEAVE ;
  410.     }
  411.  
  412.  
  413. Points to note this time are
  414.  
  415. =over 5
  416.  
  417. =item 1. 
  418.  
  419. The only flag specified this time was G_SCALAR. That means the C<@_> array
  420. will be created and that the value returned by I<Adder> will still
  421. exist after the call to I<perl_call_pv>.
  422.  
  423.  
  424.  
  425. =item 2.
  426.  
  427. Because we are interested in what is returned from I<Adder> we cannot specify
  428. G_DISCARD. This means that we will have to tidy up the Perl stack and dispose
  429. of any temporary values ourselves. This is the purpose of 
  430.  
  431.     ENTER ;
  432.     SAVETMPS ;
  433.  
  434. at the start of the function, and
  435.  
  436.     FREETMPS ;
  437.     LEAVE ;
  438.  
  439. at the end. The C<ENTER>/C<SAVETMPS> pair creates a boundary for any 
  440. temporaries we create. 
  441. This means that the temporaries we get rid of will be limited to those which
  442. were created after these calls.
  443.  
  444. The C<FREETMPS>/C<LEAVE> pair will get rid of any values returned by the Perl 
  445. sub, plus it will also dump the mortal SV's we have created. 
  446. Having C<ENTER>/C<SAVETMPS> at the beginning
  447. of the code makes sure that no other mortals are destroyed.
  448.  
  449. =item 3.
  450.  
  451. The purpose of the macro C<SPAGAIN> is to refresh the local copy of the
  452. stack pointer. This is necessary because it is possible that the memory
  453. allocated to the Perl stack has been re-allocated whilst in the I<perl_call_pv>
  454. call.
  455.  
  456. If you are making use of the Perl stack pointer in your code you must always
  457. refresh the your local copy using SPAGAIN whenever you make use of
  458. of the I<perl_call_*> functions or any other Perl internal function.
  459.  
  460. =item 4. 
  461.  
  462. Although only a single value was expected to be returned from I<Adder>, it is
  463. still good practice to check the return code from I<perl_call_pv> anyway.
  464.  
  465. Expecting a single value is not quite the same as knowing that there will
  466. be one. If someone modified I<Adder> to return a list and we didn't check
  467. for that possibility and take appropriate action the Perl stack would end 
  468. up in an inconsistent state. That is something you I<really> don't want
  469. to ever happen.
  470.  
  471. =item 5.
  472.  
  473. The C<POPi> macro is used here to pop the return value from the stack. In this
  474. case we wanted an integer, so C<POPi> was used.
  475.  
  476.  
  477. Here is the complete list of POP macros available, along with the types they 
  478. return.
  479.  
  480.     POPs    SV
  481.     POPp    pointer
  482.     POPn    double
  483.     POPi    integer
  484.     POPl    long
  485.  
  486. =item 6.
  487.  
  488. The final C<PUTBACK> is used to leave the Perl stack in a consistent state 
  489. before exiting the function. This is
  490. necessary because when we popped the return value from the stack with C<POPi> it
  491. only updated our local copy of the stack pointer. Remember, C<PUTBACK> sets the
  492. global stack pointer to be the same as our local copy.
  493.  
  494. =back
  495.  
  496.  
  497. =head2 Example 4: Returning a list of values
  498.  
  499. Now, let's extend the previous example to return both the sum of the parameters 
  500. and the difference.
  501.  
  502. Here is the Perl sub
  503.  
  504.     sub AddSubtract
  505.     {
  506.        my($a, $b) = @_ ;
  507.        ($a+$b, $a-$b) ;
  508.     }
  509.  
  510. and this is the C function
  511.  
  512.     static void
  513.     call_AddSubtract(a, b)
  514.     int a ;
  515.     int b ;
  516.     {
  517.         dSP ;
  518.         int count ;
  519.  
  520.         ENTER ;
  521.         SAVETMPS;
  522.  
  523.         PUSHMARK(sp) ;
  524.         XPUSHs(sv_2mortal(newSViv(a)));
  525.         XPUSHs(sv_2mortal(newSViv(b)));
  526.         PUTBACK ;
  527.  
  528.         count = perl_call_pv("AddSubtract", G_ARRAY);
  529.  
  530.         SPAGAIN ;
  531.  
  532.         if (count != 2)
  533.             croak("Big trouble\n") ;
  534.  
  535.         printf ("%d - %d = %d\n", a, b, POPi) ;
  536.         printf ("%d + %d = %d\n", a, b, POPi) ;
  537.  
  538.         PUTBACK ;
  539.         FREETMPS ;
  540.         LEAVE ;
  541.     }
  542.  
  543. If I<call_AddSubtract> is called like this
  544.  
  545.     call_AddSubtract(7, 4) ;
  546.  
  547. then here is the output
  548.  
  549.     7 - 4 = 3
  550.     7 + 4 = 11
  551.  
  552. Notes
  553.  
  554. =over 5
  555.  
  556. =item 1.
  557.  
  558. We wanted array context, so we used G_ARRAY.
  559.  
  560. =item 2.
  561.  
  562. Not surprisingly C<POPi> is used twice this time because we were retrieving 2
  563. values from the stack. The main point to note is that they came off the stack in
  564. reverse order.
  565.  
  566. =back
  567.  
  568. =head2 Example 5: Returning Data from Perl via the parameter list
  569.  
  570. It is also possible to return values directly via the parameter list -
  571. whether it is actually desirable to do it is another matter entirely.
  572.  
  573. The Perl sub, I<Inc>, below takes 2 parameters and increments each directly.
  574.  
  575.     sub Inc
  576.     {
  577.         ++ $_[0] ;
  578.         ++ $_[1] ;
  579.     }
  580.  
  581. and here is a C function to call it.
  582.  
  583.     static void
  584.     call_Inc(a, b)
  585.     int a ;
  586.     int b ;
  587.     {
  588.         dSP ;
  589.         int count ;
  590.         SV * sva ;
  591.         SV * svb ;
  592.  
  593.         ENTER ;
  594.         SAVETMPS;
  595.  
  596.         sva = sv_2mortal(newSViv(a)) ;
  597.         svb = sv_2mortal(newSViv(b)) ;
  598.  
  599.         PUSHMARK(sp) ;
  600.         XPUSHs(sva);
  601.         XPUSHs(svb);
  602.         PUTBACK ;
  603.  
  604.         count = perl_call_pv("Inc", G_DISCARD);
  605.  
  606.         if (count != 0)
  607.             croak ("call_Inc: expected 0 values from 'Inc', got %d\n",
  608.                    count) ;
  609.  
  610.         printf ("%d + 1 = %d\n", a, SvIV(sva)) ;
  611.         printf ("%d + 1 = %d\n", b, SvIV(svb)) ;
  612.  
  613.         FREETMPS ;
  614.         LEAVE ;
  615.     }
  616.  
  617. To be able to access the two parameters that were pushed onto the stack
  618. after they return from I<perl_call_pv> it is necessary to make a note
  619. of their addresses - thus the two variables C<sva> and C<svb>.
  620.  
  621. The reason this is necessary is that the area of the Perl stack which
  622. held them will very likely have been overwritten by something else by
  623. the time control returns from I<perl_call_pv>.
  624.  
  625.  
  626.  
  627.  
  628. =head2 Using G_EVAL
  629.  
  630. Now an example using G_EVAL. Below is a Perl subroutine which computes
  631. the difference of its 2 parameters. If this would result in a negative
  632. result, the subroutine calls I<die>.
  633.  
  634.     sub Subtract
  635.     {
  636.         my ($a, $b) = @_ ;
  637.  
  638.         die "death can be fatal\n" if $a < $b ;
  639.  
  640.         $a - $b ;
  641.     }
  642.  
  643. and some C to call it
  644.  
  645.     static void
  646.     call_Subtract(a, b)
  647.     int a ;
  648.     int b ;
  649.     {
  650.         dSP ;
  651.         int count ;
  652.         SV * sv ;
  653.  
  654.         ENTER ;
  655.         SAVETMPS;
  656.  
  657.         PUSHMARK(sp) ;
  658.         XPUSHs(sv_2mortal(newSViv(a)));
  659.         XPUSHs(sv_2mortal(newSViv(b)));
  660.         PUTBACK ;
  661.  
  662.         count = perl_call_pv("Subtract", G_EVAL|G_SCALAR);
  663.  
  664.         SPAGAIN ;
  665.     
  666.     /* Check the eval first */
  667.         sv = GvSV(gv_fetchpv("@", TRUE, SVt_PV));
  668.         if (SvTRUE(sv))
  669.     {
  670.             printf ("Uh oh - %s\n", SvPV(sv, na)) ;
  671.         POPs ;
  672.     }
  673.     else
  674.     {
  675.             if (count != 1)
  676.                 croak ("call_Subtract : expected 1 value from 'Subtract', got %d\n", count) ;
  677.     
  678.         printf ("%d - %d = %d\n", a, b, POPi) ;
  679.     }
  680.  
  681.         PUTBACK ;
  682.         FREETMPS ;
  683.         LEAVE ;
  684.  
  685.     }
  686.  
  687. If I<call_Subtract> is called thus
  688.  
  689.     call_Subtract(4, 5)
  690.  
  691. the following will be printed
  692.  
  693.     Uh oh - death can be fatal
  694.  
  695. Notes
  696.  
  697. =over 5
  698.  
  699. =item 1.
  700.  
  701. We want to be able to catch the I<die> so we have used the G_EVAL flag.
  702. Not specifying this flag would mean that the program would terminate
  703. immediately at the I<die>.
  704.  
  705. =item 2.
  706.  
  707. The code 
  708.  
  709.         sv = GvSV(gv_fetchpv("@", TRUE, SVt_PV));
  710.         if (SvTRUE(sv))
  711.             printf ("Uh oh - %s\n", SvPVx(sv, na)) ;
  712.  
  713. is the equivalent of this bit of Perl
  714.  
  715.     print "Uh oh - $@\n" if $@ ;
  716.  
  717.  
  718. =item 3.
  719.  
  720. Note that the stack is popped using C<POPs> in the block where C<SvTRUE(sv)> 
  721. is true.
  722. This is necessary because whenever a I<perl_call_*> function invoked with
  723. G_EVAL|G_SCALAR returns an error, the top of the stack holds the value
  724. I<undef>. As we want the program to continue after detecting this error, it
  725. is essential that the stack is tidied up by removing the I<undef>.
  726.  
  727. =back
  728.  
  729.  
  730. =head2 Example 7: Using perl_call_sv
  731.  
  732. In all the previous examples I have 'hard-wired' the name of the Perl sub to
  733. be called from C. 
  734. Most of the time though, it is more convenient to be able to specify the name
  735. of the Perl sub from within the Perl script.
  736.  
  737. Consider the Perl code below
  738.  
  739.     sub fred
  740.     {
  741.         print "Hello there\n" ;
  742.     }
  743.  
  744.     CallSub("fred") ;
  745.  
  746.  
  747. here is a snippet of XSUB which defines I<CallSub>.
  748.  
  749.     void
  750.     CallSub(name)
  751.         char *    name
  752.         CODE:
  753.         PUSHMARK(sp) ;
  754.         perl_call_pv(name, G_DISCARD|G_NOARGS) ;
  755.  
  756. That is fine as far as it goes. The thing is, it only allows the Perl sub to be
  757. specified as a string. 
  758. For perl 4 this was adequate, but Perl 5 allows references to 
  759. subs and anonymous subs. This is where I<perl_call_sv> is useful.
  760.  
  761. The code below for I<CallSub> is identical to the previous time except that the
  762. C<name> parameter is now defined as an SV* and we use I<perl_call_sv> instead of
  763. I<perl_call_pv>.
  764.  
  765.     void
  766.     CallSub(name)
  767.         SV*    name
  768.         CODE:
  769.         PUSHMARK(sp) ;
  770.         perl_call_sv(name, G_DISCARD|G_NOARGS) ;
  771.  
  772. As we are using an SV to call I<fred> the following can all be used
  773.  
  774.     CallSub("fred") ;
  775.     Callsub(\&fred) ;
  776.     $ref = \&fred ;
  777.     CallSub($ref) ;
  778.     CallSub( sub { print "Hello there\n" } ) ;
  779.  
  780. As you can see, I<perl_call_sv> gives you much greater flexibility in how you 
  781. can specify the Perl sub.
  782.  
  783. =head2 Example 8: Using perl_call_argv
  784.  
  785. Here is a Perl sub which prints whatever parameters are passed to it.
  786.  
  787.     sub PrintList
  788.     {
  789.         my(@list) = @_ ;
  790.  
  791.         foreach (@list) { print "$_\n" }
  792.     }
  793.  
  794. and here is an example of I<perl_call_argv> which will call I<PrintList>.
  795.  
  796.     call_PrintList
  797.     {
  798.         dSP ;
  799.         char * words[] = {"alpha", "beta", "gamma", "delta", NULL } ;
  800.  
  801.         perl_call_argv("PrintList", words, G_DISCARD) ;
  802.     }
  803.  
  804. Note that it is not necessary to call C<PUSHMARK> in this instance. This is
  805. because I<perl_call_argv> will do it for you.
  806.  
  807. =head2 Example 9: Using perl_call_method
  808.  
  809. Consider the following Perl code
  810.  
  811.     {
  812.         package Mine ;
  813.  
  814.         sub new
  815.         { 
  816.             my($type) = shift ;
  817.             bless [@_] 
  818.         }
  819.     
  820.         sub Display 
  821.         { 
  822.             my ($self, $index) = @_ ;
  823.             print "$index: $$self[$index]\n" ;
  824.         }
  825.     }
  826.  
  827.  
  828. It just implements a very simple class to manage an array. The only method
  829. defined is C<Display> which prints out a single element of the array.
  830. Here is an all Perl example of using it.
  831.  
  832.     $a = new Mine ('red', 'green', 'blue') ;
  833.     $a->Display(1) ;
  834.  
  835. will print
  836.  
  837.     1: green
  838.  
  839. Calling a Perl method from C is fairly straightforward - a reference to 
  840. the object, the name of the method and any other parameters specific to
  841. the method are all that is required.
  842.  
  843. Here is a simple XSUB which illustrates the mechanics of calling the
  844. C<Display> method from C.
  845.  
  846.     void
  847.     call_Display(ref, method, index)
  848.             SV *    ref
  849.             char *  method
  850.         int        index
  851.             CODE:
  852.             PUSHMARK(sp);
  853.             XPUSHs(ref);
  854.         XPUSHs(sv_2mortal(newSViv(index))) ;
  855.             PUTBACK;
  856.     
  857.             perl_call_method(method, G_DISCARD) ;
  858.  
  859. C<call_Display> expects it's first parameter to be a reference to 
  860. an object, 
  861. the second to be the name of the method, and the third is the index.
  862. So the method C<Display> method can be invoked like this
  863.  
  864.  
  865.     $a = new Mine ('red', 'green', 'blue') ;
  866.     call_Method($a, 'Display', 2) ;
  867.  
  868. The only thing to note is that the reference to the 
  869. object (C<ref>) and the C<index> parameter are is pushed onto 
  870. the stack before calling I<perl_call_method>. The method name
  871. C<method> does not get pushed onto the stack, it is used as the 
  872. first parameter to I<perl_call_method>.
  873.  
  874.  
  875.  
  876. =head2 Using Perl to dispose of temporaries
  877.  
  878. In the examples given to date, any temporaries created in the callback (
  879. i.e parameters passed on the stack to the I<perl_call_*> function or
  880. values returned via the stack) have been freed by
  881.  
  882. =over 5
  883.  
  884. =item *
  885.  
  886. specifying the G_DISCARD flag with I<perl_call_*>.
  887.  
  888. =item *
  889.  
  890. explicitly disposed of using the C<ENTER>/C<SAVETMPS> - C<FREETMPS>/C<LEAVE> 
  891. pairing.
  892.  
  893. =back
  894.  
  895. There is another method which can be
  896. used, namely letting Perl do it for you automatically whenever it 
  897. regains control after the callback has terminated. 
  898. This is done by simply not using the
  899.  
  900.     ENTER ;
  901.     SAVETMPS ;
  902.     ...
  903.     FREETMPS ;
  904.     LEAVE ;
  905.  
  906. sequence in the callback (and not, of course, specifying the G_DISCARD flag).
  907.  
  908. If you are going to use this method you have to be aware of a possible 
  909. memory leak which can arise under very specific circumstances.
  910. To explain these circumstances you need to know a bit about the flow of
  911. control between Perl and the callback routine.
  912.  
  913. The examples given at the start of the document (an error handler and
  914. an event driven program) are typical of 
  915. the two main sorts 
  916. of flow control that you are likely to encounter with callbacks. 
  917. There is a very important distinction between them, so pay attention.
  918.  
  919. In the first example, an error handler, the flow of control could be as
  920. follows. You have created an interface to an external library and control 
  921. has reached the library thus
  922.  
  923.     perl --> XSUB --> external library
  924.  
  925. Whilst control is in the library, an error condition occurs. You have 
  926. previously set up a Perl callback to handle this situation, so the flow
  927. of control will be
  928.  
  929.  
  930.                       external library --> XSUB --> perl_call --+
  931.                                                                 |
  932.     perl <-- XSUB <-- external library <-- XSUB <---------------+
  933.  
  934.  
  935. After processing of the error using I<perl_call_*> is completed, 
  936. control reverts back to Perl more or less immediately. 
  937. The important thing to note is that it is only now that control is back 
  938. with Perl that any temporaries you have left hanging around will be freed. 
  939.                 
  940. In the second example, an event driven program, the flow of control will 
  941. be more like this
  942.  
  943.     event handler --> XSUB --> perl_call --+
  944.                                   |
  945.                   +--------<---------------+
  946.               |
  947.     event handler +-> XSUB --> perl_call --+
  948.                                   |
  949.                   +----------<-------------+
  950.               |
  951.     event handler +-> XSUB --> perl_call --+
  952.                                   |
  953.                   +----------<-------------+
  954.               |
  955.     event handler +-> XSUB --> perl_call --+
  956.             
  957. In this case the flow of control can consist only of the repeated sequence
  958.  
  959.     event handler -> XSUB -> perl_call 
  960.  
  961. for the practically the complete duration of the program.
  962. This means that control may never drop back to Perl proper.
  963.  
  964. So what is the big problem? Well, if you are expecting Perl to tidy up 
  965. those temporaries for you, you might be in for a long wait. 
  966. For Perl to actually dispose
  967. of your temporaries, control must drop back to it at some stage. In the
  968. event driven scenario that may never happen. This means that as time goes on,
  969. your program will create more and more temporaries, none of which will ever
  970. be freed. As each of these temporaries consumes some memory you program will
  971. eventually consume all the available memory in your system - kapow!
  972.  
  973. So here is the bottom line - if you are sure that control will revert 
  974. back to Perl fairly quickly after the end of your callback, then it 
  975. isn't absolutely necessary to explicitly dispose of any temporaries you 
  976. may have created. Mind you, if you are at all uncertain about what to do,
  977. it doesn't do any harm to tidy up anyway.
  978.  
  979.  
  980. =head2 Strategies for storing Callback Context Information
  981.  
  982.  
  983. Potentially one of the trickiest problems to overcome when designing a 
  984. callback interface can be figuring 
  985. out how to store the mapping between the C callback function and the 
  986. Perl equivalent.
  987.  
  988. To help understand why this can be a real problem first consider how a
  989. callback is set up in an all C environment. 
  990. Typically a C API will provide a function to register a callback. 
  991. This will expect a pointer to a function as one of it's parameters.
  992. Below is a call to a hypothetical function C<register_fatal> which 
  993. registers the C function to get called when a fatal error occurs.
  994.  
  995.     register_fatal(cb1) ;
  996.  
  997. The single parameter C<cb1> is a pointer to a function, so you must have
  998. defined C<cb1> in your code, say something like this
  999.  
  1000.     void
  1001.     cb1()
  1002.     {
  1003.         printf ("Fatal Error\n") ;
  1004.         exit(1) ;
  1005.     }
  1006.     
  1007.  
  1008. Now change that to call a Perl sub instead
  1009.  
  1010.     static SV * callback ;
  1011.  
  1012.     void
  1013.     register_fatal(fn)
  1014.         CODE:
  1015.         SV *    fn
  1016.         {
  1017.         /* Remember the Perl sub */
  1018.         callback = fn ;
  1019.     
  1020.         /* register the callback with the external library */
  1021.             register_fatal(cb1) ;
  1022.         }
  1023.     
  1024.     void
  1025.     cb1()
  1026.     {
  1027.         ...
  1028.         /* Call the Perl sub to process the callback */
  1029.         perl_call_sv(callback) ;
  1030.         ...
  1031.     }
  1032.     
  1033.  
  1034. where the Perl equivalent of C<register_fatal> and the callback it 
  1035. registers ,C<pcb1>, might look like this
  1036.  
  1037.     # Register the sub pcb1
  1038.     register_fatal(\&pcb1) ;
  1039.  
  1040.     sub pcb1
  1041.     {
  1042.         die "I'm dying...\n" ;
  1043.     }
  1044.  
  1045. The mapping between the C callback and the Perl equivalent is stored in the
  1046. global variable C<callback>.
  1047.  
  1048. This will be adequate if you only ever need to have 1 callback 
  1049. registered at any time. An example could be an error handler like
  1050. the code sketched out above. Remember though, repeated calls to 
  1051. C<register_fatal> will
  1052. replace the previously registered callback function with the new one.
  1053.  
  1054. Say though you want to interface to a library which allows asynchronous 
  1055. file i/o.
  1056. In this case you may be able to register a callback whenever a read operation
  1057. has completed. To be of any use we want to be able to call separate Perl
  1058. subs for each file that is opened. As it stands, the error handler example
  1059. above would not be adequate as it only allows a single callback
  1060. to be defined at any time. What we require is a means of storing the mapping 
  1061. between the opened file and the Perl sub we want to be called for that file.
  1062.  
  1063. Say the i/o library has a function C<asynch_read> which associates a
  1064. C function C<callback> with a file handle C<fh> - this assumes that it has
  1065. also provided some routine to open file file and so obtain the file handle.
  1066.  
  1067.     asynch_read(fh, callback)
  1068.  
  1069.  
  1070. This may expect the C callback function of this form
  1071.  
  1072.     void
  1073.     callback(fh, buffer)
  1074.     int    fh ;
  1075.     char *    buffer ;
  1076.     {
  1077.         ...
  1078.     }
  1079.  
  1080.  
  1081. To provide a Perl interface to this library we need to be able to map
  1082. between the C<fh> parameter and the Perl sub we want called. A hash is a 
  1083. convenient mechanism for storing this mapping. The code below shows a
  1084. possible implementation
  1085.  
  1086.     HV * Mapping = (HV*)NULL ;
  1087.  
  1088.     void
  1089.     asynch_read(fh, callback)
  1090.     int    fh
  1091.     SV *    callback
  1092.     CODE:
  1093.     {
  1094.       /* If the hash doesn't already exist, create it */
  1095.       if (Mapping == (HV*)NULL)
  1096.           Mapping = newHV() ;
  1097.     
  1098.       /* Save the fh -> callback mapping */
  1099.       hv_store(Mapping, &fh, sizeof(fh), callback, 0) ;
  1100.     
  1101.       /* Register with the C Library */
  1102.       asynch_read(fh, asynch_read_if) ;
  1103.     }
  1104.  
  1105. where C<asynch_read_if> could look like this
  1106.  
  1107.     static void
  1108.     asynch_read_if(fh, buffer)
  1109.     int    fh ;
  1110.     char *    buffer ;
  1111.     {
  1112.         dSP ;
  1113.         SV ** sv ;
  1114.     
  1115.         /* Get the callback associated with fh */
  1116.         sv =  hv_fetch(Mapping, &fh , sizeof(fh), FALSE) ;
  1117.         if (sv == (SV**)NULL)
  1118.             croak("Internal error...\n") ;
  1119.     
  1120.         PUSHMARK(sp) ;
  1121.         XPUSHs(sv_2mortal(newSViv(fh))) ;
  1122.         XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
  1123.         PUTBACK ;
  1124.     
  1125.         /* Call the Perl sub */
  1126.         perl_call_sv(*sv, G_DISCARD) ;
  1127.     }
  1128.  
  1129. So the Perl interface would look like this
  1130.  
  1131.     # Register the Perl callback
  1132.     asynch_read(fh, \&callback1) ;
  1133.     
  1134.     sub callback1
  1135.     {
  1136.         my($handle, $buffer) = @_ ;
  1137.         ...
  1138.     }
  1139.  
  1140.  
  1141. The mapping between the C callback and Perl is stored in the global hash 
  1142. C<Mapping> this time. Using a hash has the advantage that it allows an 
  1143. unlimited number of callbacks to be registered.
  1144.  
  1145. What if the interface provided by the C callback doesn't contain a parameter
  1146. which allows the file handle to Perl sub mapping? Say in the asynchronous i/o
  1147. package, the callback function only gets passed the C<buffer> parameter 
  1148. like this 
  1149.  
  1150.     void
  1151.     callback(buffer)
  1152.     char *    buffer ;
  1153.     {
  1154.         ...
  1155.     }
  1156.  
  1157. Without the file handle there is no straightforward way to map from the C 
  1158. callback to the Perl sub.
  1159.  
  1160. In this case a possible way around this problem is to pre-define a series 
  1161. of C functions to act as the interface to Perl, thus
  1162.  
  1163.  
  1164.     #define MAX_CB    3
  1165.     typedef    void (*FnMap)() ;
  1166.     static void fn1() ;
  1167.     static void fn2() ;
  1168.     static void fn3() ;
  1169.     FnMap    Functions[MAX_CB] = { fn1, fn2, fn3 } ;
  1170.     SV *    PerlSubs [MAX_CB] = { NULL, NULL, NULL } ;
  1171.     
  1172.     static void
  1173.     Pcb(index, buffer)
  1174.     int index ;
  1175.     char * buffer ;
  1176.     {
  1177.         dSP ;
  1178.         
  1179.         PUSHMARK(sp) ;
  1180.         XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
  1181.         PUTBACK ;
  1182.     
  1183.         /* Call the Perl sub */
  1184.         perl_call_sv(PerlSubs[index], G_DISCARD) ;
  1185.     }
  1186.     
  1187.     static void
  1188.     fn1(buffer)
  1189.     char * buffer ;
  1190.     {
  1191.         Pcb(0, buffer) ;
  1192.     }
  1193.     
  1194.     static void
  1195.     fn2(buffer)
  1196.     char * buffer ;
  1197.     {
  1198.         Pcb(1, buffer) ;
  1199.     }
  1200.     
  1201.     static void
  1202.     fn3(buffer)
  1203.     char * buffer ;
  1204.     {
  1205.         Pcb(2, buffer) ;
  1206.     }
  1207.  
  1208.     void
  1209.     asynch_read(fh, callback)
  1210.     int    fh
  1211.     SV *    callback
  1212.     CODE:
  1213.     {
  1214.       int index ;
  1215.       /* Find an empty entry */
  1216.       for (index = 0 ; index < MAX_CB ; ++index)
  1217.       {
  1218.           if (PerlSubs[index] == NULL)
  1219.           break ;
  1220.       }
  1221.     
  1222.       if (index < MAX_CB)
  1223.       {
  1224.           /* Remember the Perl sub */
  1225.           PerlSubs[index] = callback ;
  1226.           asynch_read(fh, Functions[index]) ;
  1227.       }
  1228.       else
  1229.           croak ("Too many callback functions registered\n") ;
  1230.     }
  1231.  
  1232.  
  1233. In this case the functions C<fn1>, C<fn2> and C<fn3> are used to remember
  1234. the Perl sub to be called. Each of the functions holds a separate 
  1235. hard-wired index which is used in the function C<Pcb> to access 
  1236. the C<PerlSubs> array and actually call the Perl sub. 
  1237.  
  1238. The obvious disadvantage of this technique is that there is a hard-wired 
  1239. limit (in this case 3) to the number of callbacks that can exist 
  1240. simultaneously. The only way to increase the limit is to modify the
  1241. code to add more functions and then re-compile.
  1242. None the less, as long as the number of functions is chosen with some
  1243. care, it is still a workable solution and in some cases is the only
  1244. one available.
  1245.  
  1246. To summarize, here are a number of possible methods for you to consider
  1247. for storing the mapping between C and the Perl callback
  1248.  
  1249. =over 5
  1250.  
  1251. =item 1. Ignore the problem - Only allow 1 callback
  1252.  
  1253. For a lot of situations, like interfacing to a error handler, this may be a 
  1254. perfectly adequate solution.
  1255.  
  1256. =item 2. Create a sequence of callbacks - hard wired limit
  1257.  
  1258. If it is impossible to tell from the parameters passed back from the 
  1259. C callback what the context is, then you
  1260. need to create a sequence of C callback interface functions, 
  1261. and store pointers to each in an array.
  1262.  
  1263. =item 3. Use a parameter to map to the Perl callback
  1264.  
  1265. Use a hash to store the mapping between C and Perl.
  1266.  
  1267. =back
  1268.  
  1269.  
  1270. =head2 Alternate Stack Manipulation
  1271.  
  1272.  
  1273. Although I have only made use of the C<POP*> macros to access values returned 
  1274. from Perl subs, it is also possible to bypass these macros and read the 
  1275. stack using the C<ST> macro (See L<perlapi> for a full description 
  1276. of the C<ST> macro). 
  1277.  
  1278. Most of the time the C<POP*> macros should be adequate, the main
  1279. problem with them is that they force you to process the returned values 
  1280. in sequence. This may not be the most suitable way to process the values
  1281. in some cases. Using the C<ST> macro will allow random access to the stack.
  1282.  
  1283. The code below is example 4 recoded to use C<ST> instead of C<POP*>.
  1284.  
  1285.     static void
  1286.     call_AddSubtract2(a, b)
  1287.     int a ;
  1288.     int b ;
  1289.     {
  1290.         dSP ;
  1291.     I32 ax ;
  1292.         int count ;
  1293.  
  1294.         ENTER ;
  1295.         SAVETMPS;
  1296.  
  1297.         PUSHMARK(sp) ;
  1298.         XPUSHs(sv_2mortal(newSViv(a)));
  1299.         XPUSHs(sv_2mortal(newSViv(b)));
  1300.         PUTBACK ;
  1301.  
  1302.         count = perl_call_pv("AddSubtract", G_ARRAY);
  1303.  
  1304.         SPAGAIN ;
  1305.     sp -= count ;
  1306.     ax = (sp - stack_base) + 1 ;
  1307.  
  1308.     if (count != 2)
  1309.         croak("Big trouble\n") ;
  1310.  
  1311.     printf ("%d - %d = %d\n", a, b, SViv(ST(0))) ;
  1312.     printf ("%d + %d = %d\n", a, b, SViv(ST(1))) ;
  1313.  
  1314.         PUTBACK ;
  1315.         FREETMPS ;
  1316.         LEAVE ;
  1317.     }
  1318.  
  1319.  
  1320. Notes
  1321.  
  1322. =over 5
  1323.  
  1324. =item 1.
  1325.  
  1326. Notice that it was necessary to define the variable C<ax>. 
  1327. This is because the C<ST> macro expects it to exist.
  1328. If we were in an XSUB it would not be necessary to define C<ax> as it is
  1329. already defined for you.
  1330.  
  1331. =item 2.
  1332.  
  1333. The code
  1334.     
  1335.         SPAGAIN ;
  1336.     sp -= count ;
  1337.     ax = (sp - stack_base) + 1 ;
  1338.  
  1339. sets the stack up so that we can use the C<ST> macro.
  1340.  
  1341. =item 3.
  1342.  
  1343. Remember that as with example 4, the returned values are 
  1344. still indexed in reverse order. 
  1345. So C<ST(0)> refers to the last value and C<ST(count-1)> refers to the first.
  1346.  
  1347. =back
  1348.  
  1349. =head1 SEE ALSO
  1350.  
  1351. L<perlapi>, L<perlguts>, L<perlembed>
  1352.  
  1353. =head1 AUTHOR
  1354.  
  1355. Paul Marquess <pmarquess@bfsec.bt.co.uk>
  1356.  
  1357. Special thanks to the following people who assisted in the creation of the 
  1358. document.
  1359.  
  1360. Jeff Okamoto, Tim Bunce, Nick Gianniotis.
  1361.  
  1362. =head1 DATE
  1363.  
  1364. Version 0.5, 6th January 1995
  1365.