source: trunk/essentials/dev-lang/perl/pod/perlcall.pod@ 3298

Last change on this file since 3298 was 3181, checked in by bird, 19 years ago

perl 5.8.8

File size: 52.3 KB
Line 
1=head1 NAME
2
3perlcall - Perl calling conventions from C
4
5=head1 DESCRIPTION
6
7The purpose of this document is to show you how to call Perl subroutines
8directly from C, i.e., how to write I<callbacks>.
9
10Apart from discussing the C interface provided by Perl for writing
11callbacks the document uses a series of examples to show how the
12interface actually works in practice. In addition some techniques for
13coding callbacks are covered.
14
15Examples where callbacks are necessary include
16
17=over 5
18
19=item * An Error Handler
20
21You have created an XSUB interface to an application's C API.
22
23A fairly common feature in applications is to allow you to define a C
24function that will be called whenever something nasty occurs. What we
25would like is to be able to specify a Perl subroutine that will be
26called instead.
27
28=item * An Event Driven Program
29
30The classic example of where callbacks are used is when writing an
31event driven program like for an X windows application. In this case
32you register functions to be called whenever specific events occur,
33e.g., a mouse button is pressed, the cursor moves into a window or a
34menu item is selected.
35
36=back
37
38Although the techniques described here are applicable when embedding
39Perl in a C program, this is not the primary goal of this document.
40There are other details that must be considered and are specific to
41embedding Perl. For details on embedding Perl in C refer to
42L<perlembed>.
43
44Before you launch yourself head first into the rest of this document,
45it would be a good idea to have read the following two documents -
46L<perlxs> and L<perlguts>.
47
48=head1 THE CALL_ FUNCTIONS
49
50Although this stuff is easier to explain using examples, you first need
51be aware of a few important definitions.
52
53Perl has a number of C functions that allow you to call Perl
54subroutines. They are
55
56 I32 call_sv(SV* sv, I32 flags);
57 I32 call_pv(char *subname, I32 flags);
58 I32 call_method(char *methname, I32 flags);
59 I32 call_argv(char *subname, I32 flags, register char **argv);
60
61The key function is I<call_sv>. All the other functions are
62fairly simple wrappers which make it easier to call Perl subroutines in
63special cases. At the end of the day they will all call I<call_sv>
64to invoke the Perl subroutine.
65
66All the I<call_*> functions have a C<flags> parameter which is
67used to pass a bit mask of options to Perl. This bit mask operates
68identically for each of the functions. The settings available in the
69bit mask are discussed in L<FLAG VALUES>.
70
71Each of the functions will now be discussed in turn.
72
73=over 5
74
75=item call_sv
76
77I<call_sv> takes two parameters, the first, C<sv>, is an SV*.
78This allows you to specify the Perl subroutine to be called either as a
79C string (which has first been converted to an SV) or a reference to a
80subroutine. The section, I<Using call_sv>, shows how you can make
81use of I<call_sv>.
82
83=item call_pv
84
85The function, I<call_pv>, is similar to I<call_sv> except it
86expects its first parameter to be a C char* which identifies the Perl
87subroutine you want to call, e.g., C<call_pv("fred", 0)>. If the
88subroutine you want to call is in another package, just include the
89package name in the string, e.g., C<"pkg::fred">.
90
91=item call_method
92
93The function I<call_method> is used to call a method from a Perl
94class. The parameter C<methname> corresponds to the name of the method
95to be called. Note that the class that the method belongs to is passed
96on the Perl stack rather than in the parameter list. This class can be
97either the name of the class (for a static method) or a reference to an
98object (for a virtual method). See L<perlobj> for more information on
99static and virtual methods and L<Using call_method> for an example
100of using I<call_method>.
101
102=item call_argv
103
104I<call_argv> calls the Perl subroutine specified by the C string
105stored in the C<subname> parameter. It also takes the usual C<flags>
106parameter. The final parameter, C<argv>, consists of a NULL terminated
107list of C strings to be passed as parameters to the Perl subroutine.
108See I<Using call_argv>.
109
110=back
111
112All the functions return an integer. This is a count of the number of
113items returned by the Perl subroutine. The actual items returned by the
114subroutine are stored on the Perl stack.
115
116As a general rule you should I<always> check the return value from
117these functions. Even if you are expecting only a particular number of
118values to be returned from the Perl subroutine, there is nothing to
119stop someone from doing something unexpected--don't say you haven't
120been warned.
121
122=head1 FLAG VALUES
123
124The C<flags> parameter in all the I<call_*> functions is a bit mask
125which can consist of any combination of the symbols defined below,
126OR'ed together.
127
128
129=head2 G_VOID
130
131Calls the Perl subroutine in a void context.
132
133This flag has 2 effects:
134
135=over 5
136
137=item 1.
138
139It indicates to the subroutine being called that it is executing in
140a void context (if it executes I<wantarray> the result will be the
141undefined value).
142
143=item 2.
144
145It ensures that nothing is actually returned from the subroutine.
146
147=back
148
149The value returned by the I<call_*> function indicates how many
150items have been returned by the Perl subroutine - in this case it will
151be 0.
152
153
154=head2 G_SCALAR
155
156Calls the Perl subroutine in a scalar context. This is the default
157context flag setting for all the I<call_*> functions.
158
159This flag has 2 effects:
160
161=over 5
162
163=item 1.
164
165It indicates to the subroutine being called that it is executing in a
166scalar context (if it executes I<wantarray> the result will be false).
167
168=item 2.
169
170It ensures that only a scalar is actually returned from the subroutine.
171The subroutine can, of course, ignore the I<wantarray> and return a
172list anyway. If so, then only the last element of the list will be
173returned.
174
175=back
176
177The value returned by the I<call_*> function indicates how many
178items have been returned by the Perl subroutine - in this case it will
179be either 0 or 1.
180
181If 0, then you have specified the G_DISCARD flag.
182
183If 1, then the item actually returned by the Perl subroutine will be
184stored on the Perl stack - the section I<Returning a Scalar> shows how
185to access this value on the stack. Remember that regardless of how
186many items the Perl subroutine returns, only the last one will be
187accessible from the stack - think of the case where only one value is
188returned as being a list with only one element. Any other items that
189were returned will not exist by the time control returns from the
190I<call_*> function. The section I<Returning a list in a scalar
191context> shows an example of this behavior.
192
193
194=head2 G_ARRAY
195
196Calls the Perl subroutine in a list context.
197
198As with G_SCALAR, this flag has 2 effects:
199
200=over 5
201
202=item 1.
203
204It indicates to the subroutine being called that it is executing in a
205list context (if it executes I<wantarray> the result will be true).
206
207
208=item 2.
209
210It ensures that all items returned from the subroutine will be
211accessible when control returns from the I<call_*> function.
212
213=back
214
215The value returned by the I<call_*> function indicates how many
216items have been returned by the Perl subroutine.
217
218If 0, then you have specified the G_DISCARD flag.
219
220If not 0, then it will be a count of the number of items returned by
221the subroutine. These items will be stored on the Perl stack. The
222section I<Returning a list of values> gives an example of using the
223G_ARRAY flag and the mechanics of accessing the returned items from the
224Perl stack.
225
226=head2 G_DISCARD
227
228By default, the I<call_*> functions place the items returned from
229by the Perl subroutine on the stack. If you are not interested in
230these items, then setting this flag will make Perl get rid of them
231automatically for you. Note that it is still possible to indicate a
232context to the Perl subroutine by using either G_SCALAR or G_ARRAY.
233
234If you do not set this flag then it is I<very> important that you make
235sure that any temporaries (i.e., parameters passed to the Perl
236subroutine and values returned from the subroutine) are disposed of
237yourself. The section I<Returning a Scalar> gives details of how to
238dispose of these temporaries explicitly and the section I<Using Perl to
239dispose of temporaries> discusses the specific circumstances where you
240can ignore the problem and let Perl deal with it for you.
241
242=head2 G_NOARGS
243
244Whenever a Perl subroutine is called using one of the I<call_*>
245functions, it is assumed by default that parameters are to be passed to
246the subroutine. If you are not passing any parameters to the Perl
247subroutine, you can save a bit of time by setting this flag. It has
248the effect of not creating the C<@_> array for the Perl subroutine.
249
250Although the functionality provided by this flag may seem
251straightforward, it should be used only if there is a good reason to do
252so. The reason for being cautious is that even if you have specified
253the G_NOARGS flag, it is still possible for the Perl subroutine that
254has been called to think that you have passed it parameters.
255
256In fact, what can happen is that the Perl subroutine you have called
257can access the C<@_> array from a previous Perl subroutine. This will
258occur when the code that is executing the I<call_*> function has
259itself been called from another Perl subroutine. The code below
260illustrates this
261
262 sub fred
263 { print "@_\n" }
264
265 sub joe
266 { &fred }
267
268 &joe(1,2,3);
269
270This will print
271
272 1 2 3
273
274What has happened is that C<fred> accesses the C<@_> array which
275belongs to C<joe>.
276
277
278=head2 G_EVAL
279
280It is possible for the Perl subroutine you are calling to terminate
281abnormally, e.g., by calling I<die> explicitly or by not actually
282existing. By default, when either of these events occurs, the
283process will terminate immediately. If you want to trap this
284type of event, specify the G_EVAL flag. It will put an I<eval { }>
285around the subroutine call.
286
287Whenever control returns from the I<call_*> function you need to
288check the C<$@> variable as you would in a normal Perl script.
289
290The value returned from the I<call_*> function is dependent on
291what other flags have been specified and whether an error has
292occurred. Here are all the different cases that can occur:
293
294=over 5
295
296=item *
297
298If the I<call_*> function returns normally, then the value
299returned is as specified in the previous sections.
300
301=item *
302
303If G_DISCARD is specified, the return value will always be 0.
304
305=item *
306
307If G_ARRAY is specified I<and> an error has occurred, the return value
308will always be 0.
309
310=item *
311
312If G_SCALAR is specified I<and> an error has occurred, the return value
313will be 1 and the value on the top of the stack will be I<undef>. This
314means that if you have already detected the error by checking C<$@> and
315you want the program to continue, you must remember to pop the I<undef>
316from the stack.
317
318=back
319
320See I<Using G_EVAL> for details on using G_EVAL.
321
322=head2 G_KEEPERR
323
324You may have noticed that using the G_EVAL flag described above will
325B<always> clear the C<$@> variable and set it to a string describing
326the error iff there was an error in the called code. This unqualified
327resetting of C<$@> can be problematic in the reliable identification of
328errors using the C<eval {}> mechanism, because the possibility exists
329that perl will call other code (end of block processing code, for
330example) between the time the error causes C<$@> to be set within
331C<eval {}>, and the subsequent statement which checks for the value of
332C<$@> gets executed in the user's script.
333
334This scenario will mostly be applicable to code that is meant to be
335called from within destructors, asynchronous callbacks, signal
336handlers, C<__DIE__> or C<__WARN__> hooks, and C<tie> functions. In
337such situations, you will not want to clear C<$@> at all, but simply to
338append any new errors to any existing value of C<$@>.
339
340The G_KEEPERR flag is meant to be used in conjunction with G_EVAL in
341I<call_*> functions that are used to implement such code. This flag
342has no effect when G_EVAL is not used.
343
344When G_KEEPERR is used, any errors in the called code will be prefixed
345with the string "\t(in cleanup)", and appended to the current value
346of C<$@>. an error will not be appended if that same error string is
347already at the end of C<$@>.
348
349In addition, a warning is generated using the appended string. This can be
350disabled using C<no warnings 'misc'>.
351
352The G_KEEPERR flag was introduced in Perl version 5.002.
353
354See I<Using G_KEEPERR> for an example of a situation that warrants the
355use of this flag.
356
357=head2 Determining the Context
358
359As mentioned above, you can determine the context of the currently
360executing subroutine in Perl with I<wantarray>. The equivalent test
361can be made in C by using the C<GIMME_V> macro, which returns
362C<G_ARRAY> if you have been called in a list context, C<G_SCALAR> if
363in a scalar context, or C<G_VOID> if in a void context (i.e. the
364return value will not be used). An older version of this macro is
365called C<GIMME>; in a void context it returns C<G_SCALAR> instead of
366C<G_VOID>. An example of using the C<GIMME_V> macro is shown in
367section I<Using GIMME_V>.
368
369=head1 EXAMPLES
370
371Enough of the definition talk, let's have a few examples.
372
373Perl provides many macros to assist in accessing the Perl stack.
374Wherever possible, these macros should always be used when interfacing
375to Perl internals. We hope this should make the code less vulnerable
376to any changes made to Perl in the future.
377
378Another point worth noting is that in the first series of examples I
379have made use of only the I<call_pv> function. This has been done
380to keep the code simpler and ease you into the topic. Wherever
381possible, if the choice is between using I<call_pv> and
382I<call_sv>, you should always try to use I<call_sv>. See
383I<Using call_sv> for details.
384
385=head2 No Parameters, Nothing returned
386
387This first trivial example will call a Perl subroutine, I<PrintUID>, to
388print out the UID of the process.
389
390 sub PrintUID
391 {
392 print "UID is $<\n";
393 }
394
395and here is a C function to call it
396
397 static void
398 call_PrintUID()
399 {
400 dSP;
401
402 PUSHMARK(SP);
403 call_pv("PrintUID", G_DISCARD|G_NOARGS);
404 }
405
406Simple, eh.
407
408A few points to note about this example.
409
410=over 5
411
412=item 1.
413
414Ignore C<dSP> and C<PUSHMARK(SP)> for now. They will be discussed in
415the next example.
416
417=item 2.
418
419We aren't passing any parameters to I<PrintUID> so G_NOARGS can be
420specified.
421
422=item 3.
423
424We aren't interested in anything returned from I<PrintUID>, so
425G_DISCARD is specified. Even if I<PrintUID> was changed to
426return some value(s), having specified G_DISCARD will mean that they
427will be wiped by the time control returns from I<call_pv>.
428
429=item 4.
430
431As I<call_pv> is being used, the Perl subroutine is specified as a
432C string. In this case the subroutine name has been 'hard-wired' into the
433code.
434
435=item 5.
436
437Because we specified G_DISCARD, it is not necessary to check the value
438returned from I<call_pv>. It will always be 0.
439
440=back
441
442=head2 Passing Parameters
443
444Now let's make a slightly more complex example. This time we want to
445call a Perl subroutine, C<LeftString>, which will take 2 parameters--a
446string ($s) and an integer ($n). The subroutine will simply
447print the first $n characters of the string.
448
449So the Perl subroutine would look like this
450
451 sub LeftString
452 {
453 my($s, $n) = @_;
454 print substr($s, 0, $n), "\n";
455 }
456
457The C function required to call I<LeftString> would look like this.
458
459 static void
460 call_LeftString(a, b)
461 char * a;
462 int b;
463 {