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