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