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