Debian Codegraph @

upstream/mageia-cauldron/man1/perlcall.1

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