Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / perl-5.8.0 / man / man1 / perlcall.1
CommitLineData
86530b38
AT
1.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
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 "2002-06-08" "perl v5.8.0" "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 "\(bu 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 "\(bu 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.
423.PP
424The G_KEEPERR flag was introduced in Perl version 5.002.
425.PP
426See \fIUsing G_KEEPERR\fR for an example of a situation that warrants the
427use of this flag.
428.Sh "Determining the Context"
429.IX Subsection "Determining the Context"
430As mentioned above, you can determine the context of the currently
431executing subroutine in Perl with \fIwantarray\fR. The equivalent test
432can be made in C by using the \f(CW\*(C`GIMME_V\*(C'\fR macro, which returns
433\&\f(CW\*(C`G_ARRAY\*(C'\fR if you have been called in a list context, \f(CW\*(C`G_SCALAR\*(C'\fR if
434in a scalar context, or \f(CW\*(C`G_VOID\*(C'\fR if in a void context (i.e. the
435return value will not be used). An older version of this macro is
436called \f(CW\*(C`GIMME\*(C'\fR; in a void context it returns \f(CW\*(C`G_SCALAR\*(C'\fR instead of
437\&\f(CW\*(C`G_VOID\*(C'\fR. An example of using the \f(CW\*(C`GIMME_V\*(C'\fR macro is shown in
438section \fIUsing \s-1GIMME_V\s0\fR.
439.SH "KNOWN PROBLEMS"
440.IX Header "KNOWN PROBLEMS"
441This section outlines all known problems that exist in the
442\&\fIcall_*\fR functions.
443.IP "1." 5
444If you are intending to make use of both the G_EVAL and G_SCALAR flags
445in your code, use a version of Perl greater than 5.000. There is a bug
446in version 5.000 of Perl which means that the combination of these two
447flags will not work as described in the section \fI\s-1FLAG\s0 \s-1VALUES\s0\fR.
448.Sp
449Specifically, if the two flags are used when calling a subroutine and
450that subroutine does not call \fIdie\fR, the value returned by
451\&\fIcall_*\fR will be wrong.
452.IP "2." 5
453In Perl 5.000 and 5.001 there is a problem with using \fIcall_*\fR if
454the Perl sub you are calling attempts to trap a \fIdie\fR.
455.Sp
456The symptom of this problem is that the called Perl sub will continue
457to completion, but whenever it attempts to pass control back to the
458\&\s-1XSUB\s0, the program will immediately terminate.
459.Sp
460For example, say you want to call this Perl sub
461.Sp
462.Vb 6
463\& sub fred
464\& {
465\& eval { die "Fatal Error" ; }
466\& print "Trapped error: $@\en"
467\& if $@ ;
468\& }
469.Ve
470.Sp
471via this \s-1XSUB\s0
472.Sp
473.Vb 6
474\& void
475\& Call_fred()
476\& CODE:
477\& PUSHMARK(SP) ;
478\& call_pv("fred", G_DISCARD|G_NOARGS) ;
479\& fprintf(stderr, "back in Call_fred\en") ;
480.Ve
481.Sp
482When \f(CW\*(C`Call_fred\*(C'\fR is executed it will print
483.Sp
484.Vb 1
485\& Trapped error: Fatal Error
486.Ve
487.Sp
488As control never returns to \f(CW\*(C`Call_fred\*(C'\fR, the \f(CW"back in Call_fred"\fR
489string will not get printed.
490.Sp
491To work around this problem, you can either upgrade to Perl 5.002 or
492higher, or use the G_EVAL flag with \fIcall_*\fR as shown below
493.Sp
494.Vb 6
495\& void
496\& Call_fred()
497\& CODE:
498\& PUSHMARK(SP) ;
499\& call_pv("fred", G_EVAL|G_DISCARD|G_NOARGS) ;
500\& fprintf(stderr, "back in Call_fred\en") ;
501.Ve
502.SH "EXAMPLES"
503.IX Header "EXAMPLES"
504Enough of the definition talk, let's have a few examples.
505.PP
506Perl provides many macros to assist in accessing the Perl stack.
507Wherever possible, these macros should always be used when interfacing
508to Perl internals. We hope this should make the code less vulnerable
509to any changes made to Perl in the future.
510.PP
511Another point worth noting is that in the first series of examples I
512have made use of only the \fIcall_pv\fR function. This has been done
513to keep the code simpler and ease you into the topic. Wherever
514possible, if the choice is between using \fIcall_pv\fR and
515\&\fIcall_sv\fR, you should always try to use \fIcall_sv\fR. See
516\&\fIUsing call_sv\fR for details.
517.Sh "No Parameters, Nothing returned"
518.IX Subsection "No Parameters, Nothing returned"
519This first trivial example will call a Perl subroutine, \fIPrintUID\fR, to
520print out the \s-1UID\s0 of the process.
521.PP
522.Vb 4
523\& sub PrintUID
524\& {
525\& print "UID is $<\en" ;
526\& }
527.Ve
528.PP
529and here is a C function to call it
530.PP
531.Vb 4
532\& static void
533\& call_PrintUID()
534\& {
535\& dSP ;
536.Ve
537.PP
538.Vb 3
539\& PUSHMARK(SP) ;
540\& call_pv("PrintUID", G_DISCARD|G_NOARGS) ;
541\& }
542.Ve
543.PP
544Simple, eh.
545.PP
546A few points to note about this example.
547.IP "1." 5
548Ignore \f(CW\*(C`dSP\*(C'\fR and \f(CW\*(C`PUSHMARK(SP)\*(C'\fR for now. They will be discussed in
549the next example.
550.IP "2." 5
551We aren't passing any parameters to \fIPrintUID\fR so G_NOARGS can be
552specified.
553.IP "3." 5
554We aren't interested in anything returned from \fIPrintUID\fR, so
555G_DISCARD is specified. Even if \fIPrintUID\fR was changed to
556return some value(s), having specified G_DISCARD will mean that they
557will be wiped by the time control returns from \fIcall_pv\fR.
558.IP "4." 5
559As \fIcall_pv\fR is being used, the Perl subroutine is specified as a
560C string. In this case the subroutine name has been 'hard\-wired' into the
561code.
562.IP "5." 5
563Because we specified G_DISCARD, it is not necessary to check the value
564returned from \fIcall_pv\fR. It will always be 0.
565.Sh "Passing Parameters"
566.IX Subsection "Passing Parameters"
567Now let's make a slightly more complex example. This time we want to
568call a Perl subroutine, \f(CW\*(C`LeftString\*(C'\fR, which will take 2 parameters\*(--a
569string ($s) and an integer ($n). The subroutine will simply
570print the first \f(CW$n\fR characters of the string.
571.PP
572So the Perl subroutine would look like this
573.PP
574.Vb 5
575\& sub LeftString
576\& {
577\& my($s, $n) = @_ ;
578\& print substr($s, 0, $n), "\en" ;
579\& }
580.Ve
581.PP
582The C function required to call \fILeftString\fR would look like this.
583.PP
584.Vb 6
585\& static void
586\& call_LeftString(a, b)
587\& char * a ;
588\& int b ;
589\& {
590\& dSP ;
591.Ve
592.PP
593.Vb 2
594\& ENTER ;
595\& SAVETMPS ;
596.Ve
597.PP
598.Vb 4
599\& PUSHMARK(SP) ;
600\& XPUSHs(sv_2mortal(newSVpv(a, 0)));
601\& XPUSHs(sv_2mortal(newSViv(b)));
602\& PUTBACK ;
603.Ve
604.PP
605.Vb 1
606\& call_pv("LeftString", G_DISCARD);
607.Ve
608.PP
609.Vb 3
610\& FREETMPS ;
611\& LEAVE ;
612\& }
613.Ve
614.PP
615Here are a few notes on the C function \fIcall_LeftString\fR.
616.IP "1." 5
617Parameters are passed to the Perl subroutine using the Perl stack.
618This is the purpose of the code beginning with the line \f(CW\*(C`dSP\*(C'\fR and
619ending with the line \f(CW\*(C`PUTBACK\*(C'\fR. The \f(CW\*(C`dSP\*(C'\fR declares a local copy
620of the stack pointer. This local copy should \fBalways\fR be accessed
621as \f(CW\*(C`SP\*(C'\fR.
622.IP "2." 5
623If you are going to put something onto the Perl stack, you need to know
624where to put it. This is the purpose of the macro \f(CW\*(C`dSP\*(C'\fR\-\-it declares
625and initializes a \fIlocal\fR copy of the Perl stack pointer.
626.Sp
627All the other macros which will be used in this example require you to
628have used this macro.
629.Sp
630The exception to this rule is if you are calling a Perl subroutine
631directly from an \s-1XSUB\s0 function. In this case it is not necessary to
632use the \f(CW\*(C`dSP\*(C'\fR macro explicitly\*(--it will be declared for you
633automatically.
634.IP "3." 5
635Any parameters to be pushed onto the stack should be bracketed by the
636\&\f(CW\*(C`PUSHMARK\*(C'\fR and \f(CW\*(C`PUTBACK\*(C'\fR macros. The purpose of these two macros, in
637this context, is to count the number of parameters you are
638pushing automatically. Then whenever Perl is creating the \f(CW@_\fR array for the
639subroutine, it knows how big to make it.
640.Sp
641The \f(CW\*(C`PUSHMARK\*(C'\fR macro tells Perl to make a mental note of the current
642stack pointer. Even if you aren't passing any parameters (like the
643example shown in the section \fINo Parameters, Nothing returned\fR) you
644must still call the \f(CW\*(C`PUSHMARK\*(C'\fR macro before you can call any of the
645\&\fIcall_*\fR functions\*(--Perl still needs to know that there are no
646parameters.
647.Sp
648The \f(CW\*(C`PUTBACK\*(C'\fR macro sets the global copy of the stack pointer to be
649the same as our local copy. If we didn't do this \fIcall_pv\fR
650wouldn't know where the two parameters we pushed were\*(--remember that
651up to now all the stack pointer manipulation we have done is with our
652local copy, \fInot\fR the global copy.
653.IP "4." 5
654Next, we come to XPUSHs. This is where the parameters actually get
655pushed onto the stack. In this case we are pushing a string and an
656integer.
657.Sp
658See \*(L"XSUBs and the Argument Stack\*(R" in perlguts for details
659on how the \s-1XPUSH\s0 macros work.
660.IP "5." 5
661Because we created temporary values (by means of \fIsv_2mortal()\fR calls)
662we will have to tidy up the Perl stack and dispose of mortal SVs.
663.Sp
664This is the purpose of
665.Sp
666.Vb 2
667\& ENTER ;
668\& SAVETMPS ;
669.Ve
670.Sp
671at the start of the function, and
672.Sp
673.Vb 2
674\& FREETMPS ;
675\& LEAVE ;
676.Ve
677.Sp
678at the end. The \f(CW\*(C`ENTER\*(C'\fR/\f(CW\*(C`SAVETMPS\*(C'\fR pair creates a boundary for any
679temporaries we create. This means that the temporaries we get rid of
680will be limited to those which were created after these calls.
681.Sp
682The \f(CW\*(C`FREETMPS\*(C'\fR/\f(CW\*(C`LEAVE\*(C'\fR pair will get rid of any values returned by
683the Perl subroutine (see next example), plus it will also dump the
684mortal SVs we have created. Having \f(CW\*(C`ENTER\*(C'\fR/\f(CW\*(C`SAVETMPS\*(C'\fR at the
685beginning of the code makes sure that no other mortals are destroyed.
686.Sp
687Think of these macros as working a bit like using \f(CW\*(C`{\*(C'\fR and \f(CW\*(C`}\*(C'\fR in Perl
688to limit the scope of local variables.
689.Sp
690See the section \fIUsing Perl to dispose of temporaries\fR for details of
691an alternative to using these macros.
692.IP "6." 5
693Finally, \fILeftString\fR can now be called via the \fIcall_pv\fR function.
694The only flag specified this time is G_DISCARD. Because we are passing
6952 parameters to the Perl subroutine this time, we have not specified
696G_NOARGS.
697.Sh "Returning a Scalar"
698.IX Subsection "Returning a Scalar"
699Now for an example of dealing with the items returned from a Perl
700subroutine.
701.PP
702Here is a Perl subroutine, \fIAdder\fR, that takes 2 integer parameters
703and simply returns their sum.
704.PP
705.Vb 5
706\& sub Adder
707\& {
708\& my($a, $b) = @_ ;
709\& $a + $b ;
710\& }
711.Ve
712.PP
713Because we are now concerned with the return value from \fIAdder\fR, the C
714function required to call it is now a bit more complex.
715.PP
716.Vb 7
717\& static void
718\& call_Adder(a, b)
719\& int a ;
720\& int b ;
721\& {
722\& dSP ;
723\& int count ;
724.Ve
725.PP
726.Vb 2
727\& ENTER ;
728\& SAVETMPS;
729.Ve
730.PP
731.Vb 4
732\& PUSHMARK(SP) ;
733\& XPUSHs(sv_2mortal(newSViv(a)));
734\& XPUSHs(sv_2mortal(newSViv(b)));
735\& PUTBACK ;
736.Ve
737.PP
738.Vb 1
739\& count = call_pv("Adder", G_SCALAR);
740.Ve
741.PP
742.Vb 1
743\& SPAGAIN ;
744.Ve
745.PP
746.Vb 2
747\& if (count != 1)
748\& croak("Big trouble\en") ;
749.Ve
750.PP
751.Vb 1
752\& printf ("The sum of %d and %d is %d\en", a, b, POPi) ;
753.Ve
754.PP
755.Vb 4
756\& PUTBACK ;
757\& FREETMPS ;
758\& LEAVE ;
759\& }
760.Ve
761.PP
762Points to note this time are
763.IP "1." 5
764The only flag specified this time was G_SCALAR. That means the \f(CW@_\fR
765array will be created and that the value returned by \fIAdder\fR will
766still exist after the call to \fIcall_pv\fR.
767.IP "2." 5
768The purpose of the macro \f(CW\*(C`SPAGAIN\*(C'\fR is to refresh the local copy of the
769stack pointer. This is necessary because it is possible that the memory
770allocated to the Perl stack has been reallocated whilst in the
771\&\fIcall_pv\fR call.
772.Sp
773If you are making use of the Perl stack pointer in your code you must
774always refresh the local copy using \s-1SPAGAIN\s0 whenever you make use
775of the \fIcall_*\fR functions or any other Perl internal function.
776.IP "3." 5
777Although only a single value was expected to be returned from \fIAdder\fR,
778it is still good practice to check the return code from \fIcall_pv\fR
779anyway.
780.Sp
781Expecting a single value is not quite the same as knowing that there
782will be one. If someone modified \fIAdder\fR to return a list and we
783didn't check for that possibility and take appropriate action the Perl
784stack would end up in an inconsistent state. That is something you
785\&\fIreally\fR don't want to happen ever.
786.IP "4." 5
787The \f(CW\*(C`POPi\*(C'\fR macro is used here to pop the return value from the stack.
788In this case we wanted an integer, so \f(CW\*(C`POPi\*(C'\fR was used.
789.Sp
790Here is the complete list of \s-1POP\s0 macros available, along with the types
791they return.
792.Sp
793.Vb 5
794\& POPs SV
795\& POPp pointer
796\& POPn double
797\& POPi integer
798\& POPl long
799.Ve
800.IP "5." 5
801The final \f(CW\*(C`PUTBACK\*(C'\fR is used to leave the Perl stack in a consistent
802state before exiting the function. This is necessary because when we
803popped the return value from the stack with \f(CW\*(C`POPi\*(C'\fR it updated only our
804local copy of the stack pointer. Remember, \f(CW\*(C`PUTBACK\*(C'\fR sets the global
805stack pointer to be the same as our local copy.
806.Sh "Returning a list of values"
807.IX Subsection "Returning a list of values"
808Now, let's extend the previous example to return both the sum of the
809parameters and the difference.
810.PP
811Here is the Perl subroutine
812.PP
813.Vb 5
814\& sub AddSubtract
815\& {
816\& my($a, $b) = @_ ;
817\& ($a+$b, $a-$b) ;
818\& }
819.Ve
820.PP
821and this is the C function
822.PP
823.Vb 7
824\& static void
825\& call_AddSubtract(a, b)
826\& int a ;
827\& int b ;
828\& {
829\& dSP ;
830\& int count ;
831.Ve
832.PP
833.Vb 2
834\& ENTER ;
835\& SAVETMPS;
836.Ve
837.PP
838.Vb 4
839\& PUSHMARK(SP) ;
840\& XPUSHs(sv_2mortal(newSViv(a)));
841\& XPUSHs(sv_2mortal(newSViv(b)));
842\& PUTBACK ;
843.Ve
844.PP
845.Vb 1
846\& count = call_pv("AddSubtract", G_ARRAY);
847.Ve
848.PP
849.Vb 1
850\& SPAGAIN ;
851.Ve
852.PP
853.Vb 2
854\& if (count != 2)
855\& croak("Big trouble\en") ;
856.Ve
857.PP
858.Vb 2
859\& printf ("%d - %d = %d\en", a, b, POPi) ;
860\& printf ("%d + %d = %d\en", a, b, POPi) ;
861.Ve
862.PP
863.Vb 4
864\& PUTBACK ;
865\& FREETMPS ;
866\& LEAVE ;
867\& }
868.Ve
869.PP
870If \fIcall_AddSubtract\fR is called like this
871.PP
872.Vb 1
873\& call_AddSubtract(7, 4) ;
874.Ve
875.PP
876then here is the output
877.PP
878.Vb 2
879\& 7 - 4 = 3
880\& 7 + 4 = 11
881.Ve
882.PP
883Notes
884.IP "1." 5
885We wanted list context, so G_ARRAY was used.
886.IP "2." 5
887Not surprisingly \f(CW\*(C`POPi\*(C'\fR is used twice this time because we were
888retrieving 2 values from the stack. The important thing to note is that
889when using the \f(CW\*(C`POP*\*(C'\fR macros they come off the stack in \fIreverse\fR
890order.
891.Sh "Returning a list in a scalar context"
892.IX Subsection "Returning a list in a scalar context"
893Say the Perl subroutine in the previous section was called in a scalar
894context, like this
895.PP
896.Vb 8
897\& static void
898\& call_AddSubScalar(a, b)
899\& int a ;
900\& int b ;
901\& {
902\& dSP ;
903\& int count ;
904\& int i ;
905.Ve
906.PP
907.Vb 2
908\& ENTER ;
909\& SAVETMPS;
910.Ve
911.PP
912.Vb 4
913\& PUSHMARK(SP) ;
914\& XPUSHs(sv_2mortal(newSViv(a)));
915\& XPUSHs(sv_2mortal(newSViv(b)));
916\& PUTBACK ;
917.Ve
918.PP
919.Vb 1
920\& count = call_pv("AddSubtract", G_SCALAR);
921.Ve
922.PP
923.Vb 1
924\& SPAGAIN ;
925.Ve
926.PP
927.Vb 1
928\& printf ("Items Returned = %d\en", count) ;
929.Ve
930.PP
931.Vb 2
932\& for (i = 1 ; i <= count ; ++i)
933\& printf ("Value %d = %d\en", i, POPi) ;
934.Ve
935.PP
936.Vb 4
937\& PUTBACK ;
938\& FREETMPS ;
939\& LEAVE ;
940\& }
941.Ve
942.PP
943The other modification made is that \fIcall_AddSubScalar\fR will print the
944number of items returned from the Perl subroutine and their value (for
945simplicity it assumes that they are integer). So if
946\&\fIcall_AddSubScalar\fR is called
947.PP
948.Vb 1
949\& call_AddSubScalar(7, 4) ;
950.Ve
951.PP
952then the output will be
953.PP
954.Vb 2
955\& Items Returned = 1
956\& Value 1 = 3
957.Ve
958.PP
959In this case the main point to note is that only the last item in the
960list is returned from the subroutine, \fIAddSubtract\fR actually made it back to
961\&\fIcall_AddSubScalar\fR.
962.Sh "Returning Data from Perl via the parameter list"
963.IX Subsection "Returning Data from Perl via the parameter list"
964It is also possible to return values directly via the parameter list \-
965whether it is actually desirable to do it is another matter entirely.
966.PP
967The Perl subroutine, \fIInc\fR, below takes 2 parameters and increments
968each directly.
969.PP
970.Vb 5
971\& sub Inc
972\& {
973\& ++ $_[0] ;
974\& ++ $_[1] ;
975\& }
976.Ve
977.PP
978and here is a C function to call it.
979.PP
980.Vb 9
981\& static void
982\& call_Inc(a, b)
983\& int a ;
984\& int b ;
985\& {
986\& dSP ;
987\& int count ;
988\& SV * sva ;
989\& SV * svb ;
990.Ve
991.PP
992.Vb 2
993\& ENTER ;
994\& SAVETMPS;
995.Ve
996.PP
997.Vb 2
998\& sva = sv_2mortal(newSViv(a)) ;
999\& svb = sv_2mortal(newSViv(b)) ;
1000.Ve
1001.PP
1002.Vb 4
1003\& PUSHMARK(SP) ;
1004\& XPUSHs(sva);
1005\& XPUSHs(svb);
1006\& PUTBACK ;
1007.Ve
1008.PP
1009.Vb 1
1010\& count = call_pv("Inc", G_DISCARD);
1011.Ve
1012.PP
1013.Vb 3
1014\& if (count != 0)
1015\& croak ("call_Inc: expected 0 values from 'Inc', got %d\en",
1016\& count) ;
1017.Ve
1018.PP
1019.Vb 2
1020\& printf ("%d + 1 = %d\en", a, SvIV(sva)) ;
1021\& printf ("%d + 1 = %d\en", b, SvIV(svb)) ;
1022.Ve
1023.PP
1024.Vb 3
1025\& FREETMPS ;
1026\& LEAVE ;
1027\& }
1028.Ve
1029.PP
1030To be able to access the two parameters that were pushed onto the stack
1031after they return from \fIcall_pv\fR it is necessary to make a note
1032of their addresses\*(--thus the two variables \f(CW\*(C`sva\*(C'\fR and \f(CW\*(C`svb\*(C'\fR.
1033.PP
1034The reason this is necessary is that the area of the Perl stack which
1035held them will very likely have been overwritten by something else by
1036the time control returns from \fIcall_pv\fR.
1037.Sh "Using G_EVAL"
1038.IX Subsection "Using G_EVAL"
1039Now an example using G_EVAL. Below is a Perl subroutine which computes
1040the difference of its 2 parameters. If this would result in a negative
1041result, the subroutine calls \fIdie\fR.
1042.PP
1043.Vb 3
1044\& sub Subtract
1045\& {
1046\& my ($a, $b) = @_ ;
1047.Ve
1048.PP
1049.Vb 1
1050\& die "death can be fatal\en" if $a < $b ;
1051.Ve
1052.PP
1053.Vb 2
1054\& $a - $b ;
1055\& }
1056.Ve
1057.PP
1058and some C to call it
1059.PP
1060.Vb 7
1061\& static void
1062\& call_Subtract(a, b)
1063\& int a ;
1064\& int b ;
1065\& {
1066\& dSP ;
1067\& int count ;
1068.Ve
1069.PP
1070.Vb 2
1071\& ENTER ;
1072\& SAVETMPS;
1073.Ve
1074.PP
1075.Vb 4
1076\& PUSHMARK(SP) ;
1077\& XPUSHs(sv_2mortal(newSViv(a)));
1078\& XPUSHs(sv_2mortal(newSViv(b)));
1079\& PUTBACK ;
1080.Ve
1081.PP
1082.Vb 1
1083\& count = call_pv("Subtract", G_EVAL|G_SCALAR);
1084.Ve
1085.PP
1086.Vb 1
1087\& SPAGAIN ;
1088.Ve
1089.PP
1090.Vb 12
1091\& /* Check the eval first */
1092\& if (SvTRUE(ERRSV))
1093\& {
1094\& STRLEN n_a;
1095\& printf ("Uh oh - %s\en", SvPV(ERRSV, n_a)) ;
1096\& POPs ;
1097\& }
1098\& else
1099\& {
1100\& if (count != 1)
1101\& croak("call_Subtract: wanted 1 value from 'Subtract', got %d\en",
1102\& count) ;
1103.Ve
1104.PP
1105.Vb 2
1106\& printf ("%d - %d = %d\en", a, b, POPi) ;
1107\& }
1108.Ve
1109.PP
1110.Vb 4
1111\& PUTBACK ;
1112\& FREETMPS ;
1113\& LEAVE ;
1114\& }
1115.Ve
1116.PP
1117If \fIcall_Subtract\fR is called thus
1118.PP
1119.Vb 1
1120\& call_Subtract(4, 5)
1121.Ve
1122.PP
1123the following will be printed
1124.PP
1125.Vb 1
1126\& Uh oh - death can be fatal
1127.Ve
1128.PP
1129Notes
1130.IP "1." 5
1131We want to be able to catch the \fIdie\fR so we have used the G_EVAL
1132flag. Not specifying this flag would mean that the program would
1133terminate immediately at the \fIdie\fR statement in the subroutine
1134\&\fISubtract\fR.
1135.IP "2." 5
1136The code
1137.Sp
1138.Vb 6
1139\& if (SvTRUE(ERRSV))
1140\& {
1141\& STRLEN n_a;
1142\& printf ("Uh oh - %s\en", SvPV(ERRSV, n_a)) ;
1143\& POPs ;
1144\& }
1145.Ve
1146.Sp
1147is the direct equivalent of this bit of Perl
1148.Sp
1149.Vb 1
1150\& print "Uh oh - $@\en" if $@ ;
1151.Ve
1152.Sp
1153\&\f(CW\*(C`PL_errgv\*(C'\fR is a perl global of type \f(CW\*(C`GV *\*(C'\fR that points to the
1154symbol table entry containing the error. \f(CW\*(C`ERRSV\*(C'\fR therefore
1155refers to the C equivalent of \f(CW$@\fR.
1156.IP "3." 5
1157Note that the stack is popped using \f(CW\*(C`POPs\*(C'\fR in the block where
1158\&\f(CW\*(C`SvTRUE(ERRSV)\*(C'\fR is true. This is necessary because whenever a
1159\&\fIcall_*\fR function invoked with G_EVAL|G_SCALAR returns an error,
1160the top of the stack holds the value \fIundef\fR. Because we want the
1161program to continue after detecting this error, it is essential that
1162the stack is tidied up by removing the \fIundef\fR.
1163.Sh "Using G_KEEPERR"
1164.IX Subsection "Using G_KEEPERR"
1165Consider this rather facetious example, where we have used an \s-1XS\s0
1166version of the call_Subtract example above inside a destructor:
1167.PP
1168.Vb 9
1169\& package Foo;
1170\& sub new { bless {}, $_[0] }
1171\& sub Subtract {
1172\& my($a,$b) = @_;
1173\& die "death can be fatal" if $a < $b ;
1174\& $a - $b;
1175\& }
1176\& sub DESTROY { call_Subtract(5, 4); }
1177\& sub foo { die "foo dies"; }
1178.Ve
1179.PP
1180.Vb 3
1181\& package main;
1182\& eval { Foo->new->foo };
1183\& print "Saw: $@" if $@; # should be, but isn't
1184.Ve
1185.PP
1186This example will fail to recognize that an error occurred inside the
1187\&\f(CW\*(C`eval {}\*(C'\fR. Here's why: the call_Subtract code got executed while perl
1188was cleaning up temporaries when exiting the eval block, and because
1189call_Subtract is implemented with \fIcall_pv\fR using the G_EVAL
1190flag, it promptly reset \f(CW$@\fR. This results in the failure of the
1191outermost test for \f(CW$@\fR, and thereby the failure of the error trap.
1192.PP
1193Appending the G_KEEPERR flag, so that the \fIcall_pv\fR call in
1194call_Subtract reads:
1195.PP
1196.Vb 1
1197\& count = call_pv("Subtract", G_EVAL|G_SCALAR|G_KEEPERR);
1198.Ve
1199.PP
1200will preserve the error and restore reliable error handling.
1201.Sh "Using call_sv"
1202.IX Subsection "Using call_sv"
1203In all the previous examples I have 'hard\-wired' the name of the Perl
1204subroutine to be called from C. Most of the time though, it is more
1205convenient to be able to specify the name of the Perl subroutine from
1206within the Perl script.
1207.PP
1208Consider the Perl code below
1209.PP
1210.Vb 4
1211\& sub fred
1212\& {
1213\& print "Hello there\en" ;
1214\& }
1215.Ve
1216.PP
1217.Vb 1
1218\& CallSubPV("fred") ;
1219.Ve
1220.PP
1221Here is a snippet of \s-1XSUB\s0 which defines \fICallSubPV\fR.
1222.PP
1223.Vb 6
1224\& void
1225\& CallSubPV(name)
1226\& char * name
1227\& CODE:
1228\& PUSHMARK(SP) ;
1229\& call_pv(name, G_DISCARD|G_NOARGS) ;
1230.Ve
1231.PP
1232That is fine as far as it goes. The thing is, the Perl subroutine
1233can be specified as only a string. For Perl 4 this was adequate,
1234but Perl 5 allows references to subroutines and anonymous subroutines.
1235This is where \fIcall_sv\fR is useful.
1236.PP
1237The code below for \fICallSubSV\fR is identical to \fICallSubPV\fR except
1238that the \f(CW\*(C`name\*(C'\fR parameter is now defined as an SV* and we use
1239\&\fIcall_sv\fR instead of \fIcall_pv\fR.
1240.PP
1241.Vb 6
1242\& void
1243\& CallSubSV(name)
1244\& SV * name
1245\& CODE:
1246\& PUSHMARK(SP) ;
1247\& call_sv(name, G_DISCARD|G_NOARGS) ;
1248.Ve
1249.PP
1250Because we are using an \s-1SV\s0 to call \fIfred\fR the following can all be used
1251.PP
1252.Vb 5
1253\& CallSubSV("fred") ;
1254\& CallSubSV(\e&fred) ;
1255\& $ref = \e&fred ;
1256\& CallSubSV($ref) ;
1257\& CallSubSV( sub { print "Hello there\en" } ) ;
1258.Ve
1259.PP
1260As you can see, \fIcall_sv\fR gives you much greater flexibility in
1261how you can specify the Perl subroutine.
1262.PP
1263You should note that if it is necessary to store the \s-1SV\s0 (\f(CW\*(C`name\*(C'\fR in the
1264example above) which corresponds to the Perl subroutine so that it can
1265be used later in the program, it not enough just to store a copy of the
1266pointer to the \s-1SV\s0. Say the code above had been like this
1267.PP
1268.Vb 1
1269\& static SV * rememberSub ;
1270.Ve
1271.PP
1272.Vb 5
1273\& void
1274\& SaveSub1(name)
1275\& SV * name
1276\& CODE:
1277\& rememberSub = name ;
1278.Ve
1279.PP
1280.Vb 5
1281\& void
1282\& CallSavedSub1()
1283\& CODE:
1284\& PUSHMARK(SP) ;
1285\& call_sv(rememberSub, G_DISCARD|G_NOARGS) ;
1286.Ve
1287.PP
1288The reason this is wrong is that by the time you come to use the
1289pointer \f(CW\*(C`rememberSub\*(C'\fR in \f(CW\*(C`CallSavedSub1\*(C'\fR, it may or may not still refer
1290to the Perl subroutine that was recorded in \f(CW\*(C`SaveSub1\*(C'\fR. This is
1291particularly true for these cases
1292.PP
1293.Vb 2
1294\& SaveSub1(\e&fred) ;
1295\& CallSavedSub1() ;
1296.Ve
1297.PP
1298.Vb 2
1299\& SaveSub1( sub { print "Hello there\en" } ) ;
1300\& CallSavedSub1() ;
1301.Ve
1302.PP
1303By the time each of the \f(CW\*(C`SaveSub1\*(C'\fR statements above have been executed,
1304the SV*s which corresponded to the parameters will no longer exist.
1305Expect an error message from Perl of the form
1306.PP
1307.Vb 1
1308\& Can't use an undefined value as a subroutine reference at ...
1309.Ve
1310.PP
1311for each of the \f(CW\*(C`CallSavedSub1\*(C'\fR lines.
1312.PP
1313Similarly, with this code
1314.PP
1315.Vb 4
1316\& $ref = \e&fred ;
1317\& SaveSub1($ref) ;
1318\& $ref = 47 ;
1319\& CallSavedSub1() ;
1320.Ve
1321.PP
1322you can expect one of these messages (which you actually get is dependent on
1323the version of Perl you are using)
1324.PP
1325.Vb 2
1326\& Not a CODE reference at ...
1327\& Undefined subroutine &main::47 called ...
1328.Ve
1329.PP
1330The variable \f(CW$ref\fR may have referred to the subroutine \f(CW\*(C`fred\*(C'\fR
1331whenever the call to \f(CW\*(C`SaveSub1\*(C'\fR was made but by the time
1332\&\f(CW\*(C`CallSavedSub1\*(C'\fR gets called it now holds the number \f(CW47\fR. Because we
1333saved only a pointer to the original \s-1SV\s0 in \f(CW\*(C`SaveSub1\*(C'\fR, any changes to
1334\&\f(CW$ref\fR will be tracked by the pointer \f(CW\*(C`rememberSub\*(C'\fR. This means that
1335whenever \f(CW\*(C`CallSavedSub1\*(C'\fR gets called, it will attempt to execute the
1336code which is referenced by the SV* \f(CW\*(C`rememberSub\*(C'\fR. In this case
1337though, it now refers to the integer \f(CW47\fR, so expect Perl to complain
1338loudly.
1339.PP
1340A similar but more subtle problem is illustrated with this code
1341.PP
1342.Vb 4
1343\& $ref = \e&fred ;
1344\& SaveSub1($ref) ;
1345\& $ref = \e&joe ;
1346\& CallSavedSub1() ;
1347.Ve
1348.PP
1349This time whenever \f(CW\*(C`CallSavedSub1\*(C'\fR get called it will execute the Perl
1350subroutine \f(CW\*(C`joe\*(C'\fR (assuming it exists) rather than \f(CW\*(C`fred\*(C'\fR as was
1351originally requested in the call to \f(CW\*(C`SaveSub1\*(C'\fR.
1352.PP
1353To get around these problems it is necessary to take a full copy of the
1354\&\s-1SV\s0. The code below shows \f(CW\*(C`SaveSub2\*(C'\fR modified to do that
1355.PP
1356.Vb 1
1357\& static SV * keepSub = (SV*)NULL ;
1358.Ve
1359.PP
1360.Vb 11
1361\& void
1362\& SaveSub2(name)
1363\& SV * name
1364\& CODE:
1365\& /* Take a copy of the callback */
1366\& if (keepSub == (SV*)NULL)
1367\& /* First time, so create a new SV */
1368\& keepSub = newSVsv(name) ;
1369\& else
1370\& /* Been here before, so overwrite */
1371\& SvSetSV(keepSub, name) ;
1372.Ve
1373.PP
1374.Vb 5
1375\& void
1376\& CallSavedSub2()
1377\& CODE:
1378\& PUSHMARK(SP) ;
1379\& call_sv(keepSub, G_DISCARD|G_NOARGS) ;
1380.Ve
1381.PP
1382To avoid creating a new \s-1SV\s0 every time \f(CW\*(C`SaveSub2\*(C'\fR is called,
1383the function first checks to see if it has been called before. If not,
1384then space for a new \s-1SV\s0 is allocated and the reference to the Perl
1385subroutine, \f(CW\*(C`name\*(C'\fR is copied to the variable \f(CW\*(C`keepSub\*(C'\fR in one
1386operation using \f(CW\*(C`newSVsv\*(C'\fR. Thereafter, whenever \f(CW\*(C`SaveSub2\*(C'\fR is called
1387the existing \s-1SV\s0, \f(CW\*(C`keepSub\*(C'\fR, is overwritten with the new value using
1388\&\f(CW\*(C`SvSetSV\*(C'\fR.
1389.Sh "Using call_argv"
1390.IX Subsection "Using call_argv"
1391Here is a Perl subroutine which prints whatever parameters are passed
1392to it.
1393.PP
1394.Vb 3
1395\& sub PrintList
1396\& {
1397\& my(@list) = @_ ;
1398.Ve
1399.PP
1400.Vb 2
1401\& foreach (@list) { print "$_\en" }
1402\& }
1403.Ve
1404.PP
1405and here is an example of \fIcall_argv\fR which will call
1406\&\fIPrintList\fR.
1407.PP
1408.Vb 1
1409\& static char * words[] = {"alpha", "beta", "gamma", "delta", NULL} ;
1410.Ve
1411.PP
1412.Vb 4
1413\& static void
1414\& call_PrintList()
1415\& {
1416\& dSP ;
1417.Ve
1418.PP
1419.Vb 2
1420\& call_argv("PrintList", G_DISCARD, words) ;
1421\& }
1422.Ve
1423.PP
1424Note that it is not necessary to call \f(CW\*(C`PUSHMARK\*(C'\fR in this instance.
1425This is because \fIcall_argv\fR will do it for you.
1426.Sh "Using call_method"
1427.IX Subsection "Using call_method"
1428Consider the following Perl code
1429.PP
1430.Vb 2
1431\& {
1432\& package Mine ;
1433.Ve
1434.PP
1435.Vb 5
1436\& sub new
1437\& {
1438\& my($type) = shift ;
1439\& bless [@_]
1440\& }
1441.Ve
1442.PP
1443.Vb 5
1444\& sub Display
1445\& {
1446\& my ($self, $index) = @_ ;
1447\& print "$index: $$self[$index]\en" ;
1448\& }
1449.Ve
1450.PP
1451.Vb 6
1452\& sub PrintID
1453\& {
1454\& my($class) = @_ ;
1455\& print "This is Class $class version 1.0\en" ;
1456\& }
1457\& }
1458.Ve
1459.PP
1460It implements just a very simple class to manage an array. Apart from
1461the constructor, \f(CW\*(C`new\*(C'\fR, it declares methods, one static and one
1462virtual. The static method, \f(CW\*(C`PrintID\*(C'\fR, prints out simply the class
1463name and a version number. The virtual method, \f(CW\*(C`Display\*(C'\fR, prints out a
1464single element of the array. Here is an all Perl example of using it.
1465.PP
1466.Vb 3
1467\& $a = new Mine ('red', 'green', 'blue') ;
1468\& $a->Display(1) ;
1469\& PrintID Mine;
1470.Ve
1471.PP
1472will print
1473.PP
1474.Vb 2
1475\& 1: green
1476\& This is Class Mine version 1.0
1477.Ve
1478.PP
1479Calling a Perl method from C is fairly straightforward. The following
1480things are required
1481.IP "\(bu" 5
1482a reference to the object for a virtual method or the name of the class
1483for a static method.
1484.IP "\(bu" 5
1485the name of the method.
1486.IP "\(bu" 5
1487any other parameters specific to the method.
1488.PP
1489Here is a simple \s-1XSUB\s0 which illustrates the mechanics of calling both
1490the \f(CW\*(C`PrintID\*(C'\fR and \f(CW\*(C`Display\*(C'\fR methods from C.
1491.PP
1492.Vb 10
1493\& void
1494\& call_Method(ref, method, index)
1495\& SV * ref
1496\& char * method
1497\& int index
1498\& CODE:
1499\& PUSHMARK(SP);
1500\& XPUSHs(ref);
1501\& XPUSHs(sv_2mortal(newSViv(index))) ;
1502\& PUTBACK;
1503.Ve
1504.PP
1505.Vb 1
1506\& call_method(method, G_DISCARD) ;
1507.Ve
1508.PP
1509.Vb 8
1510\& void
1511\& call_PrintID(class, method)
1512\& char * class
1513\& char * method
1514\& CODE:
1515\& PUSHMARK(SP);
1516\& XPUSHs(sv_2mortal(newSVpv(class, 0))) ;
1517\& PUTBACK;
1518.Ve
1519.PP
1520.Vb 1
1521\& call_method(method, G_DISCARD) ;
1522.Ve
1523.PP
1524So the methods \f(CW\*(C`PrintID\*(C'\fR and \f(CW\*(C`Display\*(C'\fR can be invoked like this
1525.PP
1526.Vb 3
1527\& $a = new Mine ('red', 'green', 'blue') ;
1528\& call_Method($a, 'Display', 1) ;
1529\& call_PrintID('Mine', 'PrintID') ;
1530.Ve
1531.PP
1532The only thing to note is that in both the static and virtual methods,
1533the method name is not passed via the stack\*(--it is used as the first
1534parameter to \fIcall_method\fR.
1535.Sh "Using \s-1GIMME_V\s0"
1536.IX Subsection "Using GIMME_V"
1537Here is a trivial \s-1XSUB\s0 which prints the context in which it is
1538currently executing.
1539.PP
1540.Vb 10
1541\& void
1542\& PrintContext()
1543\& CODE:
1544\& I32 gimme = GIMME_V;
1545\& if (gimme == G_VOID)
1546\& printf ("Context is Void\en") ;
1547\& else if (gimme == G_SCALAR)
1548\& printf ("Context is Scalar\en") ;
1549\& else
1550\& printf ("Context is Array\en") ;
1551.Ve
1552.PP
1553and here is some Perl to test it
1554.PP
1555.Vb 3
1556\& PrintContext ;
1557\& $a = PrintContext ;
1558\& @a = PrintContext ;
1559.Ve
1560.PP
1561The output from that will be
1562.PP
1563.Vb 3
1564\& Context is Void
1565\& Context is Scalar
1566\& Context is Array
1567.Ve
1568.Sh "Using Perl to dispose of temporaries"
1569.IX Subsection "Using Perl to dispose of temporaries"
1570In the examples given to date, any temporaries created in the callback
1571(i.e., parameters passed on the stack to the \fIcall_*\fR function or
1572values returned via the stack) have been freed by one of these methods
1573.IP "\(bu" 5
1574specifying the G_DISCARD flag with \fIcall_*\fR.
1575.IP "\(bu" 5
1576explicitly disposed of using the \f(CW\*(C`ENTER\*(C'\fR/\f(CW\*(C`SAVETMPS\*(C'\fR \-
1577\&\f(CW\*(C`FREETMPS\*(C'\fR/\f(CW\*(C`LEAVE\*(C'\fR pairing.
1578.PP
1579There is another method which can be used, namely letting Perl do it
1580for you automatically whenever it regains control after the callback
1581has terminated. This is done by simply not using the
1582.PP
1583.Vb 5
1584\& ENTER ;
1585\& SAVETMPS ;
1586\& ...
1587\& FREETMPS ;
1588\& LEAVE ;
1589.Ve
1590.PP
1591sequence in the callback (and not, of course, specifying the G_DISCARD
1592flag).
1593.PP
1594If you are going to use this method you have to be aware of a possible
1595memory leak which can arise under very specific circumstances. To
1596explain these circumstances you need to know a bit about the flow of
1597control between Perl and the callback routine.
1598.PP
1599The examples given at the start of the document (an error handler and
1600an event driven program) are typical of the two main sorts of flow
1601control that you are likely to encounter with callbacks. There is a
1602very important distinction between them, so pay attention.
1603.PP
1604In the first example, an error handler, the flow of control could be as
1605follows. You have created an interface to an external library.
1606Control can reach the external library like this
1607.PP
1608.Vb 1
1609\& perl --> XSUB --> external library
1610.Ve
1611.PP
1612Whilst control is in the library, an error condition occurs. You have
1613previously set up a Perl callback to handle this situation, so it will
1614get executed. Once the callback has finished, control will drop back to
1615Perl again. Here is what the flow of control will be like in that
1616situation
1617.PP
1618.Vb 7
1619\& perl --> XSUB --> external library
1620\& ...
1621\& error occurs
1622\& ...
1623\& external library --> call_* --> perl
1624\& |
1625\& perl <-- XSUB <-- external library <-- call_* <----+
1626.Ve
1627.PP
1628After processing of the error using \fIcall_*\fR is completed,
1629control reverts back to Perl more or less immediately.
1630.PP
1631In the diagram, the further right you go the more deeply nested the
1632scope is. It is only when control is back with perl on the extreme
1633left of the diagram that you will have dropped back to the enclosing
1634scope and any temporaries you have left hanging around will be freed.
1635.PP
1636In the second example, an event driven program, the flow of control
1637will be more like this
1638.PP
1639.Vb 13
1640\& perl --> XSUB --> event handler
1641\& ...
1642\& event handler --> call_* --> perl
1643\& |
1644\& event handler <-- call_* <----+
1645\& ...
1646\& event handler --> call_* --> perl
1647\& |
1648\& event handler <-- call_* <----+
1649\& ...
1650\& event handler --> call_* --> perl
1651\& |
1652\& event handler <-- call_* <----+
1653.Ve
1654.PP
1655In this case the flow of control can consist of only the repeated
1656sequence
1657.PP
1658.Vb 1
1659\& event handler --> call_* --> perl
1660.Ve
1661.PP
1662for practically the complete duration of the program. This means that
1663control may \fInever\fR drop back to the surrounding scope in Perl at the
1664extreme left.
1665.PP
1666So what is the big problem? Well, if you are expecting Perl to tidy up
1667those temporaries for you, you might be in for a long wait. For Perl
1668to dispose of your temporaries, control must drop back to the
1669enclosing scope at some stage. In the event driven scenario that may
1670never happen. This means that as time goes on, your program will
1671create more and more temporaries, none of which will ever be freed. As
1672each of these temporaries consumes some memory your program will
1673eventually consume all the available memory in your system\*(--kapow!
1674.PP
1675So here is the bottom line\*(--if you are sure that control will revert
1676back to the enclosing Perl scope fairly quickly after the end of your
1677callback, then it isn't absolutely necessary to dispose explicitly of
1678any temporaries you may have created. Mind you, if you are at all
1679uncertain about what to do, it doesn't do any harm to tidy up anyway.
1680.Sh "Strategies for storing Callback Context Information"
1681.IX Subsection "Strategies for storing Callback Context Information"
1682Potentially one of the trickiest problems to overcome when designing a
1683callback interface can be figuring out how to store the mapping between
1684the C callback function and the Perl equivalent.
1685.PP
1686To help understand why this can be a real problem first consider how a
1687callback is set up in an all C environment. Typically a C \s-1API\s0 will
1688provide a function to register a callback. This will expect a pointer
1689to a function as one of its parameters. Below is a call to a
1690hypothetical function \f(CW\*(C`register_fatal\*(C'\fR which registers the C function
1691to get called when a fatal error occurs.
1692.PP
1693.Vb 1
1694\& register_fatal(cb1) ;
1695.Ve
1696.PP
1697The single parameter \f(CW\*(C`cb1\*(C'\fR is a pointer to a function, so you must
1698have defined \f(CW\*(C`cb1\*(C'\fR in your code, say something like this
1699.PP
1700.Vb 6
1701\& static void
1702\& cb1()
1703\& {
1704\& printf ("Fatal Error\en") ;
1705\& exit(1) ;
1706\& }
1707.Ve
1708.PP
1709Now change that to call a Perl subroutine instead
1710.PP
1711.Vb 1
1712\& static SV * callback = (SV*)NULL;
1713.Ve
1714.PP
1715.Vb 4
1716\& static void
1717\& cb1()
1718\& {
1719\& dSP ;
1720.Ve
1721.PP
1722.Vb 1
1723\& PUSHMARK(SP) ;
1724.Ve
1725.PP
1726.Vb 3
1727\& /* Call the Perl sub to process the callback */
1728\& call_sv(callback, G_DISCARD) ;
1729\& }
1730.Ve
1731.PP
1732.Vb 9
1733\& void
1734\& register_fatal(fn)
1735\& SV * fn
1736\& CODE:
1737\& /* Remember the Perl sub */
1738\& if (callback == (SV*)NULL)
1739\& callback = newSVsv(fn) ;
1740\& else
1741\& SvSetSV(callback, fn) ;
1742.Ve
1743.PP
1744.Vb 2
1745\& /* register the callback with the external library */
1746\& register_fatal(cb1) ;
1747.Ve
1748.PP
1749where the Perl equivalent of \f(CW\*(C`register_fatal\*(C'\fR and the callback it
1750registers, \f(CW\*(C`pcb1\*(C'\fR, might look like this
1751.PP
1752.Vb 2
1753\& # Register the sub pcb1
1754\& register_fatal(\e&pcb1) ;
1755.Ve
1756.PP
1757.Vb 4
1758\& sub pcb1
1759\& {
1760\& die "I'm dying...\en" ;
1761\& }
1762.Ve
1763.PP
1764The mapping between the C callback and the Perl equivalent is stored in
1765the global variable \f(CW\*(C`callback\*(C'\fR.
1766.PP
1767This will be adequate if you ever need to have only one callback
1768registered at any time. An example could be an error handler like the
1769code sketched out above. Remember though, repeated calls to
1770\&\f(CW\*(C`register_fatal\*(C'\fR will replace the previously registered callback
1771function with the new one.
1772.PP
1773Say for example you want to interface to a library which allows asynchronous
1774file i/o. In this case you may be able to register a callback whenever
1775a read operation has completed. To be of any use we want to be able to
1776call separate Perl subroutines for each file that is opened. As it
1777stands, the error handler example above would not be adequate as it
1778allows only a single callback to be defined at any time. What we
1779require is a means of storing the mapping between the opened file and
1780the Perl subroutine we want to be called for that file.
1781.PP
1782Say the i/o library has a function \f(CW\*(C`asynch_read\*(C'\fR which associates a C
1783function \f(CW\*(C`ProcessRead\*(C'\fR with a file handle \f(CW\*(C`fh\*(C'\fR\-\-this assumes that it
1784has also provided some routine to open the file and so obtain the file
1785handle.
1786.PP
1787.Vb 1
1788\& asynch_read(fh, ProcessRead)
1789.Ve
1790.PP
1791This may expect the C \fIProcessRead\fR function of this form
1792.PP
1793.Vb 7
1794\& void
1795\& ProcessRead(fh, buffer)
1796\& int fh ;
1797\& char * buffer ;
1798\& {
1799\& ...
1800\& }
1801.Ve
1802.PP
1803To provide a Perl interface to this library we need to be able to map
1804between the \f(CW\*(C`fh\*(C'\fR parameter and the Perl subroutine we want called. A
1805hash is a convenient mechanism for storing this mapping. The code
1806below shows a possible implementation
1807.PP
1808.Vb 1
1809\& static HV * Mapping = (HV*)NULL ;
1810.Ve
1811.PP
1812.Vb 8
1813\& void
1814\& asynch_read(fh, callback)
1815\& int fh
1816\& SV * callback
1817\& CODE:
1818\& /* If the hash doesn't already exist, create it */
1819\& if (Mapping == (HV*)NULL)
1820\& Mapping = newHV() ;
1821.Ve
1822.PP
1823.Vb 2
1824\& /* Save the fh -> callback mapping */
1825\& hv_store(Mapping, (char*)&fh, sizeof(fh), newSVsv(callback), 0) ;
1826.Ve
1827.PP
1828.Vb 2
1829\& /* Register with the C Library */
1830\& asynch_read(fh, asynch_read_if) ;
1831.Ve
1832.PP
1833and \f(CW\*(C`asynch_read_if\*(C'\fR could look like this
1834.PP
1835.Vb 7
1836\& static void
1837\& asynch_read_if(fh, buffer)
1838\& int fh ;
1839\& char * buffer ;
1840\& {
1841\& dSP ;
1842\& SV ** sv ;
1843.Ve
1844.PP
1845.Vb 4
1846\& /* Get the callback associated with fh */
1847\& sv = hv_fetch(Mapping, (char*)&fh , sizeof(fh), FALSE) ;
1848\& if (sv == (SV**)NULL)
1849\& croak("Internal error...\en") ;
1850.Ve
1851.PP
1852.Vb 4
1853\& PUSHMARK(SP) ;
1854\& XPUSHs(sv_2mortal(newSViv(fh))) ;
1855\& XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
1856\& PUTBACK ;
1857.Ve
1858.PP
1859.Vb 3
1860\& /* Call the Perl sub */
1861\& call_sv(*sv, G_DISCARD) ;
1862\& }
1863.Ve
1864.PP
1865For completeness, here is \f(CW\*(C`asynch_close\*(C'\fR. This shows how to remove
1866the entry from the hash \f(CW\*(C`Mapping\*(C'\fR.
1867.PP
1868.Vb 6
1869\& void
1870\& asynch_close(fh)
1871\& int fh
1872\& CODE:
1873\& /* Remove the entry from the hash */
1874\& (void) hv_delete(Mapping, (char*)&fh, sizeof(fh), G_DISCARD) ;
1875.Ve
1876.PP
1877.Vb 2
1878\& /* Now call the real asynch_close */
1879\& asynch_close(fh) ;
1880.Ve
1881.PP
1882So the Perl interface would look like this
1883.PP
1884.Vb 4
1885\& sub callback1
1886\& {
1887\& my($handle, $buffer) = @_ ;
1888\& }
1889.Ve
1890.PP
1891.Vb 2
1892\& # Register the Perl callback
1893\& asynch_read($fh, \e&callback1) ;
1894.Ve
1895.PP
1896.Vb 1
1897\& asynch_close($fh) ;
1898.Ve
1899.PP
1900The mapping between the C callback and Perl is stored in the global
1901hash \f(CW\*(C`Mapping\*(C'\fR this time. Using a hash has the distinct advantage that
1902it allows an unlimited number of callbacks to be registered.
1903.PP
1904What if the interface provided by the C callback doesn't contain a
1905parameter which allows the file handle to Perl subroutine mapping? Say
1906in the asynchronous i/o package, the callback function gets passed only
1907the \f(CW\*(C`buffer\*(C'\fR parameter like this
1908.PP
1909.Vb 6
1910\& void
1911\& ProcessRead(buffer)
1912\& char * buffer ;
1913\& {
1914\& ...
1915\& }
1916.Ve
1917.PP
1918Without the file handle there is no straightforward way to map from the
1919C callback to the Perl subroutine.
1920.PP
1921In this case a possible way around this problem is to predefine a
1922series of C functions to act as the interface to Perl, thus
1923.PP
1924.Vb 3
1925\& #define MAX_CB 3
1926\& #define NULL_HANDLE -1
1927\& typedef void (*FnMap)() ;
1928.Ve
1929.PP
1930.Vb 5
1931\& struct MapStruct {
1932\& FnMap Function ;
1933\& SV * PerlSub ;
1934\& int Handle ;
1935\& } ;
1936.Ve
1937.PP
1938.Vb 3
1939\& static void fn1() ;
1940\& static void fn2() ;
1941\& static void fn3() ;
1942.Ve
1943.PP
1944.Vb 6
1945\& static struct MapStruct Map [MAX_CB] =
1946\& {
1947\& { fn1, NULL, NULL_HANDLE },
1948\& { fn2, NULL, NULL_HANDLE },
1949\& { fn3, NULL, NULL_HANDLE }
1950\& } ;
1951.Ve
1952.PP
1953.Vb 6
1954\& static void
1955\& Pcb(index, buffer)
1956\& int index ;
1957\& char * buffer ;
1958\& {
1959\& dSP ;
1960.Ve
1961.PP
1962.Vb 3
1963\& PUSHMARK(SP) ;
1964\& XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
1965\& PUTBACK ;
1966.Ve
1967.PP
1968.Vb 3
1969\& /* Call the Perl sub */
1970\& call_sv(Map[index].PerlSub, G_DISCARD) ;
1971\& }
1972.Ve
1973.PP
1974.Vb 6
1975\& static void
1976\& fn1(buffer)
1977\& char * buffer ;
1978\& {
1979\& Pcb(0, buffer) ;
1980\& }
1981.Ve
1982.PP
1983.Vb 6
1984\& static void
1985\& fn2(buffer)
1986\& char * buffer ;
1987\& {
1988\& Pcb(1, buffer) ;
1989\& }
1990.Ve
1991.PP
1992.Vb 6
1993\& static void
1994\& fn3(buffer)
1995\& char * buffer ;
1996\& {
1997\& Pcb(2, buffer) ;
1998\& }
1999.Ve
2000.PP
2001.Vb 7
2002\& void
2003\& array_asynch_read(fh, callback)
2004\& int fh
2005\& SV * callback
2006\& CODE:
2007\& int index ;
2008\& int null_index = MAX_CB ;
2009.Ve
2010.PP
2011.Vb 5
2012\& /* Find the same handle or an empty entry */
2013\& for (index = 0 ; index < MAX_CB ; ++index)
2014\& {
2015\& if (Map[index].Handle == fh)
2016\& break ;
2017.Ve
2018.PP
2019.Vb 3
2020\& if (Map[index].Handle == NULL_HANDLE)
2021\& null_index = index ;
2022\& }
2023.Ve
2024.PP
2025.Vb 2
2026\& if (index == MAX_CB && null_index == MAX_CB)
2027\& croak ("Too many callback functions registered\en") ;
2028.Ve
2029.PP
2030.Vb 2
2031\& if (index == MAX_CB)
2032\& index = null_index ;
2033.Ve
2034.PP
2035.Vb 2
2036\& /* Save the file handle */
2037\& Map[index].Handle = fh ;
2038.Ve
2039.PP
2040.Vb 5
2041\& /* Remember the Perl sub */
2042\& if (Map[index].PerlSub == (SV*)NULL)
2043\& Map[index].PerlSub = newSVsv(callback) ;
2044\& else
2045\& SvSetSV(Map[index].PerlSub, callback) ;
2046.Ve
2047.PP
2048.Vb 1
2049\& asynch_read(fh, Map[index].Function) ;
2050.Ve
2051.PP
2052.Vb 5
2053\& void
2054\& array_asynch_close(fh)
2055\& int fh
2056\& CODE:
2057\& int index ;
2058.Ve
2059.PP
2060.Vb 4
2061\& /* Find the file handle */
2062\& for (index = 0; index < MAX_CB ; ++ index)
2063\& if (Map[index].Handle == fh)
2064\& break ;
2065.Ve
2066.PP
2067.Vb 2
2068\& if (index == MAX_CB)
2069\& croak ("could not close fh %d\en", fh) ;
2070.Ve
2071.PP
2072.Vb 3
2073\& Map[index].Handle = NULL_HANDLE ;
2074\& SvREFCNT_dec(Map[index].PerlSub) ;
2075\& Map[index].PerlSub = (SV*)NULL ;
2076.Ve
2077.PP
2078.Vb 1
2079\& asynch_close(fh) ;
2080.Ve
2081.PP
2082In 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
2083remember the Perl subroutine to be called. Each of the functions holds
2084a separate hard-wired index which is used in the function \f(CW\*(C`Pcb\*(C'\fR to
2085access the \f(CW\*(C`Map\*(C'\fR array and actually call the Perl subroutine.
2086.PP
2087There are some obvious disadvantages with this technique.
2088.PP
2089Firstly, the code is considerably more complex than with the previous
2090example.
2091.PP
2092Secondly, there is a hard-wired limit (in this case 3) to the number of
2093callbacks that can exist simultaneously. The only way to increase the
2094limit is by modifying the code to add more functions and then
2095recompiling. None the less, as long as the number of functions is
2096chosen with some care, it is still a workable solution and in some
2097cases is the only one available.
2098.PP
2099To summarize, here are a number of possible methods for you to consider
2100for storing the mapping between C and the Perl callback
2101.IP "1. Ignore the problem \- Allow only 1 callback" 5
2102.IX Item "1. Ignore the problem - Allow only 1 callback"
2103For a lot of situations, like interfacing to an error handler, this may
2104be a perfectly adequate solution.
2105.IP "2. Create a sequence of callbacks \- hard wired limit" 5
2106.IX Item "2. Create a sequence of callbacks - hard wired limit"
2107If it is impossible to tell from the parameters passed back from the C
2108callback what the context is, then you may need to create a sequence of C
2109callback interface functions, and store pointers to each in an array.
2110.IP "3. Use a parameter to map to the Perl callback" 5
2111.IX Item "3. Use a parameter to map to the Perl callback"
2112A hash is an ideal mechanism to store the mapping between C and Perl.
2113.Sh "Alternate Stack Manipulation"
2114.IX Subsection "Alternate Stack Manipulation"
2115Although I have made use of only the \f(CW\*(C`POP*\*(C'\fR macros to access values
2116returned from Perl subroutines, it is also possible to bypass these
2117macros and read the stack using the \f(CW\*(C`ST\*(C'\fR macro (See perlxs for a
2118full description of the \f(CW\*(C`ST\*(C'\fR macro).
2119.PP
2120Most of the time the \f(CW\*(C`POP*\*(C'\fR macros should be adequate, the main
2121problem with them is that they force you to process the returned values
2122in sequence. This may not be the most suitable way to process the
2123values in some cases. What we want is to be able to access the stack in
2124a random order. The \f(CW\*(C`ST\*(C'\fR macro as used when coding an \s-1XSUB\s0 is ideal
2125for this purpose.
2126.PP
2127The code below is the example given in the section \fIReturning a list
2128of values\fR recoded to use \f(CW\*(C`ST\*(C'\fR instead of \f(CW\*(C`POP*\*(C'\fR.
2129.PP
2130.Vb 8
2131\& static void
2132\& call_AddSubtract2(a, b)
2133\& int a ;
2134\& int b ;
2135\& {
2136\& dSP ;
2137\& I32 ax ;
2138\& int count ;
2139.Ve
2140.PP
2141.Vb 2
2142\& ENTER ;
2143\& SAVETMPS;
2144.Ve
2145.PP
2146.Vb 4
2147\& PUSHMARK(SP) ;
2148\& XPUSHs(sv_2mortal(newSViv(a)));
2149\& XPUSHs(sv_2mortal(newSViv(b)));
2150\& PUTBACK ;
2151.Ve
2152.PP
2153.Vb 1
2154\& count = call_pv("AddSubtract", G_ARRAY);
2155.Ve
2156.PP
2157.Vb 3
2158\& SPAGAIN ;
2159\& SP -= count ;
2160\& ax = (SP - PL_stack_base) + 1 ;
2161.Ve
2162.PP
2163.Vb 2
2164\& if (count != 2)
2165\& croak("Big trouble\en") ;
2166.Ve
2167.PP
2168.Vb 2
2169\& printf ("%d + %d = %d\en", a, b, SvIV(ST(0))) ;
2170\& printf ("%d - %d = %d\en", a, b, SvIV(ST(1))) ;
2171.Ve
2172.PP
2173.Vb 4
2174\& PUTBACK ;
2175\& FREETMPS ;
2176\& LEAVE ;
2177\& }
2178.Ve
2179.PP
2180Notes
2181.IP "1." 5
2182Notice that it was necessary to define the variable \f(CW\*(C`ax\*(C'\fR. This is
2183because the \f(CW\*(C`ST\*(C'\fR macro expects it to exist. If we were in an \s-1XSUB\s0 it
2184would not be necessary to define \f(CW\*(C`ax\*(C'\fR as it is already defined for
2185you.
2186.IP "2." 5
2187The code
2188.Sp
2189.Vb 3
2190\& SPAGAIN ;
2191\& SP -= count ;
2192\& ax = (SP - PL_stack_base) + 1 ;
2193.Ve
2194.Sp
2195sets the stack up so that we can use the \f(CW\*(C`ST\*(C'\fR macro.
2196.IP "3." 5
2197Unlike the original coding of this example, the returned
2198values are not accessed in reverse order. So \f(CWST(0)\fR refers to the
2199first value returned by the Perl subroutine and \f(CW\*(C`ST(count\-1)\*(C'\fR
2200refers to the last.
2201.Sh "Creating and calling an anonymous subroutine in C"
2202.IX Subsection "Creating and calling an anonymous subroutine in C"
2203As we've already shown, \f(CW\*(C`call_sv\*(C'\fR can be used to invoke an
2204anonymous subroutine. However, our example showed a Perl script
2205invoking an \s-1XSUB\s0 to perform this operation. Let's see how it can be
2206done inside our C code:
2207.PP
2208.Vb 1
2209\& ...
2210.Ve
2211.PP
2212.Vb 1
2213\& SV *cvrv = eval_pv("sub { print 'You will not find me cluttering any namespace!' }", TRUE);
2214.Ve
2215.PP
2216.Vb 1
2217\& ...
2218.Ve
2219.PP
2220.Vb 1
2221\& call_sv(cvrv, G_VOID|G_NOARGS);
2222.Ve
2223.PP
2224\&\f(CW\*(C`eval_pv\*(C'\fR is used to compile the anonymous subroutine, which
2225will be the return value as well (read more about \f(CW\*(C`eval_pv\*(C'\fR in
2226\&\*(L"eval_pv\*(R" in perlapi). Once this code reference is in hand, it
2227can be mixed in with all the previous examples we've shown.
2228.SH "SEE ALSO"
2229.IX Header "SEE ALSO"
2230perlxs, perlguts, perlembed
2231.SH "AUTHOR"
2232.IX Header "AUTHOR"
2233Paul Marquess
2234.PP
2235Special thanks to the following people who assisted in the creation of
2236the document.
2237.PP
2238Jeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem, Gurusamy Sarathy
2239and Larry Wall.
2240.SH "DATE"
2241.IX Header "DATE"
2242Version 1.3, 14th Apr 1997