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