1PERLCALL(1)            Perl Programmers Reference Guide            PERLCALL(1)
2
3
4

NAME

6       perlcall - Perl calling conventions from C
7

DESCRIPTION

9       The purpose of this document is to show you how to call Perl
10       subroutines directly from C, i.e., how to write callbacks.
11
12       Apart from discussing the C interface provided by Perl for writing
13       callbacks the document uses a series of examples to show how the
14       interface actually works in practice.  In addition some techniques for
15       coding callbacks are covered.
16
17       Examples where callbacks are necessary include
18
19       ·    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
24            a C function that will be called whenever something nasty occurs.
25            What we would like is to be able to specify a Perl subroutine that
26            will be called instead.
27
28       ·    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
32            case you register functions to be called whenever specific events
33            occur, e.g., a mouse button is pressed, the cursor moves into a
34            window or a menu item is selected.
35
36       Although the techniques described here are applicable when embedding
37       Perl in a C program, this is not the primary goal of this document.
38       There are other details that must be considered and are specific to
39       embedding Perl. For details on embedding Perl in C refer to perlembed.
40
41       Before you launch yourself head first into the rest of this document,
42       it would be a good idea to have read the following two
43       documents--perlxs and perlguts.
44

THE CALL_ FUNCTIONS

46       Although this stuff is easier to explain using examples, you first need
47       be aware of a few important definitions.
48
49       Perl has a number of C functions that allow you to call Perl
50       subroutines.  They are
51
52           I32 call_sv(SV* sv, I32 flags);
53           I32 call_pv(char *subname, I32 flags);
54           I32 call_method(char *methname, I32 flags);
55           I32 call_argv(char *subname, I32 flags, register char **argv);
56
57       The key function is call_sv.  All the other functions are fairly simple
58       wrappers which make it easier to call Perl subroutines in special
59       cases. At the end of the day they will all call call_sv to invoke the
60       Perl subroutine.
61
62       All the call_* functions have a "flags" parameter which is used to pass
63       a bit mask of options to Perl.  This bit mask operates identically for
64       each of the functions.  The settings available in the bit mask are
65       discussed in "FLAG VALUES".
66
67       Each of the functions will now be discussed in turn.
68
69       call_sv
70            call_sv takes two parameters. The first, "sv", is an SV*.  This
71            allows you to specify the Perl subroutine to be called either as a
72            C string (which has first been converted to an SV) or a reference
73            to a subroutine. The section, Using call_sv, shows how you can
74            make use of call_sv.
75
76       call_pv
77            The function, call_pv, is similar to call_sv except it expects its
78            first parameter to be a C char* which identifies the Perl
79            subroutine you want to call, e.g., "call_pv("fred", 0)".  If the
80            subroutine you want to call is in another package, just include
81            the package name in the string, e.g., "pkg::fred".
82
83       call_method
84            The function call_method is used to call a method from a Perl
85            class.  The parameter "methname" corresponds to the name of the
86            method to be called.  Note that the class that the method belongs
87            to is passed on the Perl stack rather than in the parameter list.
88            This class can be either the name of the class (for a static
89            method) or a reference to an object (for a virtual method).  See
90            perlobj for more information on static and virtual methods and
91            "Using call_method" for an example of using call_method.
92
93       call_argv
94            call_argv calls the Perl subroutine specified by the C string
95            stored in the "subname" parameter. It also takes the usual "flags"
96            parameter.  The final parameter, "argv", consists of a NULL-
97            terminated list of C strings to be passed as parameters to the
98            Perl subroutine.  See Using call_argv.
99
100       All the functions return an integer. This is a count of the number of
101       items returned by the Perl subroutine. The actual items returned by the
102       subroutine are stored on the Perl stack.
103
104       As a general rule you should always check the return value from these
105       functions.  Even if you are expecting only a particular number of
106       values to be returned from the Perl subroutine, there is nothing to
107       stop someone from doing something unexpected--don't say you haven't
108       been warned.
109

FLAG VALUES

111       The "flags" parameter in all the call_* functions is one of G_VOID,
112       G_SCALAR, or G_ARRAY, which indicate the call context, OR'ed together
113       with a bit mask of any combination of the other G_* symbols defined
114       below.
115
116   G_VOID
117       Calls the Perl subroutine in a void context.
118
119       This flag has 2 effects:
120
121       1.   It indicates to the subroutine being called that it is executing
122            in a void context (if it executes wantarray the result will be the
123            undefined value).
124
125       2.   It ensures that nothing is actually returned from the subroutine.
126
127       The value returned by the call_* function indicates how many items have
128       been returned by the Perl subroutine--in this case it will be 0.
129
130   G_SCALAR
131       Calls the Perl subroutine in a scalar context.  This is the default
132       context flag setting for all the call_* functions.
133
134       This flag has 2 effects:
135
136       1.   It indicates to the subroutine being called that it is executing
137            in a scalar context (if it executes wantarray the result will be
138            false).
139
140       2.   It ensures that only a scalar is actually returned from the
141            subroutine.  The subroutine can, of course,  ignore the wantarray
142            and return a list anyway. If so, then only the last element of the
143            list will be returned.
144
145       The value returned by the call_* function indicates how many items have
146       been returned by the Perl subroutine - in this case it will be either 0
147       or 1.
148
149       If 0, then you have specified the G_DISCARD flag.
150
151       If 1, then the item actually returned by the Perl subroutine will be
152       stored on the Perl stack - the section Returning a Scalar shows how to
153       access this value on the stack.  Remember that regardless of how many
154       items the Perl subroutine returns, only the last one will be accessible
155       from the stack - think of the case where only one value is returned as
156       being a list with only one element.  Any other items that were returned
157       will not exist by the time control returns from the call_* function.
158       The section Returning a list in a scalar context shows an example of
159       this behavior.
160
161   G_ARRAY
162       Calls the Perl subroutine in a list context.
163
164       As with G_SCALAR, this flag has 2 effects:
165
166       1.   It indicates to the subroutine being called that it is executing
167            in a list context (if it executes wantarray the result will be
168            true).
169
170       2.   It ensures that all items returned from the subroutine will be
171            accessible when control returns from the call_* function.
172
173       The value returned by the call_* function indicates how many items have
174       been returned by the Perl subroutine.
175
176       If 0, then you have specified the G_DISCARD flag.
177
178       If not 0, then it will be a count of the number of items returned by
179       the subroutine. These items will be stored on the Perl stack.  The
180       section Returning a list of values gives an example of using the
181       G_ARRAY flag and the mechanics of accessing the returned items from the
182       Perl stack.
183
184   G_DISCARD
185       By default, the call_* functions place the items returned from by the
186       Perl subroutine on the stack.  If you are not interested in these
187       items, then setting this flag will make Perl get rid of them
188       automatically for you.  Note that it is still possible to indicate a
189       context to the Perl subroutine by using either G_SCALAR or G_ARRAY.
190
191       If you do not set this flag then it is very important that you make
192       sure that any temporaries (i.e., parameters passed to the Perl
193       subroutine and values returned from the subroutine) are disposed of
194       yourself.  The section Returning a Scalar gives details of how to
195       dispose of these temporaries explicitly and the section Using Perl to
196       dispose of temporaries discusses the specific circumstances where you
197       can ignore the problem and let Perl deal with it for you.
198
199   G_NOARGS
200       Whenever a Perl subroutine is called using one of the call_* functions,
201       it is assumed by default that parameters are to be passed to the
202       subroutine.  If you are not passing any parameters to the Perl
203       subroutine, you can save a bit of time by setting this flag.  It has
204       the effect of not creating the @_ array for the Perl subroutine.
205
206       Although the functionality provided by this flag may seem
207       straightforward, it should be used only if there is a good reason to do
208       so.  The reason for being cautious is that, even if you have specified
209       the G_NOARGS flag, it is still possible for the Perl subroutine that
210       has been called to think that you have passed it parameters.
211
212       In fact, what can happen is that the Perl subroutine you have called
213       can access the @_ array from a previous Perl subroutine.  This will
214       occur when the code that is executing the call_* function has itself
215       been called from another Perl subroutine. The code below illustrates
216       this
217
218           sub fred
219             { print "@_\n"  }
220
221           sub joe
222             { &fred }
223
224           &joe(1,2,3);
225
226       This will print
227
228           1 2 3
229
230       What has happened is that "fred" accesses the @_ array which belongs to
231       "joe".
232
233   G_EVAL
234       It is possible for the Perl subroutine you are calling to terminate
235       abnormally, e.g., by calling die explicitly or by not actually
236       existing.  By default, when either of these events occurs, the process
237       will terminate immediately.  If you want to trap this type of event,
238       specify the G_EVAL flag.  It will put an eval { } around the subroutine
239       call.
240
241       Whenever control returns from the call_* function you need to check the
242       $@ variable as you would in a normal Perl script.
243
244       The value returned from the call_* function is dependent on what other
245       flags have been specified and whether an error has occurred.  Here are
246       all the different cases that can occur:
247
248       ·    If the call_* function returns normally, then the value returned
249            is as specified in the previous sections.
250
251       ·    If G_DISCARD is specified, the return value will always be 0.
252
253       ·    If G_ARRAY is specified and an error has occurred, the return
254            value will always be 0.
255
256       ·    If G_SCALAR is specified and an error has occurred, the return
257            value will be 1 and the value on the top of the stack will be
258            undef. This means that if you have already detected the error by
259            checking $@ and you want the program to continue, you must
260            remember to pop the undef from the stack.
261
262       See Using G_EVAL for details on using G_EVAL.
263
264   G_KEEPERR
265       Using the G_EVAL flag described above will always set $@: clearing it
266       if there was no error, and setting it to describe the error if there
267       was an error in the called code.  This is what you want if your
268       intention is to handle possible errors, but sometimes you just want to
269       trap errors and stop them interfering with the rest of the program.
270
271       This scenario will mostly be applicable to code that is meant to be
272       called from within destructors, asynchronous callbacks, and signal
273       handlers.  In such situations, where the code being called has little
274       relation to the surrounding dynamic context, the main program needs to
275       be insulated from errors in the called code, even if they can't be
276       handled intelligently.  It may also be useful to do this with code for
277       "__DIE__" or "__WARN__" hooks, and "tie" functions.
278
279       The G_KEEPERR flag is meant to be used in conjunction with G_EVAL in
280       call_* functions that are used to implement such code, or with
281       "eval_sv".  This flag has no effect on the "call_*" functions when
282       G_EVAL is not used.
283
284       When G_KEEPERR is used, any error in the called code will terminate the
285       call as usual, and the error will not propagate beyond the call (as
286       usual for G_EVAL), but it will not go into $@.  Instead the error will
287       be converted into a warning, prefixed with the string "\t(in cleanup)".
288       This can be disabled using "no warnings 'misc'".  If there is no error,
289       $@ will not be cleared.
290
291       Note that the G_KEEPERR flag does not propagate into inner evals; these
292       may still set $@.
293
294       The G_KEEPERR flag was introduced in Perl version 5.002.
295
296       See Using G_KEEPERR for an example of a situation that warrants the use
297       of this flag.
298
299   Determining the Context
300       As mentioned above, you can determine the context of the currently
301       executing subroutine in Perl with wantarray.  The equivalent test can
302       be made in C by using the "GIMME_V" macro, which returns "G_ARRAY" if
303       you have been called in a list context, "G_SCALAR" if in a scalar
304       context, or "G_VOID" if in a void context (i.e., the return value will
305       not be used).  An older version of this macro is called "GIMME"; in a
306       void context it returns "G_SCALAR" instead of "G_VOID".  An example of
307       using the "GIMME_V" macro is shown in section Using GIMME_V.
308

EXAMPLES

310       Enough of the definition talk! Let's have a few examples.
311
312       Perl provides many macros to assist in accessing the Perl stack.
313       Wherever possible, these macros should always be used when interfacing
314       to Perl internals.  We hope this should make the code less vulnerable
315       to any changes made to Perl in the future.
316
317       Another point worth noting is that in the first series of examples I
318       have made use of only the call_pv function.  This has been done to keep
319       the code simpler and ease you into the topic.  Wherever possible, if
320       the choice is between using call_pv and call_sv, you should always try
321       to use call_sv.  See Using call_sv for details.
322
323   No Parameters, Nothing Returned
324       This first trivial example will call a Perl subroutine, PrintUID, to
325       print out the UID of the process.
326
327           sub PrintUID
328           {
329               print "UID is $<\n";
330           }
331
332       and here is a C function to call it
333
334           static void
335           call_PrintUID()
336           {
337               dSP;
338
339               PUSHMARK(SP);
340               call_pv("PrintUID", G_DISCARD|G_NOARGS);
341           }
342
343       Simple, eh?
344
345       A few points to note about this example:
346
347       1.   Ignore "dSP" and "PUSHMARK(SP)" for now. They will be discussed in
348            the next example.
349
350       2.   We aren't passing any parameters to PrintUID so G_NOARGS can be
351            specified.
352
353       3.   We aren't interested in anything returned from PrintUID, so
354            G_DISCARD is specified. Even if PrintUID was changed to return
355            some value(s), having specified G_DISCARD will mean that they will
356            be wiped by the time control returns from call_pv.
357
358       4.   As call_pv is being used, the Perl subroutine is specified as a C
359            string. In this case the subroutine name has been 'hard-wired'
360            into the code.
361
362       5.   Because we specified G_DISCARD, it is not necessary to check the
363            value returned from call_pv. It will always be 0.
364
365   Passing Parameters
366       Now let's make a slightly more complex example. This time we want to
367       call a Perl subroutine, "LeftString", which will take 2 parameters--a
368       string ($s) and an integer ($n).  The subroutine will simply print the
369       first $n characters of the string.
370
371       So the Perl subroutine would look like this:
372
373           sub LeftString
374           {
375               my($s, $n) = @_;
376               print substr($s, 0, $n), "\n";
377           }
378
379       The C function required to call LeftString would look like this:
380
381           static void
382           call_LeftString(a, b)
383           char * a;
384           int b;
385           {
386               dSP;
387
388               ENTER;
389               SAVETMPS;
390
391               PUSHMARK(SP);
392               XPUSHs(sv_2mortal(newSVpv(a, 0)));
393               XPUSHs(sv_2mortal(newSViv(b)));
394               PUTBACK;
395
396               call_pv("LeftString", G_DISCARD);
397
398               FREETMPS;
399               LEAVE;
400           }
401
402       Here are a few notes on the C function call_LeftString.
403
404       1.   Parameters are passed to the Perl subroutine using the Perl stack.
405            This is the purpose of the code beginning with the line "dSP" and
406            ending with the line "PUTBACK".  The "dSP" declares a local copy
407            of the stack pointer.  This local copy should always be accessed
408            as "SP".
409
410       2.   If you are going to put something onto the Perl stack, you need to
411            know where to put it. This is the purpose of the macro "dSP"--it
412            declares and initializes a local copy of the Perl stack pointer.
413
414            All the other macros which will be used in this example require
415            you to have used this macro.
416
417            The exception to this rule is if you are calling a Perl subroutine
418            directly from an XSUB function. In this case it is not necessary
419            to use the "dSP" macro explicitly--it will be declared for you
420            automatically.
421
422       3.   Any parameters to be pushed onto the stack should be bracketed by
423            the "PUSHMARK" and "PUTBACK" macros.  The purpose of these two
424            macros, in this context, is to count the number of parameters you
425            are pushing automatically.  Then whenever Perl is creating the @_
426            array for the subroutine, it knows how big to make it.
427
428            The "PUSHMARK" macro tells Perl to make a mental note of the
429            current stack pointer. Even if you aren't passing any parameters
430            (like the example shown in the section No Parameters, Nothing
431            Returned) you must still call the "PUSHMARK" macro before you can
432            call any of the call_* functions--Perl still needs to know that
433            there are no parameters.
434
435            The "PUTBACK" macro sets the global copy of the stack pointer to
436            be the same as our local copy. If we didn't do this, call_pv
437            wouldn't know where the two parameters we pushed were--remember
438            that up to now all the stack pointer manipulation we have done is
439            with our local copy, not the global copy.
440
441       4.   Next, we come to XPUSHs. This is where the parameters actually get
442            pushed onto the stack. In this case we are pushing a string and an
443            integer.
444
445            See "XSUBs and the Argument Stack" in perlguts for details on how
446            the XPUSH macros work.
447
448       5.   Because we created temporary values (by means of sv_2mortal()
449            calls) we will have to tidy up the Perl stack and dispose of
450            mortal SVs.
451
452            This is the purpose of
453
454                ENTER;
455                SAVETMPS;
456
457            at the start of the function, and
458
459                FREETMPS;
460                LEAVE;
461
462            at the end. The "ENTER"/"SAVETMPS" pair creates a boundary for any
463            temporaries we create.  This means that the temporaries we get rid
464            of will be limited to those which were created after these calls.
465
466            The "FREETMPS"/"LEAVE" pair will get rid of any values returned by
467            the Perl subroutine (see next example), plus it will also dump the
468            mortal SVs we have created.  Having "ENTER"/"SAVETMPS" at the
469            beginning of the code makes sure that no other mortals are
470            destroyed.
471
472            Think of these macros as working a bit like "{" and "}" in Perl to
473            limit the scope of local variables.
474
475            See the section Using Perl to Dispose of Temporaries for details
476            of an alternative to using these macros.
477
478       6.   Finally, LeftString can now be called via the call_pv function.
479            The only flag specified this time is G_DISCARD. Because we are
480            passing 2 parameters to the Perl subroutine this time, we have not
481            specified G_NOARGS.
482
483   Returning a Scalar
484       Now for an example of dealing with the items returned from a Perl
485       subroutine.
486
487       Here is a Perl subroutine, Adder, that takes 2 integer parameters and
488       simply returns their sum.
489
490           sub Adder
491           {
492               my($a, $b) = @_;
493               $a + $b;
494           }
495
496       Because we are now concerned with the return value from Adder, the C
497       function required to call it is now a bit more complex.
498
499           static void
500           call_Adder(a, b)
501           int a;
502           int b;
503           {
504               dSP;
505               int count;
506
507               ENTER;
508               SAVETMPS;
509
510               PUSHMARK(SP);
511               XPUSHs(sv_2mortal(newSViv(a)));
512               XPUSHs(sv_2mortal(newSViv(b)));
513               PUTBACK;
514
515               count = call_pv("Adder", G_SCALAR);
516
517               SPAGAIN;
518
519               if (count != 1)
520                   croak("Big trouble\n");
521
522               printf ("The sum of %d and %d is %d\n", a, b, POPi);
523
524               PUTBACK;
525               FREETMPS;
526               LEAVE;
527           }
528
529       Points to note this time are
530
531       1.   The only flag specified this time was G_SCALAR. That means that
532            the @_ array will be created and that the value returned by Adder
533            will still exist after the call to call_pv.
534
535       2.   The purpose of the macro "SPAGAIN" is to refresh the local copy of
536            the stack pointer. This is necessary because it is possible that
537            the memory allocated to the Perl stack has been reallocated during
538            the call_pv call.
539
540            If you are making use of the Perl stack pointer in your code you
541            must always refresh the local copy using SPAGAIN whenever you make
542            use of the call_* functions or any other Perl internal function.
543
544       3.   Although only a single value was expected to be returned from
545            Adder, it is still good practice to check the return code from
546            call_pv anyway.
547
548            Expecting a single value is not quite the same as knowing that
549            there will be one. If someone modified Adder to return a list and
550            we didn't check for that possibility and take appropriate action
551            the Perl stack would end up in an inconsistent state. That is
552            something you really don't want to happen ever.
553
554       4.   The "POPi" macro is used here to pop the return value from the
555            stack.  In this case we wanted an integer, so "POPi" was used.
556
557            Here is the complete list of POP macros available, along with the
558            types they return.
559
560                POPs        SV
561                POPp        pointer
562                POPn        double
563                POPi        integer
564                POPl        long
565
566       5.   The final "PUTBACK" is used to leave the Perl stack in a
567            consistent state before exiting the function.  This is necessary
568            because when we popped the return value from the stack with "POPi"
569            it updated only our local copy of the stack pointer.  Remember,
570            "PUTBACK" sets the global stack pointer to be the same as our
571            local copy.
572
573   Returning a List of Values
574       Now, let's extend the previous example to return both the sum of the
575       parameters and the difference.
576
577       Here is the Perl subroutine
578
579           sub AddSubtract
580           {
581              my($a, $b) = @_;
582              ($a+$b, $a-$b);
583           }
584
585       and this is the C function
586
587           static void
588           call_AddSubtract(a, b)
589           int a;
590           int b;
591           {
592               dSP;
593               int count;
594
595               ENTER;
596               SAVETMPS;
597
598               PUSHMARK(SP);
599               XPUSHs(sv_2mortal(newSViv(a)));
600               XPUSHs(sv_2mortal(newSViv(b)));
601               PUTBACK;
602
603               count = call_pv("AddSubtract", G_ARRAY);
604
605               SPAGAIN;
606
607               if (count != 2)
608                   croak("Big trouble\n");
609
610               printf ("%d - %d = %d\n", a, b, POPi);
611               printf ("%d + %d = %d\n", a, b, POPi);
612
613               PUTBACK;
614               FREETMPS;
615               LEAVE;
616           }
617
618       If call_AddSubtract is called like this
619
620           call_AddSubtract(7, 4);
621
622       then here is the output
623
624           7 - 4 = 3
625           7 + 4 = 11
626
627       Notes
628
629       1.   We wanted list context, so G_ARRAY was used.
630
631       2.   Not surprisingly "POPi" is used twice this time because we were
632            retrieving 2 values from the stack. The important thing to note is
633            that when using the "POP*" macros they come off the stack in
634            reverse order.
635
636   Returning a List in a Scalar Context
637       Say the Perl subroutine in the previous section was called in a scalar
638       context, like this
639
640           static void
641           call_AddSubScalar(a, b)
642           int a;
643           int b;
644           {
645               dSP;
646               int count;
647               int i;
648
649               ENTER;
650               SAVETMPS;
651
652               PUSHMARK(SP);
653               XPUSHs(sv_2mortal(newSViv(a)));
654               XPUSHs(sv_2mortal(newSViv(b)));
655               PUTBACK;
656
657               count = call_pv("AddSubtract", G_SCALAR);
658
659               SPAGAIN;
660
661               printf ("Items Returned = %d\n", count);
662
663               for (i = 1; i <= count; ++i)
664                   printf ("Value %d = %d\n", i, POPi);
665
666               PUTBACK;
667               FREETMPS;
668               LEAVE;
669           }
670
671       The other modification made is that call_AddSubScalar will print the
672       number of items returned from the Perl subroutine and their value (for
673       simplicity it assumes that they are integer).  So if call_AddSubScalar
674       is called
675
676           call_AddSubScalar(7, 4);
677
678       then the output will be
679
680           Items Returned = 1
681           Value 1 = 3
682
683       In this case the main point to note is that only the last item in the
684       list is returned from the subroutine. AddSubtract actually made it back
685       to call_AddSubScalar.
686
687   Returning Data from Perl via the Parameter List
688       It is also possible to return values directly via the parameter
689       list--whether it is actually desirable to do it is another matter
690       entirely.
691
692       The Perl subroutine, Inc, below takes 2 parameters and increments each
693       directly.
694
695           sub Inc
696           {
697               ++ $_[0];
698               ++ $_[1];
699           }
700
701       and here is a C function to call it.
702
703           static void
704           call_Inc(a, b)
705           int a;
706           int b;
707           {
708               dSP;
709               int count;
710               SV * sva;
711               SV * svb;
712
713               ENTER;
714               SAVETMPS;
715
716               sva = sv_2mortal(newSViv(a));
717               svb = sv_2mortal(newSViv(b));
718
719               PUSHMARK(SP);
720               XPUSHs(sva);
721               XPUSHs(svb);
722               PUTBACK;
723
724               count = call_pv("Inc", G_DISCARD);
725
726               if (count != 0)
727                   croak ("call_Inc: expected 0 values from 'Inc', got %d\n",
728                          count);
729
730               printf ("%d + 1 = %d\n", a, SvIV(sva));
731               printf ("%d + 1 = %d\n", b, SvIV(svb));
732
733               FREETMPS;
734               LEAVE;
735           }
736
737       To be able to access the two parameters that were pushed onto the stack
738       after they return from call_pv it is necessary to make a note of their
739       addresses--thus the two variables "sva" and "svb".
740
741       The reason this is necessary is that the area of the Perl stack which
742       held them will very likely have been overwritten by something else by
743       the time control returns from call_pv.
744
745   Using G_EVAL
746       Now an example using G_EVAL. Below is a Perl subroutine which computes
747       the difference of its 2 parameters. If this would result in a negative
748       result, the subroutine calls die.
749
750           sub Subtract
751           {
752               my ($a, $b) = @_;
753
754               die "death can be fatal\n" if $a < $b;
755
756               $a - $b;
757           }
758
759       and some C to call it
760
761           static void
762           call_Subtract(a, b)
763           int a;
764           int b;
765           {
766               dSP;
767               int count;
768
769               ENTER;
770               SAVETMPS;
771
772               PUSHMARK(SP);
773               XPUSHs(sv_2mortal(newSViv(a)));
774               XPUSHs(sv_2mortal(newSViv(b)));
775               PUTBACK;
776
777               count = call_pv("Subtract", G_EVAL|G_SCALAR);
778
779               SPAGAIN;
780
781               /* Check the eval first */
782               if (SvTRUE(ERRSV))
783               {
784                   printf ("Uh oh - %s\n", SvPV_nolen(ERRSV));
785                   POPs;
786               }
787               else
788               {
789                   if (count != 1)
790                      croak("call_Subtract: wanted 1 value from 'Subtract', got %d\n",
791                               count);
792
793                   printf ("%d - %d = %d\n", a, b, POPi);
794               }
795
796               PUTBACK;
797               FREETMPS;
798               LEAVE;
799           }
800
801       If call_Subtract is called thus
802
803           call_Subtract(4, 5)
804
805       the following will be printed
806
807           Uh oh - death can be fatal
808
809       Notes
810
811       1.   We want to be able to catch the die so we have used the G_EVAL
812            flag.  Not specifying this flag would mean that the program would
813            terminate immediately at the die statement in the subroutine
814            Subtract.
815
816       2.   The code
817
818                if (SvTRUE(ERRSV))
819                {
820                    printf ("Uh oh - %s\n", SvPV_nolen(ERRSV));
821                    POPs;
822                }
823
824            is the direct equivalent of this bit of Perl
825
826                print "Uh oh - $@\n" if $@;
827
828            "PL_errgv" is a perl global of type "GV *" that points to the
829            symbol table entry containing the error.  "ERRSV" therefore refers
830            to the C equivalent of $@.
831
832       3.   Note that the stack is popped using "POPs" in the block where
833            "SvTRUE(ERRSV)" is true.  This is necessary because whenever a
834            call_* function invoked with G_EVAL|G_SCALAR returns an error, the
835            top of the stack holds the value undef. Because we want the
836            program to continue after detecting this error, it is essential
837            that the stack be tidied up by removing the undef.
838
839   Using G_KEEPERR
840       Consider this rather facetious example, where we have used an XS
841       version of the call_Subtract example above inside a destructor:
842
843           package Foo;
844           sub new { bless {}, $_[0] }
845           sub Subtract {
846               my($a,$b) = @_;
847               die "death can be fatal" if $a < $b;
848               $a - $b;
849           }
850           sub DESTROY { call_Subtract(5, 4); }
851           sub foo { die "foo dies"; }
852
853           package main;
854           {
855               my $foo = Foo->new;
856               eval { $foo->foo };
857           }
858           print "Saw: $@" if $@;             # should be, but isn't
859
860       This example will fail to recognize that an error occurred inside the
861       "eval {}".  Here's why: the call_Subtract code got executed while perl
862       was cleaning up temporaries when exiting the outer braced block, and
863       because call_Subtract is implemented with call_pv using the G_EVAL
864       flag, it promptly reset $@.  This results in the failure of the
865       outermost test for $@, and thereby the failure of the error trap.
866
867       Appending the G_KEEPERR flag, so that the call_pv call in call_Subtract
868       reads:
869
870               count = call_pv("Subtract", G_EVAL|G_SCALAR|G_KEEPERR);
871
872       will preserve the error and restore reliable error handling.
873
874   Using call_sv
875       In all the previous examples I have 'hard-wired' the name of the Perl
876       subroutine to be called from C.  Most of the time though, it is more
877       convenient to be able to specify the name of the Perl subroutine from
878       within the Perl script.
879
880       Consider the Perl code below
881
882           sub fred
883           {
884               print "Hello there\n";
885           }
886
887           CallSubPV("fred");
888
889       Here is a snippet of XSUB which defines CallSubPV.
890
891           void
892           CallSubPV(name)
893               char *  name
894               CODE:
895               PUSHMARK(SP);
896               call_pv(name, G_DISCARD|G_NOARGS);
897
898       That is fine as far as it goes. The thing is, the Perl subroutine can
899       be specified as only a string.  For Perl 4 this was adequate, but Perl
900       5 allows references to subroutines and anonymous subroutines.  This is
901       where call_sv is useful.
902
903       The code below for CallSubSV is identical to CallSubPV except that the
904       "name" parameter is now defined as an SV* and we use call_sv instead of
905       call_pv.
906
907           void
908           CallSubSV(name)
909               SV *    name
910               CODE:
911               PUSHMARK(SP);
912               call_sv(name, G_DISCARD|G_NOARGS);
913
914       Because we are using an SV to call fred the following can all be used:
915
916           CallSubSV("fred");
917           CallSubSV(\&fred);
918           $ref = \&fred;
919           CallSubSV($ref);
920           CallSubSV( sub { print "Hello there\n" } );
921
922       As you can see, call_sv gives you much greater flexibility in how you
923       can specify the Perl subroutine.
924
925       You should note that, if it is necessary to store the SV ("name" in the
926       example above) which corresponds to the Perl subroutine so that it can
927       be used later in the program, it not enough just to store a copy of the
928       pointer to the SV. Say the code above had been like this:
929
930           static SV * rememberSub;
931
932           void
933           SaveSub1(name)
934               SV *    name
935               CODE:
936               rememberSub = name;
937
938           void
939           CallSavedSub1()
940               CODE:
941               PUSHMARK(SP);
942               call_sv(rememberSub, G_DISCARD|G_NOARGS);
943
944       The reason this is wrong is that, by the time you come to use the
945       pointer "rememberSub" in "CallSavedSub1", it may or may not still refer
946       to the Perl subroutine that was recorded in "SaveSub1".  This is
947       particularly true for these cases:
948
949           SaveSub1(\&fred);
950           CallSavedSub1();
951
952           SaveSub1( sub { print "Hello there\n" } );
953           CallSavedSub1();
954
955       By the time each of the "SaveSub1" statements above has been executed,
956       the SV*s which corresponded to the parameters will no longer exist.
957       Expect an error message from Perl of the form
958
959           Can't use an undefined value as a subroutine reference at ...
960
961       for each of the "CallSavedSub1" lines.
962
963       Similarly, with this code
964
965           $ref = \&fred;
966           SaveSub1($ref);
967           $ref = 47;
968           CallSavedSub1();
969
970       you can expect one of these messages (which you actually get is
971       dependent on the version of Perl you are using)
972
973           Not a CODE reference at ...
974           Undefined subroutine &main::47 called ...
975
976       The variable $ref may have referred to the subroutine "fred" whenever
977       the call to "SaveSub1" was made but by the time "CallSavedSub1" gets
978       called it now holds the number 47. Because we saved only a pointer to
979       the original SV in "SaveSub1", any changes to $ref will be tracked by
980       the pointer "rememberSub". This means that whenever "CallSavedSub1"
981       gets called, it will attempt to execute the code which is referenced by
982       the SV* "rememberSub".  In this case though, it now refers to the
983       integer 47, so expect Perl to complain loudly.
984
985       A similar but more subtle problem is illustrated with this code:
986
987           $ref = \&fred;
988           SaveSub1($ref);
989           $ref = \&joe;
990           CallSavedSub1();
991
992       This time whenever "CallSavedSub1" gets called it will execute the Perl
993       subroutine "joe" (assuming it exists) rather than "fred" as was
994       originally requested in the call to "SaveSub1".
995
996       To get around these problems it is necessary to take a full copy of the
997       SV.  The code below shows "SaveSub2" modified to do that.
998
999           static SV * keepSub = (SV*)NULL;
1000
1001           void
1002           SaveSub2(name)
1003               SV *    name
1004               CODE:
1005               /* Take a copy of the callback */
1006               if (keepSub == (SV*)NULL)
1007                   /* First time, so create a new SV */
1008                   keepSub = newSVsv(name);
1009               else
1010                   /* Been here before, so overwrite */
1011                   SvSetSV(keepSub, name);
1012
1013           void
1014           CallSavedSub2()
1015               CODE:
1016               PUSHMARK(SP);
1017               call_sv(keepSub, G_DISCARD|G_NOARGS);
1018
1019       To avoid creating a new SV every time "SaveSub2" is called, the
1020       function first checks to see if it has been called before.  If not,
1021       then space for a new SV is allocated and the reference to the Perl
1022       subroutine "name" is copied to the variable "keepSub" in one operation
1023       using "newSVsv".  Thereafter, whenever "SaveSub2" is called, the
1024       existing SV, "keepSub", is overwritten with the new value using
1025       "SvSetSV".
1026
1027   Using call_argv
1028       Here is a Perl subroutine which prints whatever parameters are passed
1029       to it.
1030
1031           sub PrintList
1032           {
1033               my(@list) = @_;
1034
1035               foreach (@list) { print "$_\n" }
1036           }
1037
1038       And here is an example of call_argv which will call PrintList.
1039
1040           static char * words[] = {"alpha", "beta", "gamma", "delta", NULL};
1041
1042           static void
1043           call_PrintList()
1044           {
1045               dSP;
1046
1047               call_argv("PrintList", G_DISCARD, words);
1048           }
1049
1050       Note that it is not necessary to call "PUSHMARK" in this instance.
1051       This is because call_argv will do it for you.
1052
1053   Using call_method
1054       Consider the following Perl code:
1055
1056           {
1057               package Mine;
1058
1059               sub new
1060               {
1061                   my($type) = shift;
1062                   bless [@_]
1063               }
1064
1065               sub Display
1066               {
1067                   my ($self, $index) = @_;
1068                   print "$index: $$self[$index]\n";
1069               }
1070
1071               sub PrintID
1072               {
1073                   my($class) = @_;
1074                   print "This is Class $class version 1.0\n";
1075               }
1076           }
1077
1078       It implements just a very simple class to manage an array.  Apart from
1079       the constructor, "new", it declares methods, one static and one
1080       virtual. The static method, "PrintID", prints out simply the class name
1081       and a version number. The virtual method, "Display", prints out a
1082       single element of the array.  Here is an all-Perl example of using it.
1083
1084           $a = Mine->new('red', 'green', 'blue');
1085           $a->Display(1);
1086           Mine->PrintID;
1087
1088       will print
1089
1090           1: green
1091           This is Class Mine version 1.0
1092
1093       Calling a Perl method from C is fairly straightforward. The following
1094       things are required:
1095
1096       ·    A reference to the object for a virtual method or the name of the
1097            class for a static method
1098
1099       ·    The name of the method
1100
1101       ·    Any other parameters specific to the method
1102
1103       Here is a simple XSUB which illustrates the mechanics of calling both
1104       the "PrintID" and "Display" methods from C.
1105
1106           void
1107           call_Method(ref, method, index)
1108               SV *    ref
1109               char *  method
1110               int             index
1111               CODE:
1112               PUSHMARK(SP);
1113               XPUSHs(ref);
1114               XPUSHs(sv_2mortal(newSViv(index)));
1115               PUTBACK;
1116
1117               call_method(method, G_DISCARD);
1118
1119           void
1120           call_PrintID(class, method)
1121               char *  class
1122               char *  method
1123               CODE:
1124               PUSHMARK(SP);
1125               XPUSHs(sv_2mortal(newSVpv(class, 0)));
1126               PUTBACK;
1127
1128               call_method(method, G_DISCARD);
1129
1130       So the methods "PrintID" and "Display" can be invoked like this:
1131
1132           $a = Mine->new('red', 'green', 'blue');
1133           call_Method($a, 'Display', 1);
1134           call_PrintID('Mine', 'PrintID');
1135
1136       The only thing to note is that, in both the static and virtual methods,
1137       the method name is not passed via the stack--it is used as the first
1138       parameter to call_method.
1139
1140   Using GIMME_V
1141       Here is a trivial XSUB which prints the context in which it is
1142       currently executing.
1143
1144           void
1145           PrintContext()
1146               CODE:
1147               I32 gimme = GIMME_V;
1148               if (gimme == G_VOID)
1149                   printf ("Context is Void\n");
1150               else if (gimme == G_SCALAR)
1151                   printf ("Context is Scalar\n");
1152               else
1153                   printf ("Context is Array\n");
1154
1155       And here is some Perl to test it.
1156
1157           PrintContext;
1158           $a = PrintContext;
1159           @a = PrintContext;
1160
1161       The output from that will be
1162
1163           Context is Void
1164           Context is Scalar
1165           Context is Array
1166
1167   Using Perl to Dispose of Temporaries
1168       In the examples given to date, any temporaries created in the callback
1169       (i.e., parameters passed on the stack to the call_* function or values
1170       returned via the stack) have been freed by one of these methods:
1171
1172       ·    Specifying the G_DISCARD flag with call_*
1173
1174       ·    Explicitly using the "ENTER"/"SAVETMPS"--"FREETMPS"/"LEAVE"
1175            pairing
1176
1177       There is another method which can be used, namely letting Perl do it
1178       for you automatically whenever it regains control after the callback
1179       has terminated.  This is done by simply not using the
1180
1181           ENTER;
1182           SAVETMPS;
1183           ...
1184           FREETMPS;
1185           LEAVE;
1186
1187       sequence in the callback (and not, of course, specifying the G_DISCARD
1188       flag).
1189
1190       If you are going to use this method you have to be aware of a possible
1191       memory leak which can arise under very specific circumstances.  To
1192       explain these circumstances you need to know a bit about the flow of
1193       control between Perl and the callback routine.
1194
1195       The examples given at the start of the document (an error handler and
1196       an event driven program) are typical of the two main sorts of flow
1197       control that you are likely to encounter with callbacks.  There is a
1198       very important distinction between them, so pay attention.
1199
1200       In the first example, an error handler, the flow of control could be as
1201       follows.  You have created an interface to an external library.
1202       Control can reach the external library like this
1203
1204           perl --> XSUB --> external library
1205
1206       Whilst control is in the library, an error condition occurs. You have
1207       previously set up a Perl callback to handle this situation, so it will
1208       get executed. Once the callback has finished, control will drop back to
1209       Perl again.  Here is what the flow of control will be like in that
1210       situation
1211
1212           perl --> XSUB --> external library
1213                             ...
1214                             error occurs
1215                             ...
1216                             external library --> call_* --> perl
1217                                                                 |
1218           perl <-- XSUB <-- external library <-- call_* <----+
1219
1220       After processing of the error using call_* is completed, control
1221       reverts back to Perl more or less immediately.
1222
1223       In the diagram, the further right you go the more deeply nested the
1224       scope is.  It is only when control is back with perl on the extreme
1225       left of the diagram that you will have dropped back to the enclosing
1226       scope and any temporaries you have left hanging around will be freed.
1227
1228       In the second example, an event driven program, the flow of control
1229       will be more like this
1230
1231           perl --> XSUB --> event handler
1232                             ...
1233                             event handler --> call_* --> perl
1234                                                              |
1235                             event handler <-- call_* <----+
1236                             ...
1237                             event handler --> call_* --> perl
1238                                                              |
1239                             event handler <-- call_* <----+
1240                             ...
1241                             event handler --> call_* --> perl
1242                                                              |
1243                             event handler <-- call_* <----+
1244
1245       In this case the flow of control can consist of only the repeated
1246       sequence
1247
1248           event handler --> call_* --> perl
1249
1250       for practically the complete duration of the program.  This means that
1251       control may never drop back to the surrounding scope in Perl at the
1252       extreme left.
1253
1254       So what is the big problem? Well, if you are expecting Perl to tidy up
1255       those temporaries for you, you might be in for a long wait.  For Perl
1256       to dispose of your temporaries, control must drop back to the enclosing
1257       scope at some stage.  In the event driven scenario that may never
1258       happen.  This means that, as time goes on, your program will create
1259       more and more temporaries, none of which will ever be freed. As each of
1260       these temporaries consumes some memory your program will eventually
1261       consume all the available memory in your system--kapow!
1262
1263       So here is the bottom line--if you are sure that control will revert
1264       back to the enclosing Perl scope fairly quickly after the end of your
1265       callback, then it isn't absolutely necessary to dispose explicitly of
1266       any temporaries you may have created. Mind you, if you are at all
1267       uncertain about what to do, it doesn't do any harm to tidy up anyway.
1268
1269   Strategies for Storing Callback Context Information
1270       Potentially one of the trickiest problems to overcome when designing a
1271       callback interface can be figuring out how to store the mapping between
1272       the C callback function and the Perl equivalent.
1273
1274       To help understand why this can be a real problem first consider how a
1275       callback is set up in an all C environment.  Typically a C API will
1276       provide a function to register a callback.  This will expect a pointer
1277       to a function as one of its parameters.  Below is a call to a
1278       hypothetical function "register_fatal" which registers the C function
1279       to get called when a fatal error occurs.
1280
1281           register_fatal(cb1);
1282
1283       The single parameter "cb1" is a pointer to a function, so you must have
1284       defined "cb1" in your code, say something like this
1285
1286           static void
1287           cb1()
1288           {
1289               printf ("Fatal Error\n");
1290               exit(1);
1291           }
1292
1293       Now change that to call a Perl subroutine instead
1294
1295           static SV * callback = (SV*)NULL;
1296
1297           static void
1298           cb1()
1299           {
1300               dSP;
1301
1302               PUSHMARK(SP);
1303
1304               /* Call the Perl sub to process the callback */
1305               call_sv(callback, G_DISCARD);
1306           }
1307
1308
1309           void
1310           register_fatal(fn)
1311               SV *    fn
1312               CODE:
1313               /* Remember the Perl sub */
1314               if (callback == (SV*)NULL)
1315                   callback = newSVsv(fn);
1316               else
1317                   SvSetSV(callback, fn);
1318
1319               /* register the callback with the external library */
1320               register_fatal(cb1);
1321
1322       where the Perl equivalent of "register_fatal" and the callback it
1323       registers, "pcb1", might look like this
1324
1325           # Register the sub pcb1
1326           register_fatal(\&pcb1);
1327
1328           sub pcb1
1329           {
1330               die "I'm dying...\n";
1331           }
1332
1333       The mapping between the C callback and the Perl equivalent is stored in
1334       the global variable "callback".
1335
1336       This will be adequate if you ever need to have only one callback
1337       registered at any time. An example could be an error handler like the
1338       code sketched out above. Remember though, repeated calls to
1339       "register_fatal" will replace the previously registered callback
1340       function with the new one.
1341
1342       Say for example you want to interface to a library which allows
1343       asynchronous file i/o.  In this case you may be able to register a
1344       callback whenever a read operation has completed. To be of any use we
1345       want to be able to call separate Perl subroutines for each file that is
1346       opened.  As it stands, the error handler example above would not be
1347       adequate as it allows only a single callback to be defined at any time.
1348       What we require is a means of storing the mapping between the opened
1349       file and the Perl subroutine we want to be called for that file.
1350
1351       Say the i/o library has a function "asynch_read" which associates a C
1352       function "ProcessRead" with a file handle "fh"--this assumes that it
1353       has also provided some routine to open the file and so obtain the file
1354       handle.
1355
1356           asynch_read(fh, ProcessRead)
1357
1358       This may expect the C ProcessRead function of this form
1359
1360           void
1361           ProcessRead(fh, buffer)
1362           int fh;
1363           char *      buffer;
1364           {
1365                ...
1366           }
1367
1368       To provide a Perl interface to this library we need to be able to map
1369       between the "fh" parameter and the Perl subroutine we want called.  A
1370       hash is a convenient mechanism for storing this mapping.  The code
1371       below shows a possible implementation
1372
1373           static HV * Mapping = (HV*)NULL;
1374
1375           void
1376           asynch_read(fh, callback)
1377               int     fh
1378               SV *    callback
1379               CODE:
1380               /* If the hash doesn't already exist, create it */
1381               if (Mapping == (HV*)NULL)
1382                   Mapping = newHV();
1383
1384               /* Save the fh -> callback mapping */
1385               hv_store(Mapping, (char*)&fh, sizeof(fh), newSVsv(callback), 0);
1386
1387               /* Register with the C Library */
1388               asynch_read(fh, asynch_read_if);
1389
1390       and "asynch_read_if" could look like this
1391
1392           static void
1393           asynch_read_if(fh, buffer)
1394           int fh;
1395           char *      buffer;
1396           {
1397               dSP;
1398               SV ** sv;
1399
1400               /* Get the callback associated with fh */
1401               sv =  hv_fetch(Mapping, (char*)&fh , sizeof(fh), FALSE);
1402               if (sv == (SV**)NULL)
1403                   croak("Internal error...\n");
1404
1405               PUSHMARK(SP);
1406               XPUSHs(sv_2mortal(newSViv(fh)));
1407               XPUSHs(sv_2mortal(newSVpv(buffer, 0)));
1408               PUTBACK;
1409
1410               /* Call the Perl sub */
1411               call_sv(*sv, G_DISCARD);
1412           }
1413
1414       For completeness, here is "asynch_close".  This shows how to remove the
1415       entry from the hash "Mapping".
1416
1417           void
1418           asynch_close(fh)
1419               int     fh
1420               CODE:
1421               /* Remove the entry from the hash */
1422               (void) hv_delete(Mapping, (char*)&fh, sizeof(fh), G_DISCARD);
1423
1424               /* Now call the real asynch_close */
1425               asynch_close(fh);
1426
1427       So the Perl interface would look like this
1428
1429           sub callback1
1430           {
1431               my($handle, $buffer) = @_;
1432           }
1433
1434           # Register the Perl callback
1435           asynch_read($fh, \&callback1);
1436
1437           asynch_close($fh);
1438
1439       The mapping between the C callback and Perl is stored in the global
1440       hash "Mapping" this time. Using a hash has the distinct advantage that
1441       it allows an unlimited number of callbacks to be registered.
1442
1443       What if the interface provided by the C callback doesn't contain a
1444       parameter which allows the file handle to Perl subroutine mapping?  Say
1445       in the asynchronous i/o package, the callback function gets passed only
1446       the "buffer" parameter like this
1447
1448           void
1449           ProcessRead(buffer)
1450           char *      buffer;
1451           {
1452               ...
1453           }
1454
1455       Without the file handle there is no straightforward way to map from the
1456       C callback to the Perl subroutine.
1457
1458       In this case a possible way around this problem is to predefine a
1459       series of C functions to act as the interface to Perl, thus
1460
1461           #define MAX_CB              3
1462           #define NULL_HANDLE -1
1463           typedef void (*FnMap)();
1464
1465           struct MapStruct {
1466               FnMap    Function;
1467               SV *     PerlSub;
1468               int      Handle;
1469             };
1470
1471           static void  fn1();
1472           static void  fn2();
1473           static void  fn3();
1474
1475           static struct MapStruct Map [MAX_CB] =
1476               {
1477                   { fn1, NULL, NULL_HANDLE },
1478                   { fn2, NULL, NULL_HANDLE },
1479                   { fn3, NULL, NULL_HANDLE }
1480               };
1481
1482           static void
1483           Pcb(index, buffer)
1484           int index;
1485           char * buffer;
1486           {
1487               dSP;
1488
1489               PUSHMARK(SP);
1490               XPUSHs(sv_2mortal(newSVpv(buffer, 0)));
1491               PUTBACK;
1492
1493               /* Call the Perl sub */
1494               call_sv(Map[index].PerlSub, G_DISCARD);
1495           }
1496
1497           static void
1498           fn1(buffer)
1499           char * buffer;
1500           {
1501               Pcb(0, buffer);
1502           }
1503
1504           static void
1505           fn2(buffer)
1506           char * buffer;
1507           {
1508               Pcb(1, buffer);
1509           }
1510
1511           static void
1512           fn3(buffer)
1513           char * buffer;
1514           {
1515               Pcb(2, buffer);
1516           }
1517
1518           void
1519           array_asynch_read(fh, callback)
1520               int             fh
1521               SV *    callback
1522               CODE:
1523               int index;
1524               int null_index = MAX_CB;
1525
1526               /* Find the same handle or an empty entry */
1527               for (index = 0; index < MAX_CB; ++index)
1528               {
1529                   if (Map[index].Handle == fh)
1530                       break;
1531
1532                   if (Map[index].Handle == NULL_HANDLE)
1533                       null_index = index;
1534               }
1535
1536               if (index == MAX_CB && null_index == MAX_CB)
1537                   croak ("Too many callback functions registered\n");
1538
1539               if (index == MAX_CB)
1540                   index = null_index;
1541
1542               /* Save the file handle */
1543               Map[index].Handle = fh;
1544
1545               /* Remember the Perl sub */
1546               if (Map[index].PerlSub == (SV*)NULL)
1547                   Map[index].PerlSub = newSVsv(callback);
1548               else
1549                   SvSetSV(Map[index].PerlSub, callback);
1550
1551               asynch_read(fh, Map[index].Function);
1552
1553           void
1554           array_asynch_close(fh)
1555               int     fh
1556               CODE:
1557               int index;
1558
1559               /* Find the file handle */
1560               for (index = 0; index < MAX_CB; ++ index)
1561                   if (Map[index].Handle == fh)
1562                       break;
1563
1564               if (index == MAX_CB)
1565                   croak ("could not close fh %d\n", fh);
1566
1567               Map[index].Handle = NULL_HANDLE;
1568               SvREFCNT_dec(Map[index].PerlSub);
1569               Map[index].PerlSub = (SV*)NULL;
1570
1571               asynch_close(fh);
1572
1573       In this case the functions "fn1", "fn2", and "fn3" are used to remember
1574       the Perl subroutine to be called. Each of the functions holds a
1575       separate hard-wired index which is used in the function "Pcb" to access
1576       the "Map" array and actually call the Perl subroutine.
1577
1578       There are some obvious disadvantages with this technique.
1579
1580       Firstly, the code is considerably more complex than with the previous
1581       example.
1582
1583       Secondly, there is a hard-wired limit (in this case 3) to the number of
1584       callbacks that can exist simultaneously. The only way to increase the
1585       limit is by modifying the code to add more functions and then
1586       recompiling.  None the less, as long as the number of functions is
1587       chosen with some care, it is still a workable solution and in some
1588       cases is the only one available.
1589
1590       To summarize, here are a number of possible methods for you to consider
1591       for storing the mapping between C and the Perl callback
1592
1593       1. Ignore the problem - Allow only 1 callback
1594            For a lot of situations, like interfacing to an error handler,
1595            this may be a perfectly adequate solution.
1596
1597       2. Create a sequence of callbacks - hard wired limit
1598            If it is impossible to tell from the parameters passed back from
1599            the C callback what the context is, then you may need to create a
1600            sequence of C callback interface functions, and store pointers to
1601            each in an array.
1602
1603       3. Use a parameter to map to the Perl callback
1604            A hash is an ideal mechanism to store the mapping between C and
1605            Perl.
1606
1607   Alternate Stack Manipulation
1608       Although I have made use of only the "POP*" macros to access values
1609       returned from Perl subroutines, it is also possible to bypass these
1610       macros and read the stack using the "ST" macro (See perlxs for a full
1611       description of the "ST" macro).
1612
1613       Most of the time the "POP*" macros should be adequate; the main problem
1614       with them is that they force you to process the returned values in
1615       sequence. This may not be the most suitable way to process the values
1616       in some cases. What we want is to be able to access the stack in a
1617       random order. The "ST" macro as used when coding an XSUB is ideal for
1618       this purpose.
1619
1620       The code below is the example given in the section Returning a List of
1621       Values recoded to use "ST" instead of "POP*".
1622
1623           static void
1624           call_AddSubtract2(a, b)
1625           int a;
1626           int b;
1627           {
1628               dSP;
1629               I32 ax;
1630               int count;
1631
1632               ENTER;
1633               SAVETMPS;
1634
1635               PUSHMARK(SP);
1636               XPUSHs(sv_2mortal(newSViv(a)));
1637               XPUSHs(sv_2mortal(newSViv(b)));
1638               PUTBACK;
1639
1640               count = call_pv("AddSubtract", G_ARRAY);
1641
1642               SPAGAIN;
1643               SP -= count;
1644               ax = (SP - PL_stack_base) + 1;
1645
1646               if (count != 2)
1647                   croak("Big trouble\n");
1648
1649               printf ("%d + %d = %d\n", a, b, SvIV(ST(0)));
1650               printf ("%d - %d = %d\n", a, b, SvIV(ST(1)));
1651
1652               PUTBACK;
1653               FREETMPS;
1654               LEAVE;
1655           }
1656
1657       Notes
1658
1659       1.   Notice that it was necessary to define the variable "ax".  This is
1660            because the "ST" macro expects it to exist.  If we were in an XSUB
1661            it would not be necessary to define "ax" as it is already defined
1662            for us.
1663
1664       2.   The code
1665
1666                    SPAGAIN;
1667                    SP -= count;
1668                    ax = (SP - PL_stack_base) + 1;
1669
1670            sets the stack up so that we can use the "ST" macro.
1671
1672       3.   Unlike the original coding of this example, the returned values
1673            are not accessed in reverse order.  So ST(0) refers to the first
1674            value returned by the Perl subroutine and "ST(count-1)" refers to
1675            the last.
1676
1677   Creating and Calling an Anonymous Subroutine in C
1678       As we've already shown, "call_sv" can be used to invoke an anonymous
1679       subroutine.  However, our example showed a Perl script invoking an XSUB
1680       to perform this operation.  Let's see how it can be done inside our C
1681       code:
1682
1683        ...
1684
1685        SV *cvrv = eval_pv("sub { print 'You will not find me cluttering any namespace!' }", TRUE);
1686
1687        ...
1688
1689        call_sv(cvrv, G_VOID|G_NOARGS);
1690
1691       "eval_pv" is used to compile the anonymous subroutine, which will be
1692       the return value as well (read more about "eval_pv" in "eval_pv" in
1693       perlapi).  Once this code reference is in hand, it can be mixed in with
1694       all the previous examples we've shown.
1695

LIGHTWEIGHT CALLBACKS

1697       Sometimes you need to invoke the same subroutine repeatedly.  This
1698       usually happens with a function that acts on a list of values, such as
1699       Perl's built-in sort(). You can pass a comparison function to sort(),
1700       which will then be invoked for every pair of values that needs to be
1701       compared. The first() and reduce() functions from List::Util follow a
1702       similar pattern.
1703
1704       In this case it is possible to speed up the routine (often quite
1705       substantially) by using the lightweight callback API.  The idea is that
1706       the calling context only needs to be created and destroyed once, and
1707       the sub can be called arbitrarily many times in between.
1708
1709       It is usual to pass parameters using global variables (typically $_ for
1710       one parameter, or $a and $b for two parameters) rather than via @_. (It
1711       is possible to use the @_ mechanism if you know what you're doing,
1712       though there is as yet no supported API for it. It's also inherently
1713       slower.)
1714
1715       The pattern of macro calls is like this:
1716
1717           dMULTICALL;                 /* Declare local variables */
1718           I32 gimme = G_SCALAR;       /* context of the call: G_SCALAR,
1719                                        * G_ARRAY, or G_VOID */
1720
1721           PUSH_MULTICALL(cv);         /* Set up the context for calling cv,
1722                                          and set local vars appropriately */
1723
1724           /* loop */ {
1725               /* set the value(s) af your parameter variables */
1726               MULTICALL;              /* Make the actual call */
1727           } /* end of loop */
1728
1729           POP_MULTICALL;              /* Tear down the calling context */
1730
1731       For some concrete examples, see the implementation of the first() and
1732       reduce() functions of List::Util 1.18. There you will also find a
1733       header file that emulates the multicall API on older versions of perl.
1734

SEE ALSO

1736       perlxs, perlguts, perlembed
1737

AUTHOR

1739       Paul Marquess
1740
1741       Special thanks to the following people who assisted in the creation of
1742       the document.
1743
1744       Jeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem, Gurusamy Sarathy
1745       and Larry Wall.
1746

DATE

1748       Version 1.3, 14th Apr 1997
1749
1750
1751
1752perl v5.16.3                      2013-03-04                       PERLCALL(1)
Impressum