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