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 subrou‐
10       tines 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 inter‐
14       face actually works in practice.  In addition some techniques for cod‐
15       ing callbacks are covered.
16
17       Examples where callbacks are necessary include
18
19       * An Error Handler
20            You have created an XSUB interface to an application's C API.
21
22            A fairly common feature in applications is to allow you to define
23            a C function that will be called whenever something nasty occurs.
24            What we would like is to be able to specify a Perl subroutine that
25            will be called instead.
26
27       * An Event Driven Program
28            The classic example of where callbacks are used is when writing an
29            event driven program like for an X windows application.  In this
30            case you register functions to be called whenever specific events
31            occur, e.g., a mouse button is pressed, the cursor moves into a
32            window or a menu item is selected.
33
34       Although the techniques described here are applicable when embedding
35       Perl in a C program, this is not the primary goal of this document.
36       There are other details that must be considered and are specific to
37       embedding Perl. For details on embedding Perl in C refer to perlembed.
38
39       Before you launch yourself head first into the rest of this document,
40       it would be a good idea to have read the following two documents - per‐
41       lxs and perlguts.
42

THE CALL_ FUNCTIONS

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

FLAG VALUES

109       The "flags" parameter in all the call_* functions is a bit mask which
110       can consist of any combination of the symbols defined below, OR'ed
111       together.
112
113       G_VOID
114
115       Calls the Perl subroutine in a void context.
116
117       This flag has 2 effects:
118
119       1.   It indicates to the subroutine being called that it is executing
120            in a void context (if it executes wantarray the result will be the
121            undefined value).
122
123       2.   It ensures that nothing is actually returned from the subroutine.
124
125       The value returned by the call_* function indicates how many items have
126       been returned by the Perl subroutine - in this case it will be 0.
127
128       G_SCALAR
129
130       Calls the Perl subroutine in a scalar context.  This is the default
131       context flag setting for all the call_* functions.
132
133       This flag has 2 effects:
134
135       1.   It indicates to the subroutine being called that it is executing
136            in a scalar context (if it executes wantarray the result will be
137            false).
138
139       2.   It ensures that only a scalar is actually returned from the sub‐
140            routine.  The subroutine can, of course,  ignore the wantarray and
141            return a list anyway. If so, then only the last element of the
142            list will be returned.
143
144       The value returned by the call_* function indicates how many items have
145       been returned by the Perl subroutine - in this case it will be either 0
146       or 1.
147
148       If 0, then you have specified the G_DISCARD flag.
149
150       If 1, then the item actually returned by the Perl subroutine will be
151       stored on the Perl stack - the section Returning a Scalar shows how to
152       access this value on the stack.  Remember that regardless of how many
153       items the Perl subroutine returns, only the last one will be accessible
154       from the stack - think of the case where only one value is returned as
155       being a list with only one element.  Any other items that were returned
156       will not exist by the time control returns from the call_* function.
157       The section Returning a list in a scalar context shows an example of
158       this behavior.
159
160       G_ARRAY
161
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 sec‐
180       tion Returning a list of values gives an example of using the G_ARRAY
181       flag and the mechanics of accessing the returned items from the Perl
182       stack.
183
184       G_DISCARD
185
186       By default, the call_* functions place the items returned from by the
187       Perl subroutine on the stack.  If you are not interested in these
188       items, then setting this flag will make Perl get rid of them automati‐
189       cally for you.  Note that it is still possible to indicate a context to
190       the Perl subroutine by using either G_SCALAR or G_ARRAY.
191
192       If you do not set this flag then it is very important that you make
193       sure that any temporaries (i.e., parameters passed to the Perl subrou‐
194       tine and values returned from the subroutine) are disposed of yourself.
195       The section Returning a Scalar gives details of how to dispose of these
196       temporaries explicitly and the section Using Perl to dispose of tempo‐
197       raries discusses the specific circumstances where you can ignore the
198       problem and let Perl deal with it for you.
199
200       G_NOARGS
201
202       Whenever a Perl subroutine is called using one of the call_* functions,
203       it is assumed by default that parameters are to be passed to the sub‐
204       routine.  If you are not passing any parameters to the Perl subroutine,
205       you can save a bit of time by setting this flag.  It has the effect of
206       not creating the @_ array for the Perl subroutine.
207
208       Although the functionality provided by this flag may seem straightfor‐
209       ward, it should be used only if there is a good reason to do so.  The
210       reason for being cautious is that even if you have specified the
211       G_NOARGS flag, it is still possible for the Perl subroutine that has
212       been called to think that you have passed it parameters.
213
214       In fact, what can happen is that the Perl subroutine you have called
215       can access the @_ array from a previous Perl subroutine.  This will
216       occur when the code that is executing the call_* function has itself
217       been called from another Perl subroutine. The code below illustrates
218       this
219
220           sub fred
221             { print "@_\n"  }
222
223           sub joe
224             { &fred }
225
226           &joe(1,2,3);
227
228       This will print
229
230           1 2 3
231
232       What has happened is that "fred" accesses the @_ array which belongs to
233       "joe".
234
235       G_EVAL
236
237       It is possible for the Perl subroutine you are calling to terminate
238       abnormally, e.g., by calling die explicitly or by not actually exist‐
239       ing.  By default, when either of these events occurs, the process will
240       terminate immediately.  If you want to trap this type of event, specify
241       the G_EVAL flag.  It will put an eval { } around the subroutine call.
242
243       Whenever control returns from the call_* function you need to check the
244       $@ variable as you would in a normal Perl script.
245
246       The value returned from the call_* function is dependent on what other
247       flags have been specified and whether an error has occurred.  Here are
248       all the different cases that can occur:
249
250       ·    If the call_* function returns normally, then the value returned
251            is as specified in the previous sections.
252
253       ·    If G_DISCARD is specified, the return value will always be 0.
254
255       ·    If G_ARRAY is specified and an error has occurred, the return
256            value will always be 0.
257
258       ·    If G_SCALAR is specified and an error has occurred, the return
259            value will be 1 and the value on the top of the stack will be
260            undef. This means that if you have already detected the error by
261            checking $@ and you want the program to continue, you must remem‐
262            ber to pop the undef from the stack.
263
264       See Using G_EVAL for details on using G_EVAL.
265
266       G_KEEPERR
267
268       You may have noticed that using the G_EVAL flag described above will
269       always clear the $@ variable and set it to a string describing the
270       error iff there was an error in the called code.  This unqualified
271       resetting of $@ can be problematic in the reliable identification of
272       errors using the "eval {}" mechanism, because the possibility exists
273       that perl will call other code (end of block processing code, for exam‐
274       ple) between the time the error causes $@ to be set within "eval {}",
275       and the subsequent statement which checks for the value of $@ gets exe‐
276       cuted in the user's script.
277
278       This scenario will mostly be applicable to code that is meant to be
279       called from within destructors, asynchronous callbacks, signal han‐
280       dlers, "__DIE__" or "__WARN__" hooks, and "tie" functions.  In such
281       situations, you will not want to clear $@ at all, but simply to append
282       any new errors to any existing value of $@.
283
284       The G_KEEPERR flag is meant to be used in conjunction with G_EVAL in
285       call_* functions that are used to implement such code.  This flag has
286       no effect when G_EVAL is not used.
287
288       When G_KEEPERR is used, any errors in the called code will be prefixed
289       with the string "\t(in cleanup)", and appended to the current value of
290       $@.  an error will not be appended if that same error string is already
291       at the end of $@.
292
293       In addition, a warning is generated using the appended string. This can
294       be disabled using "no warnings 'misc'".
295
296       The G_KEEPERR flag was introduced in Perl version 5.002.
297
298       See Using G_KEEPERR for an example of a situation that warrants the use
299       of this flag.
300
301       Determining the Context
302
303       As mentioned above, you can determine the context of the currently exe‐
304       cuting subroutine in Perl with wantarray.  The equivalent test can be
305       made in C by using the "GIMME_V" macro, which returns "G_ARRAY" if you
306       have been called in a list context, "G_SCALAR" if in a scalar context,
307       or "G_VOID" if in a void context (i.e. the return value will not be
308       used).  An older version of this macro is called "GIMME"; in a void
309       context it returns "G_SCALAR" instead of "G_VOID".  An example of using
310       the "GIMME_V" macro is shown in section Using GIMME_V.
311

EXAMPLES

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

SEE ALSO

1712       perlxs, perlguts, perlembed
1713

AUTHOR

1715       Paul Marquess
1716
1717       Special thanks to the following people who assisted in the creation of
1718       the document.
1719
1720       Jeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem, Gurusamy Sarathy
1721       and Larry Wall.
1722

DATE

1724       Version 1.3, 14th Apr 1997
1725
1726
1727
1728perl v5.8.8                       2006-01-07                       PERLCALL(1)
Impressum