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

LIGHTWEIGHT CALLBACKS

1745       Sometimes you need to invoke the same subroutine repeatedly.  This
1746       usually happens with a function that acts on a list of values, such as
1747       Perl's built-in sort(). You can pass a comparison function to sort(),
1748       which will then be invoked for every pair of values that needs to be
1749       compared. The first() and reduce() functions from List::Util follow a
1750       similar pattern.
1751
1752       In this case it is possible to speed up the routine (often quite
1753       substantially) by using the lightweight callback API.  The idea is that
1754       the calling context only needs to be created and destroyed once, and
1755       the sub can be called arbitrarily many times in between.
1756
1757       It is usual to pass parameters using global variables (typically $_ for
1758       one parameter, or $a and $b for two parameters) rather than via @_. (It
1759       is possible to use the @_ mechanism if you know what you're doing,
1760       though there is as yet no supported API for it. It's also inherently
1761       slower.)
1762
1763       The pattern of macro calls is like this:
1764
1765           dMULTICALL;                 /* Declare local variables */
1766           U8 gimme = G_SCALAR;        /* context of the call: G_SCALAR,
1767                                        * G_ARRAY, or G_VOID */
1768
1769           PUSH_MULTICALL(cv);         /* Set up the context for calling cv,
1770                                          and set local vars appropriately */
1771
1772           /* loop */ {
1773               /* set the value(s) af your parameter variables */
1774               MULTICALL;              /* Make the actual call */
1775           } /* end of loop */
1776
1777           POP_MULTICALL;              /* Tear down the calling context */
1778
1779       For some concrete examples, see the implementation of the first() and
1780       reduce() functions of List::Util 1.18. There you will also find a
1781       header file that emulates the multicall API on older versions of perl.
1782

SEE ALSO

1784       perlxs, perlguts, perlembed
1785

AUTHOR

1787       Paul Marquess
1788
1789       Special thanks to the following people who assisted in the creation of
1790       the document.
1791
1792       Jeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem, Gurusamy Sarathy
1793       and Larry Wall.
1794

DATE

1796       Last updated for perl 5.23.1.
1797
1798
1799
1800perl v5.28.2                      2018-11-01                       PERLCALL(1)
Impressum