This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perlapi: Consolidate sv_catpv-ish entries
[perl5.git] / pod / perlcall.pod
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 call Perl subroutines
8 directly from C, i.e., how to write I<callbacks>.
9
10 Apart from discussing the C interface provided by Perl for writing
11 callbacks the document uses a series of examples to show how the
12 interface actually works in practice.  In addition some techniques for
13 coding callbacks are covered.
14
15 Examples where callbacks are necessary include
16
17 =over 5
18
19 =item * An Error Handler
20
21 You have created an XSUB interface to an application's C API.
22
23 A fairly common feature in applications is to allow you to define a C
24 function that will be called whenever something nasty occurs. What we
25 would like is to be able to specify a Perl subroutine that will be
26 called instead.
27
28 =item * An Event-Driven Program
29
30 The classic example of where callbacks are used is when writing an
31 event driven program, such as for an X11 application.  In this case
32 you register functions to be called whenever specific events occur,
33 e.g., a mouse button is pressed, the cursor moves into a window or a
34 menu item is selected.
35
36 =back
37
38 Although the techniques described here are applicable when embedding
39 Perl in a C program, this is not the primary goal of this document.
40 There are other details that must be considered and are specific to
41 embedding Perl. For details on embedding Perl in C refer to
42 L<perlembed>.
43
44 Before you launch yourself head first into the rest of this document,
45 it would be a good idea to have read the following two documents--L<perlxs>
46 and L<perlguts>.
47
48 =head1 THE CALL_ FUNCTIONS
49
50 Although this stuff is easier to explain using examples, you first need
51 be aware of a few important definitions.
52
53 Perl has a number of C functions that allow you to call Perl
54 subroutines.  They are
55
56     I32 call_sv(SV* sv, I32 flags);
57     I32 call_pv(char *subname, I32 flags);
58     I32 call_method(char *methname, I32 flags);
59     I32 call_argv(char *subname, I32 flags, char **argv);
60
61 The key function is I<call_sv>.  All the other functions are
62 fairly simple wrappers which make it easier to call Perl subroutines in
63 special cases. At the end of the day they will all call I<call_sv>
64 to invoke the Perl subroutine.
65
66 All the I<call_*> functions have a C<flags> parameter which is
67 used to pass a bit mask of options to Perl.  This bit mask operates
68 identically for each of the functions.  The settings available in the
69 bit mask are discussed in L</FLAG VALUES>.
70
71 Each of the functions will now be discussed in turn.
72
73 =over 5
74
75 =item call_sv
76
77 I<call_sv> takes two parameters. The first, C<sv>, is an SV*.
78 This allows you to specify the Perl subroutine to be called either as a
79 C string (which has first been converted to an SV) or a reference to a
80 subroutine. The section, L</Using call_sv>, shows how you can make
81 use of I<call_sv>.
82
83 =item call_pv
84
85 The function, I<call_pv>, is similar to I<call_sv> except it
86 expects its first parameter to be a C char* which identifies the Perl
87 subroutine you want to call, e.g., C<call_pv("fred", 0)>.  If the
88 subroutine you want to call is in another package, just include the
89 package name in the string, e.g., C<"pkg::fred">.
90
91 =item call_method
92
93 The function I<call_method> is used to call a method from a Perl
94 class.  The parameter C<methname> corresponds to the name of the method
95 to be called.  Note that the class that the method belongs to is passed
96 on the Perl stack rather than in the parameter list. This class can be
97 either the name of the class (for a static method) or a reference to an
98 object (for a virtual method).  See L<perlobj> for more information on
99 static and virtual methods and L</Using call_method> for an example
100 of using I<call_method>.
101
102 =item call_argv
103
104 I<call_argv> calls the Perl subroutine specified by the C string
105 stored in the C<subname> parameter. It also takes the usual C<flags>
106 parameter.  The final parameter, C<argv>, consists of a NULL-terminated
107 list of C strings to be passed as parameters to the Perl subroutine.
108 See L</Using call_argv>.
109
110 =back
111
112 All the functions return an integer. This is a count of the number of
113 items returned by the Perl subroutine. The actual items returned by the
114 subroutine are stored on the Perl stack.
115
116 As a general rule you should I<always> check the return value from
117 these functions.  Even if you are expecting only a particular number of
118 values to be returned from the Perl subroutine, there is nothing to
119 stop someone from doing something unexpected--don't say you haven't
120 been warned.
121
122 =head1 FLAG VALUES
123
124 The C<flags> parameter in all the I<call_*> functions is one of C<G_VOID>,
125 C<G_SCALAR>, or C<G_ARRAY>, which indicate the call context, OR'ed together
126 with a bit mask of any combination of the other G_* symbols defined below.
127
128 =head2  G_VOID
129
130 =for apidoc AmnUh||G_VOID
131
132 Calls the Perl subroutine in a void context.
133
134 This flag has 2 effects:
135
136 =over 5
137
138 =item 1.
139
140 It indicates to the subroutine being called that it is executing in
141 a void context (if it executes I<wantarray> the result will be the
142 undefined value).
143
144 =item 2.
145
146 It ensures that nothing is actually returned from the subroutine.
147
148 =back
149
150 The value returned by the I<call_*> function indicates how many
151 items have been returned by the Perl subroutine--in this case it will
152 be 0.
153
154
155 =head2  G_SCALAR
156
157 =for apidoc AmnUh||G_SCALAR
158
159 Calls the Perl subroutine in a scalar context.  This is the default
160 context flag setting for all the I<call_*> functions.
161
162 This flag has 2 effects:
163
164 =over 5
165
166 =item 1.
167
168 It indicates to the subroutine being called that it is executing in a
169 scalar context (if it executes I<wantarray> the result will be false).
170
171 =item 2.
172
173 It ensures that only a scalar is actually returned from the subroutine.
174 The subroutine can, of course,  ignore the I<wantarray> and return a
175 list anyway. If so, then only the last element of the list will be
176 returned.
177
178 =back
179
180 The value returned by the I<call_*> function indicates how many
181 items have been returned by the Perl subroutine - in this case it will
182 be either 0 or 1.
183
184 If 0, then you have specified the G_DISCARD flag.
185
186 If 1, then the item actually returned by the Perl subroutine will be
187 stored on the Perl stack - the section L</Returning a Scalar> shows how
188 to access this value on the stack.  Remember that regardless of how
189 many items the Perl subroutine returns, only the last one will be
190 accessible from the stack - think of the case where only one value is
191 returned as being a list with only one element.  Any other items that
192 were returned will not exist by the time control returns from the
193 I<call_*> function.  The section L</Returning a List in Scalar
194 Context> shows an example of this behavior.
195
196
197 =head2 G_ARRAY
198
199 =for apidoc AmnUh||G_ARRAY
200
201 Calls the Perl subroutine in a list context.
202
203 As with G_SCALAR, this flag has 2 effects:
204
205 =over 5
206
207 =item 1.
208
209 It indicates to the subroutine being called that it is executing in a
210 list context (if it executes I<wantarray> the result will be true).
211
212 =item 2.
213
214 It ensures that all items returned from the subroutine will be
215 accessible when control returns from the I<call_*> function.
216
217 =back
218
219 The value returned by the I<call_*> function indicates how many
220 items have been returned by the Perl subroutine.
221
222 If 0, then you have specified the G_DISCARD flag.
223
224 If not 0, then it will be a count of the number of items returned by
225 the subroutine. These items will be stored on the Perl stack.  The
226 section L</Returning a List of Values> gives an example of using the
227 G_ARRAY flag and the mechanics of accessing the returned items from the
228 Perl stack.
229
230 =head2 G_DISCARD
231
232 =for apidoc AmnUh||G_DISCARD
233
234 By default, the I<call_*> functions place the items returned from
235 by the Perl subroutine on the stack.  If you are not interested in
236 these items, then setting this flag will make Perl get rid of them
237 automatically for you.  Note that it is still possible to indicate a
238 context to the Perl subroutine by using either G_SCALAR or G_ARRAY.
239
240 If you do not set this flag then it is I<very> important that you make
241 sure that any temporaries (i.e., parameters passed to the Perl
242 subroutine and values returned from the subroutine) are disposed of
243 yourself.  The section L</Returning a Scalar> gives details of how to
244 dispose of these temporaries explicitly and the section L</Using Perl to
245 Dispose of Temporaries> discusses the specific circumstances where you
246 can ignore the problem and let Perl deal with it for you.
247
248 =head2 G_NOARGS
249
250 =for apidoc AmnUh||G_NOARGS
251
252 Whenever a Perl subroutine is called using one of the I<call_*>
253 functions, it is assumed by default that parameters are to be passed to
254 the subroutine.  If you are not passing any parameters to the Perl
255 subroutine, you can save a bit of time by setting this flag.  It has
256 the effect of not creating the C<@_> array for the Perl subroutine.
257
258 Although the functionality provided by this flag may seem
259 straightforward, it should be used only if there is a good reason to do
260 so.  The reason for being cautious is that, even if you have specified
261 the G_NOARGS flag, it is still possible for the Perl subroutine that
262 has been called to think that you have passed it parameters.
263
264 In fact, what can happen is that the Perl subroutine you have called
265 can access the C<@_> array from a previous Perl subroutine.  This will
266 occur when the code that is executing the I<call_*> function has
267 itself been called from another Perl subroutine. The code below
268 illustrates this
269
270     sub fred
271       { print "@_\n"  }
272
273     sub joe
274       { &fred }
275
276     &joe(1,2,3);
277
278 This will print
279
280     1 2 3
281
282 What has happened is that C<fred> accesses the C<@_> array which
283 belongs to C<joe>.
284
285
286 =head2 G_EVAL
287
288 =for apidoc AmnUh||G_EVAL
289
290 It is possible for the Perl subroutine you are calling to terminate
291 abnormally, e.g., by calling I<die> explicitly or by not actually
292 existing.  By default, when either of these events occurs, the
293 process will terminate immediately.  If you want to trap this
294 type of event, specify the G_EVAL flag.  It will put an I<eval { }>
295 around the subroutine call.
296
297 Whenever control returns from the I<call_*> function you need to
298 check the C<$@> variable as you would in a normal Perl script.
299
300 The value returned from the I<call_*> function is dependent on
301 what other flags have been specified and whether an error has
302 occurred.  Here are all the different cases that can occur:
303
304 =over 5
305
306 =item *
307
308 If the I<call_*> function returns normally, then the value
309 returned is as specified in the previous sections.
310
311 =item *
312
313 If G_DISCARD is specified, the return value will always be 0.
314
315 =item *
316
317 If G_ARRAY is specified I<and> an error has occurred, the return value
318 will always be 0.
319
320 =item *
321
322 If G_SCALAR is specified I<and> an error has occurred, the return value
323 will be 1 and the value on the top of the stack will be I<undef>. This
324 means that if you have already detected the error by checking C<$@> and
325 you want the program to continue, you must remember to pop the I<undef>
326 from the stack.
327
328 =back
329
330 See L</Using G_EVAL> for details on using G_EVAL.
331
332 =head2 G_KEEPERR
333
334 =for apidoc AmnUh||G_KEEPERR
335
336 Using the G_EVAL flag described above will always set C<$@>: clearing
337 it if there was no error, and setting it to describe the error if there
338 was an error in the called code.  This is what you want if your intention
339 is to handle possible errors, but sometimes you just want to trap errors
340 and stop them interfering with the rest of the program.
341
342 This scenario will mostly be applicable to code that is meant to be called
343 from within destructors, asynchronous callbacks, and signal handlers.
344 In such situations, where the code being called has little relation to the
345 surrounding dynamic context, the main program needs to be insulated from
346 errors in the called code, even if they can't be handled intelligently.
347 It may also be useful to do this with code for C<__DIE__> or C<__WARN__>
348 hooks, and C<tie> functions.
349
350 The G_KEEPERR flag is meant to be used in conjunction with G_EVAL in
351 I<call_*> functions that are used to implement such code, or with
352 C<eval_sv>.  This flag has no effect on the C<call_*> functions when
353 G_EVAL is not used.
354
355 When G_KEEPERR is used, any error in the called code will terminate the
356 call as usual, and the error will not propagate beyond the call (as usual
357 for G_EVAL), but it will not go into C<$@>.  Instead the error will be
358 converted into a warning, prefixed with the string "\t(in cleanup)".
359 This can be disabled using C<no warnings 'misc'>.  If there is no error,
360 C<$@> will not be cleared.
361
362 Note that the G_KEEPERR flag does not propagate into inner evals; these
363 may still set C<$@>.
364
365 The G_KEEPERR flag was introduced in Perl version 5.002.
366
367 See L</Using G_KEEPERR> for an example of a situation that warrants the
368 use of this flag.
369
370 =head2 Determining the Context
371
372 As mentioned above, you can determine the context of the currently
373 executing subroutine in Perl with I<wantarray>.  The equivalent test
374 can be made in C by using the C<GIMME_V> macro, which returns
375 C<G_ARRAY> if you have been called in a list context, C<G_SCALAR> if
376 in a scalar context, or C<G_VOID> if in a void context (i.e., the
377 return value will not be used).  An older version of this macro is
378 called C<GIMME>; in a void context it returns C<G_SCALAR> instead of
379 C<G_VOID>.  An example of using the C<GIMME_V> macro is shown in
380 section L</Using GIMME_V>.
381
382 =head1 EXAMPLES
383
384 Enough of the definition talk! Let's have a few examples.
385
386 Perl provides many macros to assist in accessing the Perl stack.
387 Wherever possible, these macros should always be used when interfacing
388 to Perl internals.  We hope this should make the code less vulnerable
389 to any changes made to Perl in the future.
390
391 Another point worth noting is that in the first series of examples I
392 have made use of only the I<call_pv> function.  This has been done
393 to keep the code simpler and ease you into the topic.  Wherever
394 possible, if the choice is between using I<call_pv> and
395 I<call_sv>, you should always try to use I<call_sv>.  See
396 L</Using call_sv> for details.
397
398 =head2 No Parameters, Nothing Returned
399
400 This first trivial example will call a Perl subroutine, I<PrintUID>, to
401 print out the UID of the process.
402
403     sub PrintUID
404     {
405         print "UID is $<\n";
406     }
407
408 and here is a C function to call it
409
410     static void
411     call_PrintUID()
412     {
413         dSP;
414
415         PUSHMARK(SP);
416         call_pv("PrintUID", G_DISCARD|G_NOARGS);
417     }
418
419 Simple, eh?
420
421 A few points to note about this example:
422
423 =over 5
424
425 =item 1.
426
427 Ignore C<dSP> and C<PUSHMARK(SP)> for now. They will be discussed in
428 the next example.
429
430 =item 2.
431
432 We aren't passing any parameters to I<PrintUID> so G_NOARGS can be
433 specified.
434
435 =item 3.
436
437 We aren't interested in anything returned from I<PrintUID>, so
438 G_DISCARD is specified. Even if I<PrintUID> was changed to
439 return some value(s), having specified G_DISCARD will mean that they
440 will be wiped by the time control returns from I<call_pv>.
441
442 =item 4.
443
444 As I<call_pv> is being used, the Perl subroutine is specified as a
445 C string. In this case the subroutine name has been 'hard-wired' into the
446 code.
447
448 =item 5.
449
450 Because we specified G_DISCARD, it is not necessary to check the value
451 returned from I<call_pv>. It will always be 0.
452
453 =back
454
455 =head2 Passing Parameters
456
457 Now let's make a slightly more complex example. This time we want to
458 call a Perl subroutine, C<LeftString>, which will take 2 parameters--a
459 string ($s) and an integer ($n).  The subroutine will simply
460 print the first $n characters of the string.
461
462 So the Perl subroutine would look like this:
463
464     sub LeftString
465     {
466         my($s, $n) = @_;
467         print substr($s, 0, $n), "\n";
468     }
469
470 The C function required to call I<LeftString> would look like this:
471
472     static void
473     call_LeftString(a, b)
474     char * a;
475     int b;
476     {
477         dSP;
478
479         ENTER;
480         SAVETMPS;
481
482         PUSHMARK(SP);
483         EXTEND(SP, 2);
484         PUSHs(sv_2mortal(newSVpv(a, 0)));
485         PUSHs(sv_2mortal(newSViv(b)));
486         PUTBACK;
487
488         call_pv("LeftString", G_DISCARD);
489
490         FREETMPS;
491         LEAVE;
492     }
493
494 Here are a few notes on the C function I<call_LeftString>.
495
496 =over 5
497
498 =item 1.
499
500 Parameters are passed to the Perl subroutine using the Perl stack.
501 This is the purpose of the code beginning with the line C<dSP> and
502 ending with the line C<PUTBACK>.  The C<dSP> declares a local copy
503 of the stack pointer.  This local copy should B<always> be accessed
504 as C<SP>.
505
506 =item 2.
507
508 If you are going to put something onto the Perl stack, you need to know
509 where to put it. This is the purpose of the macro C<dSP>--it declares
510 and initializes a I<local> copy of the Perl stack pointer.
511
512 All the other macros which will be used in this example require you to
513 have used this macro.
514
515 The exception to this rule is if you are calling a Perl subroutine
516 directly from an XSUB function. In this case it is not necessary to
517 use the C<dSP> macro explicitly--it will be declared for you
518 automatically.
519
520 =item 3.
521
522 Any parameters to be pushed onto the stack should be bracketed by the
523 C<PUSHMARK> and C<PUTBACK> macros.  The purpose of these two macros, in
524 this context, is to count the number of parameters you are
525 pushing automatically.  Then whenever Perl is creating the C<@_> array for the
526 subroutine, it knows how big to make it.
527
528 The C<PUSHMARK> macro tells Perl to make a mental note of the current
529 stack pointer. Even if you aren't passing any parameters (like the
530 example shown in the section L</No Parameters, Nothing Returned>) you
531 must still call the C<PUSHMARK> macro before you can call any of the
532 I<call_*> functions--Perl still needs to know that there are no
533 parameters.
534
535 The C<PUTBACK> macro sets the global copy of the stack pointer to be
536 the same as our local copy. If we didn't do this, I<call_pv>
537 wouldn't know where the two parameters we pushed were--remember that
538 up to now all the stack pointer manipulation we have done is with our
539 local copy, I<not> the global copy.
540
541 =item 4.
542
543 Next, we come to EXTEND and PUSHs. This is where the parameters
544 actually get pushed onto the stack. In this case we are pushing a
545 string and an integer.
546
547 Alternatively you can use the XPUSHs() macro, which combines a
548 C<EXTEND(SP, 1)> and C<PUSHs()>.  This is less efficient if you're
549 pushing multiple values.
550
551 See L<perlguts/"XSUBs and the Argument Stack"> for details
552 on how the PUSH macros work.
553
554 =item 5.
555
556 Because we created temporary values (by means of sv_2mortal() calls)
557 we will have to tidy up the Perl stack and dispose of mortal SVs.
558
559 This is the purpose of
560
561     ENTER;
562     SAVETMPS;
563
564 at the start of the function, and
565
566     FREETMPS;
567     LEAVE;
568
569 at the end. The C<ENTER>/C<SAVETMPS> pair creates a boundary for any
570 temporaries we create.  This means that the temporaries we get rid of
571 will be limited to those which were created after these calls.
572
573 The C<FREETMPS>/C<LEAVE> pair will get rid of any values returned by
574 the Perl subroutine (see next example), plus it will also dump the
575 mortal SVs we have created.  Having C<ENTER>/C<SAVETMPS> at the
576 beginning of the code makes sure that no other mortals are destroyed.
577
578 Think of these macros as working a bit like C<{> and C<}> in Perl
579 to limit the scope of local variables.
580
581 See the section L</Using Perl to Dispose of Temporaries> for details of
582 an alternative to using these macros.
583
584 =item 6.
585
586 Finally, I<LeftString> can now be called via the I<call_pv> function.
587 The only flag specified this time is G_DISCARD. Because we are passing
588 2 parameters to the Perl subroutine this time, we have not specified
589 G_NOARGS.
590
591 =back
592
593 =head2 Returning a Scalar
594
595 Now for an example of dealing with the items returned from a Perl
596 subroutine.
597
598 Here is a Perl subroutine, I<Adder>, that takes 2 integer parameters
599 and simply returns their sum.
600
601     sub Adder
602     {
603         my($a, $b) = @_;
604         $a + $b;
605     }
606
607 Because we are now concerned with the return value from I<Adder>, the C
608 function required to call it is now a bit more complex.
609
610     static void
611     call_Adder(a, b)
612     int a;
613     int b;
614     {
615         dSP;
616         int count;
617
618         ENTER;
619         SAVETMPS;
620
621         PUSHMARK(SP);
622         EXTEND(SP, 2);
623         PUSHs(sv_2mortal(newSViv(a)));
624         PUSHs(sv_2mortal(newSViv(b)));
625         PUTBACK;
626
627         count = call_pv("Adder", G_SCALAR);
628
629         SPAGAIN;
630
631         if (count != 1)
632             croak("Big trouble\n");
633
634         printf ("The sum of %d and %d is %d\n", a, b, POPi);
635
636         PUTBACK;
637         FREETMPS;
638         LEAVE;
639     }
640
641 Points to note this time are
642
643 =over 5
644
645 =item 1.
646
647 The only flag specified this time was G_SCALAR. That means that the C<@_>
648 array will be created and that the value returned by I<Adder> will
649 still exist after the call to I<call_pv>.
650
651 =item 2.
652
653 The purpose of the macro C<SPAGAIN> is to refresh the local copy of the
654 stack pointer. This is necessary because it is possible that the memory
655 allocated to the Perl stack has been reallocated during the
656 I<call_pv> call.
657
658 If you are making use of the Perl stack pointer in your code you must
659 always refresh the local copy using SPAGAIN whenever you make use
660 of the I<call_*> functions or any other Perl internal function.
661
662 =item 3.
663
664 Although only a single value was expected to be returned from I<Adder>,
665 it is still good practice to check the return code from I<call_pv>
666 anyway.
667
668 Expecting a single value is not quite the same as knowing that there
669 will be one. If someone modified I<Adder> to return a list and we
670 didn't check for that possibility and take appropriate action the Perl
671 stack would end up in an inconsistent state. That is something you
672 I<really> don't want to happen ever.
673
674 =item 4.
675
676 The C<POPi> macro is used here to pop the return value from the stack.
677 In this case we wanted an integer, so C<POPi> was used.
678
679
680 Here is the complete list of POP macros available, along with the types
681 they return.
682
683     POPs        SV
684     POPp        pointer (PV)
685     POPpbytex   pointer to bytes (PV)
686     POPn        double (NV)
687     POPi        integer (IV)
688     POPu        unsigned integer (UV)
689     POPl        long
690     POPul       unsigned long
691
692 Since these macros have side-effects don't use them as arguments to
693 macros that may evaluate their argument several times, for example:
694
695   /* Bad idea, don't do this */
696   STRLEN len;
697   const char *s = SvPV(POPs, len);
698
699 Instead, use a temporary:
700
701   STRLEN len;
702   SV *sv = POPs;
703   const char *s = SvPV(sv, len);
704
705 or a macro that guarantees it will evaluate its arguments only once:
706
707   STRLEN len;
708   const char *s = SvPVx(POPs, len);
709
710 =item 5.
711
712 The final C<PUTBACK> is used to leave the Perl stack in a consistent
713 state before exiting the function.  This is necessary because when we
714 popped the return value from the stack with C<POPi> it updated only our
715 local copy of the stack pointer.  Remember, C<PUTBACK> sets the global
716 stack pointer to be the same as our local copy.
717
718 =back
719
720
721 =head2 Returning a List of Values
722
723 Now, let's extend the previous example to return both the sum of the
724 parameters and the difference.
725
726 Here is the Perl subroutine
727
728     sub AddSubtract
729     {
730        my($a, $b) = @_;
731        ($a+$b, $a-$b);
732     }
733
734 and this is the C function
735
736     static void
737     call_AddSubtract(a, b)
738     int a;
739     int b;
740     {
741         dSP;
742         int count;
743
744         ENTER;
745         SAVETMPS;
746
747         PUSHMARK(SP);
748         EXTEND(SP, 2);
749         PUSHs(sv_2mortal(newSViv(a)));
750         PUSHs(sv_2mortal(newSViv(b)));
751         PUTBACK;
752
753         count = call_pv("AddSubtract", G_ARRAY);
754
755         SPAGAIN;
756
757         if (count != 2)
758             croak("Big trouble\n");
759
760         printf ("%d - %d = %d\n", a, b, POPi);
761         printf ("%d + %d = %d\n", a, b, POPi);
762
763         PUTBACK;
764         FREETMPS;
765         LEAVE;
766     }
767
768 If I<call_AddSubtract> is called like this
769
770     call_AddSubtract(7, 4);
771
772 then here is the output
773
774     7 - 4 = 3
775     7 + 4 = 11
776
777 Notes
778
779 =over 5
780
781 =item 1.
782
783 We wanted list context, so G_ARRAY was used.
784
785 =item 2.
786
787 Not surprisingly C<POPi> is used twice this time because we were
788 retrieving 2 values from the stack. The important thing to note is that
789 when using the C<POP*> macros they come off the stack in I<reverse>
790 order.
791
792 =back
793
794 =head2 Returning a List in Scalar Context
795
796 Say the Perl subroutine in the previous section was called in a scalar
797 context, like this
798
799     static void
800     call_AddSubScalar(a, b)
801     int a;
802     int b;
803     {
804         dSP;
805         int count;
806         int i;
807
808         ENTER;
809         SAVETMPS;
810
811         PUSHMARK(SP);
812         EXTEND(SP, 2);
813         PUSHs(sv_2mortal(newSViv(a)));
814         PUSHs(sv_2mortal(newSViv(b)));
815         PUTBACK;
816
817         count = call_pv("AddSubtract", G_SCALAR);
818
819         SPAGAIN;
820
821         printf ("Items Returned = %d\n", count);
822
823         for (i = 1; i <= count; ++i)
824             printf ("Value %d = %d\n", i, POPi);
825
826         PUTBACK;
827         FREETMPS;
828         LEAVE;
829     }
830
831 The other modification made is that I<call_AddSubScalar> will print the
832 number of items returned from the Perl subroutine and their value (for
833 simplicity it assumes that they are integer).  So if
834 I<call_AddSubScalar> is called
835
836     call_AddSubScalar(7, 4);
837
838 then the output will be
839
840     Items Returned = 1
841     Value 1 = 3
842
843 In this case the main point to note is that only the last item in the
844 list is returned from the subroutine. I<AddSubtract> actually made it back to
845 I<call_AddSubScalar>.
846
847
848 =head2 Returning Data from Perl via the Parameter List
849
850 It is also possible to return values directly via the parameter
851 list--whether it is actually desirable to do it is another matter entirely.
852
853 The Perl subroutine, I<Inc>, below takes 2 parameters and increments
854 each directly.
855
856     sub Inc
857     {
858         ++ $_[0];
859         ++ $_[1];
860     }
861
862 and here is a C function to call it.
863
864     static void
865     call_Inc(a, b)
866     int a;
867     int b;
868     {
869         dSP;
870         int count;
871         SV * sva;
872         SV * svb;
873
874         ENTER;
875         SAVETMPS;
876
877         sva = sv_2mortal(newSViv(a));
878         svb = sv_2mortal(newSViv(b));
879
880         PUSHMARK(SP);
881         EXTEND(SP, 2);
882         PUSHs(sva);
883         PUSHs(svb);
884         PUTBACK;
885
886         count = call_pv("Inc", G_DISCARD);
887
888         if (count != 0)
889             croak ("call_Inc: expected 0 values from 'Inc', got %d\n",
890                    count);
891
892         printf ("%d + 1 = %d\n", a, SvIV(sva));
893         printf ("%d + 1 = %d\n", b, SvIV(svb));
894
895         FREETMPS;
896         LEAVE;
897     }
898
899 To be able to access the two parameters that were pushed onto the stack
900 after they return from I<call_pv> it is necessary to make a note
901 of their addresses--thus the two variables C<sva> and C<svb>.
902
903 The reason this is necessary is that the area of the Perl stack which
904 held them will very likely have been overwritten by something else by
905 the time control returns from I<call_pv>.
906
907
908
909
910 =head2 Using G_EVAL
911
912 Now an example using G_EVAL. Below is a Perl subroutine which computes
913 the difference of its 2 parameters. If this would result in a negative
914 result, the subroutine calls I<die>.
915
916     sub Subtract
917     {
918         my ($a, $b) = @_;
919
920         die "death can be fatal\n" if $a < $b;
921
922         $a - $b;
923     }
924
925 and some C to call it
926
927  static void
928  call_Subtract(a, b)
929  int a;
930  int b;
931  {
932      dSP;
933      int count;
934      SV *err_tmp;
935
936      ENTER;
937      SAVETMPS;
938
939      PUSHMARK(SP);
940      EXTEND(SP, 2);
941      PUSHs(sv_2mortal(newSViv(a)));
942      PUSHs(sv_2mortal(newSViv(b)));
943      PUTBACK;
944
945      count = call_pv("Subtract", G_EVAL|G_SCALAR);
946
947      SPAGAIN;
948
949      /* Check the eval first */
950      err_tmp = ERRSV;
951      if (SvTRUE(err_tmp))
952      {
953          printf ("Uh oh - %s\n", SvPV_nolen(err_tmp));
954          POPs;
955      }
956      else
957      {
958        if (count != 1)
959         croak("call_Subtract: wanted 1 value from 'Subtract', got %d\n",
960               count);
961
962          printf ("%d - %d = %d\n", a, b, POPi);
963      }
964
965      PUTBACK;
966      FREETMPS;
967      LEAVE;
968  }
969
970 If I<call_Subtract> is called thus
971
972     call_Subtract(4, 5)
973
974 the following will be printed
975
976     Uh oh - death can be fatal
977
978 Notes
979
980 =over 5
981
982 =item 1.
983
984 We want to be able to catch the I<die> so we have used the G_EVAL
985 flag.  Not specifying this flag would mean that the program would
986 terminate immediately at the I<die> statement in the subroutine
987 I<Subtract>.
988
989 =item 2.
990
991 The code
992
993     err_tmp = ERRSV;
994     if (SvTRUE(err_tmp))
995     {
996         printf ("Uh oh - %s\n", SvPV_nolen(err_tmp));
997         POPs;
998     }
999
1000 is the direct equivalent of this bit of Perl
1001
1002     print "Uh oh - $@\n" if $@;
1003
1004 C<PL_errgv> is a perl global of type C<GV *> that points to the symbol
1005 table entry containing the error.  C<ERRSV> therefore refers to the C
1006 equivalent of C<$@>.  We use a local temporary, C<err_tmp>, since
1007 C<ERRSV> is a macro that calls a function, and C<SvTRUE(ERRSV)> would
1008 end up calling that function multiple times.
1009
1010 =for apidoc AmnUh|GV *|PL_errgv
1011
1012 =item 3.
1013
1014 Note that the stack is popped using C<POPs> in the block where
1015 C<SvTRUE(err_tmp)> is true.  This is necessary because whenever a
1016 I<call_*> function invoked with G_EVAL|G_SCALAR returns an error,
1017 the top of the stack holds the value I<undef>. Because we want the
1018 program to continue after detecting this error, it is essential that
1019 the stack be tidied up by removing the I<undef>.
1020
1021 =back
1022
1023
1024 =head2 Using G_KEEPERR
1025
1026 Consider this rather facetious example, where we have used an XS
1027 version of the call_Subtract example above inside a destructor:
1028
1029     package Foo;
1030     sub new { bless {}, $_[0] }
1031     sub Subtract {
1032         my($a,$b) = @_;
1033         die "death can be fatal" if $a < $b;
1034         $a - $b;
1035     }
1036     sub DESTROY { call_Subtract(5, 4); }
1037     sub foo { die "foo dies"; }
1038
1039     package main;
1040     {
1041         my $foo = Foo->new;
1042         eval { $foo->foo };
1043     }
1044     print "Saw: $@" if $@;             # should be, but isn't
1045
1046 This example will fail to recognize that an error occurred inside the
1047 C<eval {}>.  Here's why: the call_Subtract code got executed while perl
1048 was cleaning up temporaries when exiting the outer braced block, and because
1049 call_Subtract is implemented with I<call_pv> using the G_EVAL
1050 flag, it promptly reset C<$@>.  This results in the failure of the
1051 outermost test for C<$@>, and thereby the failure of the error trap.
1052
1053 Appending the G_KEEPERR flag, so that the I<call_pv> call in
1054 call_Subtract reads:
1055
1056         count = call_pv("Subtract", G_EVAL|G_SCALAR|G_KEEPERR);
1057
1058 will preserve the error and restore reliable error handling.
1059
1060 =head2 Using call_sv
1061
1062 In all the previous examples I have 'hard-wired' the name of the Perl
1063 subroutine to be called from C.  Most of the time though, it is more
1064 convenient to be able to specify the name of the Perl subroutine from
1065 within the Perl script, and you'll want to use
1066 L<call_sv|perlapi/call_sv>.
1067
1068 Consider the Perl code below
1069
1070     sub fred
1071     {
1072         print "Hello there\n";
1073     }
1074
1075     CallSubPV("fred");
1076
1077 Here is a snippet of XSUB which defines I<CallSubPV>.
1078
1079     void
1080     CallSubPV(name)
1081         char *  name
1082         CODE:
1083         PUSHMARK(SP);
1084         call_pv(name, G_DISCARD|G_NOARGS);
1085
1086 That is fine as far as it goes. The thing is, the Perl subroutine
1087 can be specified as only a string, however, Perl allows references
1088 to subroutines and anonymous subroutines.
1089 This is where I<call_sv> is useful.
1090
1091 The code below for I<CallSubSV> is identical to I<CallSubPV> except
1092 that the C<name> parameter is now defined as an SV* and we use
1093 I<call_sv> instead of I<call_pv>.
1094
1095     void
1096     CallSubSV(name)
1097         SV *    name
1098         CODE:
1099         PUSHMARK(SP);
1100         call_sv(name, G_DISCARD|G_NOARGS);
1101
1102 Because we are using an SV to call I<fred> the following can all be used:
1103
1104     CallSubSV("fred");
1105     CallSubSV(\&fred);
1106     $ref = \&fred;
1107     CallSubSV($ref);
1108     CallSubSV( sub { print "Hello there\n" } );
1109
1110 As you can see, I<call_sv> gives you much greater flexibility in
1111 how you can specify the Perl subroutine.
1112
1113 You should note that, if it is necessary to store the SV (C<name> in the
1114 example above) which corresponds to the Perl subroutine so that it can
1115 be used later in the program, it not enough just to store a copy of the
1116 pointer to the SV. Say the code above had been like this:
1117
1118     static SV * rememberSub;
1119
1120     void
1121     SaveSub1(name)
1122         SV *    name
1123         CODE:
1124         rememberSub = name;
1125
1126     void
1127     CallSavedSub1()
1128         CODE:
1129         PUSHMARK(SP);
1130         call_sv(rememberSub, G_DISCARD|G_NOARGS);
1131
1132 The reason this is wrong is that, by the time you come to use the
1133 pointer C<rememberSub> in C<CallSavedSub1>, it may or may not still refer
1134 to the Perl subroutine that was recorded in C<SaveSub1>.  This is
1135 particularly true for these cases:
1136
1137     SaveSub1(\&fred);
1138     CallSavedSub1();
1139
1140     SaveSub1( sub { print "Hello there\n" } );
1141     CallSavedSub1();
1142
1143 By the time each of the C<SaveSub1> statements above has been executed,
1144 the SV*s which corresponded to the parameters will no longer exist.
1145 Expect an error message from Perl of the form
1146
1147     Can't use an undefined value as a subroutine reference at ...
1148
1149 for each of the C<CallSavedSub1> lines.
1150
1151 Similarly, with this code
1152
1153     $ref = \&fred;
1154     SaveSub1($ref);
1155     $ref = 47;
1156     CallSavedSub1();
1157
1158 you can expect one of these messages (which you actually get is dependent on
1159 the version of Perl you are using)
1160
1161     Not a CODE reference at ...
1162     Undefined subroutine &main::47 called ...
1163
1164 The variable $ref may have referred to the subroutine C<fred>
1165 whenever the call to C<SaveSub1> was made but by the time
1166 C<CallSavedSub1> gets called it now holds the number C<47>. Because we
1167 saved only a pointer to the original SV in C<SaveSub1>, any changes to
1168 $ref will be tracked by the pointer C<rememberSub>. This means that
1169 whenever C<CallSavedSub1> gets called, it will attempt to execute the
1170 code which is referenced by the SV* C<rememberSub>.  In this case
1171 though, it now refers to the integer C<47>, so expect Perl to complain
1172 loudly.
1173
1174 A similar but more subtle problem is illustrated with this code:
1175
1176     $ref = \&fred;
1177     SaveSub1($ref);
1178     $ref = \&joe;
1179     CallSavedSub1();
1180
1181 This time whenever C<CallSavedSub1> gets called it will execute the Perl
1182 subroutine C<joe> (assuming it exists) rather than C<fred> as was
1183 originally requested in the call to C<SaveSub1>.
1184
1185 To get around these problems it is necessary to take a full copy of the
1186 SV.  The code below shows C<SaveSub2> modified to do that.
1187
1188     /* this isn't thread-safe */
1189     static SV * keepSub = (SV*)NULL;
1190
1191     void
1192     SaveSub2(name)
1193         SV *    name
1194         CODE:
1195         /* Take a copy of the callback */
1196         if (keepSub == (SV*)NULL)
1197             /* First time, so create a new SV */
1198             keepSub = newSVsv(name);
1199         else
1200             /* Been here before, so overwrite */
1201             SvSetSV(keepSub, name);
1202
1203     void
1204     CallSavedSub2()
1205         CODE:
1206         PUSHMARK(SP);
1207         call_sv(keepSub, G_DISCARD|G_NOARGS);
1208
1209 To avoid creating a new SV every time C<SaveSub2> is called,
1210 the function first checks to see if it has been called before.  If not,
1211 then space for a new SV is allocated and the reference to the Perl
1212 subroutine C<name> is copied to the variable C<keepSub> in one
1213 operation using C<newSVsv>.  Thereafter, whenever C<SaveSub2> is called,
1214 the existing SV, C<keepSub>, is overwritten with the new value using
1215 C<SvSetSV>.
1216
1217 Note: using a static or global variable to store the SV isn't
1218 thread-safe.  You can either use the C<MY_CXT> mechanism documented in
1219 L<perlxs/Safely Storing Static Data in XS> which is fast, or store the
1220 values in perl global variables, using get_sv(), which is much slower.
1221
1222 =head2 Using call_argv
1223
1224 Here is a Perl subroutine which prints whatever parameters are passed
1225 to it.
1226
1227     sub PrintList
1228     {
1229         my(@list) = @_;
1230
1231         foreach (@list) { print "$_\n" }
1232     }
1233
1234 And here is an example of I<call_argv> which will call
1235 I<PrintList>.
1236
1237     static char * words[] = {"alpha", "beta", "gamma", "delta", NULL};
1238
1239     static void
1240     call_PrintList()
1241     {
1242         call_argv("PrintList", G_DISCARD, words);
1243     }
1244
1245 Note that it is not necessary to call C<PUSHMARK> in this instance.
1246 This is because I<call_argv> will do it for you.
1247
1248 =head2 Using call_method
1249
1250 Consider the following Perl code:
1251
1252     {
1253         package Mine;
1254
1255         sub new
1256         {
1257             my($type) = shift;
1258             bless [@_]
1259         }
1260
1261         sub Display
1262         {
1263             my ($self, $index) = @_;
1264             print "$index: $$self[$index]\n";
1265         }
1266
1267         sub PrintID
1268         {
1269             my($class) = @_;
1270             print "This is Class $class version 1.0\n";
1271         }
1272     }
1273
1274 It implements just a very simple class to manage an array.  Apart from
1275 the constructor, C<new>, it declares methods, one static and one
1276 virtual. The static method, C<PrintID>, prints out simply the class
1277 name and a version number. The virtual method, C<Display>, prints out a
1278 single element of the array.  Here is an all-Perl example of using it.
1279
1280     $a = Mine->new('red', 'green', 'blue');
1281     $a->Display(1);
1282     Mine->PrintID;
1283
1284 will print
1285
1286     1: green
1287     This is Class Mine version 1.0
1288
1289 Calling a Perl method from C is fairly straightforward. The following
1290 things are required:
1291
1292 =over 5
1293
1294 =item *
1295
1296 A reference to the object for a virtual method or the name of the class
1297 for a static method
1298
1299 =item *
1300
1301 The name of the method
1302
1303 =item *
1304
1305 Any other parameters specific to the method
1306
1307 =back
1308
1309 Here is a simple XSUB which illustrates the mechanics of calling both
1310 the C<PrintID> and C<Display> methods from C.
1311
1312     void
1313     call_Method(ref, method, index)
1314         SV *    ref
1315         char *  method
1316         int             index
1317         CODE:
1318         PUSHMARK(SP);
1319         EXTEND(SP, 2);
1320         PUSHs(ref);
1321         PUSHs(sv_2mortal(newSViv(index)));
1322         PUTBACK;
1323
1324         call_method(method, G_DISCARD);
1325
1326     void
1327     call_PrintID(class, method)
1328         char *  class
1329         char *  method
1330         CODE:
1331         PUSHMARK(SP);
1332         XPUSHs(sv_2mortal(newSVpv(class, 0)));
1333         PUTBACK;
1334
1335         call_method(method, G_DISCARD);
1336
1337
1338 So the methods C<PrintID> and C<Display> can be invoked like this:
1339
1340     $a = Mine->new('red', 'green', 'blue');
1341     call_Method($a, 'Display', 1);
1342     call_PrintID('Mine', 'PrintID');
1343
1344 The only thing to note is that, in both the static and virtual methods,
1345 the method name is not passed via the stack--it is used as the first
1346 parameter to I<call_method>.
1347
1348 =head2 Using GIMME_V
1349
1350 Here is a trivial XSUB which prints the context in which it is
1351 currently executing.
1352
1353     void
1354     PrintContext()
1355         CODE:
1356         U8 gimme = GIMME_V;
1357         if (gimme == G_VOID)
1358             printf ("Context is Void\n");
1359         else if (gimme == G_SCALAR)
1360             printf ("Context is Scalar\n");
1361         else
1362             printf ("Context is Array\n");
1363
1364 And here is some Perl to test it.
1365
1366     PrintContext;
1367     $a = PrintContext;
1368     @a = PrintContext;
1369
1370 The output from that will be
1371
1372     Context is Void
1373     Context is Scalar
1374     Context is Array
1375
1376 =head2 Using Perl to Dispose of Temporaries
1377
1378 In the examples given to date, any temporaries created in the callback
1379 (i.e., parameters passed on the stack to the I<call_*> function or
1380 values returned via the stack) have been freed by one of these methods:
1381
1382 =over 5
1383
1384 =item *
1385
1386 Specifying the G_DISCARD flag with I<call_*>
1387
1388 =item *
1389
1390 Explicitly using the C<ENTER>/C<SAVETMPS>--C<FREETMPS>/C<LEAVE> pairing
1391
1392 =back
1393
1394 There is another method which can be used, namely letting Perl do it
1395 for you automatically whenever it regains control after the callback
1396 has terminated.  This is done by simply not using the
1397
1398     ENTER;
1399     SAVETMPS;
1400     ...
1401     FREETMPS;
1402     LEAVE;
1403
1404 sequence in the callback (and not, of course, specifying the G_DISCARD
1405 flag).
1406
1407 If you are going to use this method you have to be aware of a possible
1408 memory leak which can arise under very specific circumstances.  To
1409 explain these circumstances you need to know a bit about the flow of
1410 control between Perl and the callback routine.
1411
1412 The examples given at the start of the document (an error handler and
1413 an event driven program) are typical of the two main sorts of flow
1414 control that you are likely to encounter with callbacks.  There is a
1415 very important distinction between them, so pay attention.
1416
1417 In the first example, an error handler, the flow of control could be as
1418 follows.  You have created an interface to an external library.
1419 Control can reach the external library like this
1420
1421     perl --> XSUB --> external library
1422
1423 Whilst control is in the library, an error condition occurs. You have
1424 previously set up a Perl callback to handle this situation, so it will
1425 get executed. Once the callback has finished, control will drop back to
1426 Perl again.  Here is what the flow of control will be like in that
1427 situation
1428
1429     perl --> XSUB --> external library
1430                       ...
1431                       error occurs
1432                       ...
1433                       external library --> call_* --> perl
1434                                                           |
1435     perl <-- XSUB <-- external library <-- call_* <----+
1436
1437 After processing of the error using I<call_*> is completed,
1438 control reverts back to Perl more or less immediately.
1439
1440 In the diagram, the further right you go the more deeply nested the
1441 scope is.  It is only when control is back with perl on the extreme
1442 left of the diagram that you will have dropped back to the enclosing
1443 scope and any temporaries you have left hanging around will be freed.
1444
1445 In the second example, an event driven program, the flow of control
1446 will be more like this
1447
1448     perl --> XSUB --> event handler
1449                       ...
1450                       event handler --> call_* --> perl
1451                                                        |
1452                       event handler <-- call_* <----+
1453                       ...
1454                       event handler --> call_* --> perl
1455                                                        |
1456                       event handler <-- call_* <----+
1457                       ...
1458                       event handler --> call_* --> perl
1459                                                        |
1460                       event handler <-- call_* <----+
1461
1462 In this case the flow of control can consist of only the repeated
1463 sequence
1464
1465     event handler --> call_* --> perl
1466
1467 for practically the complete duration of the program.  This means that
1468 control may I<never> drop back to the surrounding scope in Perl at the
1469 extreme left.
1470
1471 So what is the big problem? Well, if you are expecting Perl to tidy up
1472 those temporaries for you, you might be in for a long wait.  For Perl
1473 to dispose of your temporaries, control must drop back to the
1474 enclosing scope at some stage.  In the event driven scenario that may
1475 never happen.  This means that, as time goes on, your program will
1476 create more and more temporaries, none of which will ever be freed. As
1477 each of these temporaries consumes some memory your program will
1478 eventually consume all the available memory in your system--kapow!
1479
1480 So here is the bottom line--if you are sure that control will revert
1481 back to the enclosing Perl scope fairly quickly after the end of your
1482 callback, then it isn't absolutely necessary to dispose explicitly of
1483 any temporaries you may have created. Mind you, if you are at all
1484 uncertain about what to do, it doesn't do any harm to tidy up anyway.
1485
1486
1487 =head2 Strategies for Storing Callback Context Information
1488
1489
1490 Potentially one of the trickiest problems to overcome when designing a
1491 callback interface can be figuring out how to store the mapping between
1492 the C callback function and the Perl equivalent.
1493
1494 To help understand why this can be a real problem first consider how a
1495 callback is set up in an all C environment.  Typically a C API will
1496 provide a function to register a callback.  This will expect a pointer
1497 to a function as one of its parameters.  Below is a call to a
1498 hypothetical function C<register_fatal> which registers the C function
1499 to get called when a fatal error occurs.
1500
1501     register_fatal(cb1);
1502
1503 The single parameter C<cb1> is a pointer to a function, so you must
1504 have defined C<cb1> in your code, say something like this
1505
1506     static void
1507     cb1()
1508     {
1509         printf ("Fatal Error\n");
1510         exit(1);
1511     }
1512
1513 Now change that to call a Perl subroutine instead
1514
1515     static SV * callback = (SV*)NULL;
1516
1517     static void
1518     cb1()
1519     {
1520         dSP;
1521
1522         PUSHMARK(SP);
1523
1524         /* Call the Perl sub to process the callback */
1525         call_sv(callback, G_DISCARD);
1526     }
1527
1528
1529     void
1530     register_fatal(fn)
1531         SV *    fn
1532         CODE:
1533         /* Remember the Perl sub */
1534         if (callback == (SV*)NULL)
1535             callback = newSVsv(fn);
1536         else
1537             SvSetSV(callback, fn);
1538
1539         /* register the callback with the external library */
1540         register_fatal(cb1);
1541
1542 where the Perl equivalent of C<register_fatal> and the callback it
1543 registers, C<pcb1>, might look like this
1544
1545     # Register the sub pcb1
1546     register_fatal(\&pcb1);
1547
1548     sub pcb1
1549     {
1550         die "I'm dying...\n";
1551     }
1552
1553 The mapping between the C callback and the Perl equivalent is stored in
1554 the global variable C<callback>.
1555
1556 This will be adequate if you ever need to have only one callback
1557 registered at any time. An example could be an error handler like the
1558 code sketched out above. Remember though, repeated calls to
1559 C<register_fatal> will replace the previously registered callback
1560 function with the new one.
1561
1562 Say for example you want to interface to a library which allows asynchronous
1563 file i/o.  In this case you may be able to register a callback whenever
1564 a read operation has completed. To be of any use we want to be able to
1565 call separate Perl subroutines for each file that is opened.  As it
1566 stands, the error handler example above would not be adequate as it
1567 allows only a single callback to be defined at any time. What we
1568 require is a means of storing the mapping between the opened file and
1569 the Perl subroutine we want to be called for that file.
1570
1571 Say the i/o library has a function C<asynch_read> which associates a C
1572 function C<ProcessRead> with a file handle C<fh>--this assumes that it
1573 has also provided some routine to open the file and so obtain the file
1574 handle.
1575
1576     asynch_read(fh, ProcessRead)
1577
1578 This may expect the C I<ProcessRead> function of this form
1579
1580     void
1581     ProcessRead(fh, buffer)
1582     int fh;
1583     char *      buffer;
1584     {
1585          ...
1586     }
1587
1588 To provide a Perl interface to this library we need to be able to map
1589 between the C<fh> parameter and the Perl subroutine we want called.  A
1590 hash is a convenient mechanism for storing this mapping.  The code
1591 below shows a possible implementation
1592
1593     static HV * Mapping = (HV*)NULL;
1594
1595     void
1596     asynch_read(fh, callback)
1597         int     fh
1598         SV *    callback
1599         CODE:
1600         /* If the hash doesn't already exist, create it */
1601         if (Mapping == (HV*)NULL)
1602             Mapping = newHV();
1603
1604         /* Save the fh -> callback mapping */
1605         hv_store(Mapping, (char*)&fh, sizeof(fh), newSVsv(callback), 0);
1606
1607         /* Register with the C Library */
1608         asynch_read(fh, asynch_read_if);
1609
1610 and C<asynch_read_if> could look like this
1611
1612     static void
1613     asynch_read_if(fh, buffer)
1614     int fh;
1615     char *      buffer;
1616     {
1617         dSP;
1618         SV ** sv;
1619
1620         /* Get the callback associated with fh */
1621         sv =  hv_fetch(Mapping, (char*)&fh , sizeof(fh), FALSE);
1622         if (sv == (SV**)NULL)
1623             croak("Internal error...\n");
1624
1625         PUSHMARK(SP);
1626         EXTEND(SP, 2);
1627         PUSHs(sv_2mortal(newSViv(fh)));
1628         PUSHs(sv_2mortal(newSVpv(buffer, 0)));
1629         PUTBACK;
1630
1631         /* Call the Perl sub */
1632         call_sv(*sv, G_DISCARD);
1633     }
1634
1635 For completeness, here is C<asynch_close>.  This shows how to remove
1636 the entry from the hash C<Mapping>.
1637
1638     void
1639     asynch_close(fh)
1640         int     fh
1641         CODE:
1642         /* Remove the entry from the hash */
1643         (void) hv_delete(Mapping, (char*)&fh, sizeof(fh), G_DISCARD);
1644
1645         /* Now call the real asynch_close */
1646         asynch_close(fh);
1647
1648 So the Perl interface would look like this
1649
1650     sub callback1
1651     {
1652         my($handle, $buffer) = @_;
1653     }
1654
1655     # Register the Perl callback
1656     asynch_read($fh, \&callback1);
1657
1658     asynch_close($fh);
1659
1660 The mapping between the C callback and Perl is stored in the global
1661 hash C<Mapping> this time. Using a hash has the distinct advantage that
1662 it allows an unlimited number of callbacks to be registered.
1663
1664 What if the interface provided by the C callback doesn't contain a
1665 parameter which allows the file handle to Perl subroutine mapping?  Say
1666 in the asynchronous i/o package, the callback function gets passed only
1667 the C<buffer> parameter like this
1668
1669     void
1670     ProcessRead(buffer)
1671     char *      buffer;
1672     {
1673         ...
1674     }
1675
1676 Without the file handle there is no straightforward way to map from the
1677 C callback to the Perl subroutine.
1678
1679 In this case a possible way around this problem is to predefine a
1680 series of C functions to act as the interface to Perl, thus
1681
1682     #define MAX_CB              3
1683     #define NULL_HANDLE -1
1684     typedef void (*FnMap)();
1685
1686     struct MapStruct {
1687         FnMap    Function;
1688         SV *     PerlSub;
1689         int      Handle;
1690       };
1691
1692     static void  fn1();
1693     static void  fn2();
1694     static void  fn3();
1695
1696     static struct MapStruct Map [MAX_CB] =
1697         {
1698             { fn1, NULL, NULL_HANDLE },
1699             { fn2, NULL, NULL_HANDLE },
1700             { fn3, NULL, NULL_HANDLE }
1701         };
1702
1703     static void
1704     Pcb(index, buffer)
1705     int index;
1706     char * buffer;
1707     {
1708         dSP;
1709
1710         PUSHMARK(SP);
1711         XPUSHs(sv_2mortal(newSVpv(buffer, 0)));
1712         PUTBACK;
1713
1714         /* Call the Perl sub */
1715         call_sv(Map[index].PerlSub, G_DISCARD);
1716     }
1717
1718     static void
1719     fn1(buffer)
1720     char * buffer;
1721     {
1722         Pcb(0, buffer);
1723     }
1724
1725     static void
1726     fn2(buffer)
1727     char * buffer;
1728     {
1729         Pcb(1, buffer);
1730     }
1731
1732     static void
1733     fn3(buffer)
1734     char * buffer;
1735     {
1736         Pcb(2, buffer);
1737     }
1738
1739     void
1740     array_asynch_read(fh, callback)
1741         int             fh
1742         SV *    callback
1743         CODE:
1744         int index;
1745         int null_index = MAX_CB;
1746
1747         /* Find the same handle or an empty entry */
1748         for (index = 0; index < MAX_CB; ++index)
1749         {
1750             if (Map[index].Handle == fh)
1751                 break;
1752
1753             if (Map[index].Handle == NULL_HANDLE)
1754                 null_index = index;
1755         }
1756
1757         if (index == MAX_CB && null_index == MAX_CB)
1758             croak ("Too many callback functions registered\n");
1759
1760         if (index == MAX_CB)
1761             index = null_index;
1762
1763         /* Save the file handle */
1764         Map[index].Handle = fh;
1765
1766         /* Remember the Perl sub */
1767         if (Map[index].PerlSub == (SV*)NULL)
1768             Map[index].PerlSub = newSVsv(callback);
1769         else
1770             SvSetSV(Map[index].PerlSub, callback);
1771
1772         asynch_read(fh, Map[index].Function);
1773
1774     void
1775     array_asynch_close(fh)
1776         int     fh
1777         CODE:
1778         int index;
1779
1780         /* Find the file handle */
1781         for (index = 0; index < MAX_CB; ++ index)
1782             if (Map[index].Handle == fh)
1783                 break;
1784
1785         if (index == MAX_CB)
1786             croak ("could not close fh %d\n", fh);
1787
1788         Map[index].Handle = NULL_HANDLE;
1789         SvREFCNT_dec(Map[index].PerlSub);
1790         Map[index].PerlSub = (SV*)NULL;
1791
1792         asynch_close(fh);
1793
1794 In this case the functions C<fn1>, C<fn2>, and C<fn3> are used to
1795 remember the Perl subroutine to be called. Each of the functions holds
1796 a separate hard-wired index which is used in the function C<Pcb> to
1797 access the C<Map> array and actually call the Perl subroutine.
1798
1799 There are some obvious disadvantages with this technique.
1800
1801 Firstly, the code is considerably more complex than with the previous
1802 example.
1803
1804 Secondly, there is a hard-wired limit (in this case 3) to the number of
1805 callbacks that can exist simultaneously. The only way to increase the
1806 limit is by modifying the code to add more functions and then
1807 recompiling.  None the less, as long as the number of functions is
1808 chosen with some care, it is still a workable solution and in some
1809 cases is the only one available.
1810
1811 To summarize, here are a number of possible methods for you to consider
1812 for storing the mapping between C and the Perl callback
1813
1814 =over 5
1815
1816 =item 1. Ignore the problem - Allow only 1 callback
1817
1818 For a lot of situations, like interfacing to an error handler, this may
1819 be a perfectly adequate solution.
1820
1821 =item 2. Create a sequence of callbacks - hard wired limit
1822
1823 If it is impossible to tell from the parameters passed back from the C
1824 callback what the context is, then you may need to create a sequence of C
1825 callback interface functions, and store pointers to each in an array.
1826
1827 =item 3. Use a parameter to map to the Perl callback
1828
1829 A hash is an ideal mechanism to store the mapping between C and Perl.
1830
1831 =back
1832
1833
1834 =head2 Alternate Stack Manipulation
1835
1836
1837 Although I have made use of only the C<POP*> macros to access values
1838 returned from Perl subroutines, it is also possible to bypass these
1839 macros and read the stack using the C<ST> macro (See L<perlxs> for a
1840 full description of the C<ST> macro).
1841
1842 Most of the time the C<POP*> macros should be adequate; the main
1843 problem with them is that they force you to process the returned values
1844 in sequence. This may not be the most suitable way to process the
1845 values in some cases. What we want is to be able to access the stack in
1846 a random order. The C<ST> macro as used when coding an XSUB is ideal
1847 for this purpose.
1848
1849 The code below is the example given in the section L</Returning a List
1850 of Values> recoded to use C<ST> instead of C<POP*>.
1851
1852     static void
1853     call_AddSubtract2(a, b)
1854     int a;
1855     int b;
1856     {
1857         dSP;
1858         I32 ax;
1859         int count;
1860
1861         ENTER;
1862         SAVETMPS;
1863
1864         PUSHMARK(SP);
1865         EXTEND(SP, 2);
1866         PUSHs(sv_2mortal(newSViv(a)));
1867         PUSHs(sv_2mortal(newSViv(b)));
1868         PUTBACK;
1869
1870         count = call_pv("AddSubtract", G_ARRAY);
1871
1872         SPAGAIN;
1873         SP -= count;
1874         ax = (SP - PL_stack_base) + 1;
1875
1876         if (count != 2)
1877             croak("Big trouble\n");
1878
1879         printf ("%d + %d = %d\n", a, b, SvIV(ST(0)));
1880         printf ("%d - %d = %d\n", a, b, SvIV(ST(1)));
1881
1882         PUTBACK;
1883         FREETMPS;
1884         LEAVE;
1885     }
1886
1887 Notes
1888
1889 =over 5
1890
1891 =item 1.
1892
1893 Notice that it was necessary to define the variable C<ax>.  This is
1894 because the C<ST> macro expects it to exist.  If we were in an XSUB it
1895 would not be necessary to define C<ax> as it is already defined for
1896 us.
1897
1898 =item 2.
1899
1900 The code
1901
1902         SPAGAIN;
1903         SP -= count;
1904         ax = (SP - PL_stack_base) + 1;
1905
1906 sets the stack up so that we can use the C<ST> macro.
1907
1908 =item 3.
1909
1910 Unlike the original coding of this example, the returned
1911 values are not accessed in reverse order.  So C<ST(0)> refers to the
1912 first value returned by the Perl subroutine and C<ST(count-1)>
1913 refers to the last.
1914
1915 =back
1916
1917 =head2 Creating and Calling an Anonymous Subroutine in C
1918
1919 As we've already shown, C<call_sv> can be used to invoke an
1920 anonymous subroutine.  However, our example showed a Perl script
1921 invoking an XSUB to perform this operation.  Let's see how it can be
1922 done inside our C code:
1923
1924  ...
1925
1926  SV *cvrv
1927     = eval_pv("sub {
1928                 print 'You will not find me cluttering any namespace!'
1929                }", TRUE);
1930
1931  ...
1932
1933  call_sv(cvrv, G_VOID|G_NOARGS);
1934
1935 C<eval_pv> is used to compile the anonymous subroutine, which
1936 will be the return value as well (read more about C<eval_pv> in
1937 L<perlapi/eval_pv>).  Once this code reference is in hand, it
1938 can be mixed in with all the previous examples we've shown.
1939
1940 =head1 LIGHTWEIGHT CALLBACKS
1941
1942 Sometimes you need to invoke the same subroutine repeatedly.
1943 This usually happens with a function that acts on a list of
1944 values, such as Perl's built-in sort(). You can pass a
1945 comparison function to sort(), which will then be invoked
1946 for every pair of values that needs to be compared. The first()
1947 and reduce() functions from L<List::Util> follow a similar
1948 pattern.
1949
1950 In this case it is possible to speed up the routine (often
1951 quite substantially) by using the lightweight callback API.
1952 The idea is that the calling context only needs to be
1953 created and destroyed once, and the sub can be called
1954 arbitrarily many times in between.
1955
1956 It is usual to pass parameters using global variables (typically
1957 $_ for one parameter, or $a and $b for two parameters) rather
1958 than via @_. (It is possible to use the @_ mechanism if you know
1959 what you're doing, though there is as yet no supported API for
1960 it. It's also inherently slower.)
1961
1962 The pattern of macro calls is like this:
1963
1964     dMULTICALL;                 /* Declare local variables */
1965     U8 gimme = G_SCALAR;        /* context of the call: G_SCALAR,
1966                                  * G_ARRAY, or G_VOID */
1967
1968     PUSH_MULTICALL(cv);         /* Set up the context for calling cv,
1969                                    and set local vars appropriately */
1970
1971     /* loop */ {
1972         /* set the value(s) af your parameter variables */
1973         MULTICALL;              /* Make the actual call */
1974     } /* end of loop */
1975
1976     POP_MULTICALL;              /* Tear down the calling context */
1977
1978 For some concrete examples, see the implementation of the
1979 first() and reduce() functions of List::Util 1.18. There you
1980 will also find a header file that emulates the multicall API
1981 on older versions of perl.
1982
1983 =head1 SEE ALSO
1984
1985 L<perlxs>, L<perlguts>, L<perlembed>
1986
1987 =head1 AUTHOR
1988
1989 Paul Marquess 
1990
1991 Special thanks to the following people who assisted in the creation of
1992 the document.
1993
1994 Jeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem, Gurusamy Sarathy
1995 and Larry Wall.
1996
1997 =head1 DATE
1998
1999 Last updated for perl 5.23.1.