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