This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perl5.001 patch.1e
[perl5.git] / pod / perlcall.pod
CommitLineData
a0d0e21e
LW
1=head1 NAME
2
3perlcall - Perl calling conventions from C
4
5=head1 DESCRIPTION
6
7B<WARNING : This document is still under construction.
8There are bound to be a number of inaccuracies, so tread very carefully for now.>
9
10The purpose of this document is to show you how to write I<callbacks>,
11i.e. how to call Perl from C. The main
12focus is on how to interface back to Perl from a bit of C code that has itself
13been run by Perl, i.e. the 'main' program is a Perl script; you are using it
14to execute
15a section of code written in C; that bit of C code wants you to do something
16with a particular event, so you want a Perl sub to be executed whenever it
17happens.
18
19Examples where this is necessary include
20
21=over 5
22
23=item *
24
25You have created an XSUB interface to an application's C API.
26
27A fairly common feature in applications is to allow you to define a C
28function that will get called whenever something nasty occurs.
29What we would like is for a Perl sub to be called instead.
30
31=item *
32
33The classic example of where callbacks are used is in an event driven program
34like for X-windows.
35In this case your register functions to be called whenever a specific events
36occur, e.g. a mouse button is pressed.
37
38=back
39
40Although the techniques described are applicable to embedding Perl
41in a C program, this is not the primary goal of this document. For details
42on embedding Perl in C refer to L<perlembed> (currently unwritten).
43
44Before you launch yourself head first into the rest of this document, it would
45be a good idea to have read the following two documents - L<perlapi> and L<perlguts>.
46
47This stuff is easier to explain using examples. But first here are a few
48definitions anyway.
49
50=head2 Definitions
51
52Perl has a number of C functions which allow you to call Perl subs. They are
53
54 I32 perl_call_sv(SV* sv, I32 flags) ;
55 I32 perl_call_pv(char *subname, I32 flags) ;
56 I32 perl_call_method(char *methname, I32 flags) ;
57 I32 perl_call_argv(char *subname, I32 flags, register char **argv) ;
58
59The key function is I<perl_call_sv>. All the other functions make use of
60I<perl_call_sv> to do what they do.
61
62I<perl_call_sv> takes two parameters, the first is an SV*. This allows you to
63specify the Perl sub to be called either as a C string (which has first been
64converted to an SV) or a reference to a
65sub. Example 7, shows you how you can make use of I<perl_call_sv>.
66The second parameter, C<flags>, is a general purpose option command.
67This parameter is common to all the I<perl_call_*> functions.
68It is discussed in the next section.
69
70The function, I<perl_call_pv>, is similar as I<perl_call_sv> except it
71expects it's first parameter has to be a C char* which identifies the Perl
72sub you want to call, e.g. C<perl_call_pv("fred", 0)>.
73
74The function I<perl_call_method> expects its first argument to contain a
75blessed reference to a class. Using that reference it looks up and calls C<methname>
76from that class. See example 9.
77
78I<perl_call_argv> calls the Perl sub specified by the C<subname> parameter.
79It also takes the usual C<flags> parameter.
80The final parameter, C<argv>, consists of a
81list of C strings to be sent to the Perl sub. See example 8.
82
83All the functions return a number. This is a count of the number of items
84returned by the Perl sub on the stack.
85
86As a general rule you should I<always> check the return value from these
87functions.
88Even if you are only expecting a particular number of values to be returned
89from the Perl sub, there is nothing to stop someone from doing something
90unexpected - don't say you havn't been warned.
91
92=head2 Flag Values
93
94The C<flags> parameter in all the I<perl_call_*> functions consists of any
95combination of the symbols defined below, OR'ed together.
96
97=over 5
98
99=item G_SCALAR
100
101Calls the Perl sub in a scalar context.
102
103Whatever the Perl sub actually returns, we only want a scalar. If the perl sub
104does return a scalar, the return value from the I<perl_call_*> function
105will be 1 or 0. If 1, then the value actually returned by the Perl sub will
106be contained
107on the top of the stack.
108If 0, then the sub has probably called I<die> or you have
109used the G_DISCARD flag.
110
111If the Perl sub returns a list, the I<perl_call_*> function will still
112only return 1 or 0. If 1, then the number of elements in the list
113will be stored on top of the stack.
114The actual values of the list will not be accessable.
115
116
117G_SCALAR is the default flag setting for all the functions.
118
119=item G_ARRAY
120
121Calls the Perl sub in a list context.
122
123The return code from the I<perl_call_*> functions will indicate how
124many elements of the stack are used to store the array.
125
126=item G_DISCARD
127
128If you are not interested in the values returned by the Perl sub then setting
129this flag will make Perl get rid of them automatically for you. This will take
130precedence to either G_SCALAR or G_ARRAY.
131
132If you do
133not set this flag then you may need to explicitly get rid of temporary values.
134See example 3 for details.
135
136=item G_NOARGS
137
138If you are not passing any parameters to the Perl sub, you can save a bit of
139time by setting this flag. It has the effect of of not creating the C<@_> array
140for the Perl sub.
141
142A point worth noting is that if this flag is specified the Perl sub called can
143still access an C<@_> array from a previous Perl sub.
144This functionality can be illustrated with the perl code below
145
146 sub fred
147 { print "@_\n" }
148
149 sub joe
150 { &fred }
151
152 &joe(1,2,3) ;
153
154This will print
155
156 1 2 3
157
158What has happened is that C<fred> accesses the C<@_> array which belongs to C<joe>.
159
160=item G_EVAL
161
162If the Perl sub you are calling has the ability to terminate
163abnormally, e.g. by calling I<die> or by not actually existing, and
164you want to catch this type of event, specify this flag setting. It will put
165an I<eval { }> around the sub call.
166
167Whenever control returns from the I<perl_call_*> function you need to
168check the C<$@> variable as you would in a normal Perl script.
169See example 6 for details of how to do this.
170
171
172=back
173
174
175=head1 EXAMPLES
176
177Enough of the definition talk, let's have a few examples.
178
179Perl provides many macros to assist in accessing the Perl stack.
180These macros should always be used when interfacing to Perl internals.
181Hopefully this should make the code less vulnerable to changes made to
182Perl in the future.
183
184Another point worth noting is that in the first series of examples I have
185only made use of the I<perl_call_pv> function.
186This has only been done to ease you into the
187topic. Wherever possible, if the choice is between using I<perl_call_pv>
188and I<perl_call_sv>, I would always try to use I<perl_call_sv>.
189
190The code for these examples is stored in the file F<perlcall.tar>.
191(Once this document settles down, all the example code will be available in the file).
192
193=head2 Example1: No Parameters, Nothing returned
194
195This first trivial example will call a Perl sub, I<PrintUID>, to print
196out the UID of the process.
197
198 sub PrintUID
199 {
200 print "UID is $<\n" ;
201 }
202
203and here is the C to call it
204
205 void
206 call_PrintUID()
207 {
208 dSP ;
209
210 PUSHMARK(sp) ;
211 perl_call_pv("PrintUID", G_DISCARD|G_NOARGS) ;
212 }
213
214Simple, eh.
215
216A few points to note about this example.
217
218=over 5
219
220=item 1.
221
222We aren't passing any parameters to I<PrintUID> so G_NOARGS
223can be specified.
224
225=item 2.
226
227Ignore C<dSP> and C<PUSHMARK(sp)> for now. They will be discussed in the next
228example.
229
230=item 3.
231
232We aren't interested in anything returned from I<PrintUID>, so
233G_DISCARD is specified. Even if I<PrintUID> was changed to actually
234return some value(s), having specified G_DISCARD will mean that they
235will be wiped by the time control returns from I<perl_call_pv>.
236
237=item 4.
238
239Because we specified G_DISCARD, it is not necessary to check
240the value returned from I<perl_call_sv>. It will always be 0.
241
242=item 5.
243
244As I<perl_call_pv> is being used, the Perl sub is specified as a C string.
245
246=back
247
248=head2 Example 2: Passing Parameters
249
250Now let's make a slightly more complex example. This time we want
251to call a Perl sub
252which will take 2 parameters - a string (C<$s>) and an integer (C<$n>).
253The sub will simply print the first C<$n> characters of the string.
254
255So the Perl sub would look like this
256
257 sub LeftString
258 {
259 my($s, $n) = @_ ;
260 print substr($s, 0, $n), "\n" ;
261 }
262
263The C function required to call I<LeftString> would look like this.
264
265 static void
266 call_LeftString(a, b)
267 char * a ;
268 int b ;
269 {
270 dSP ;
271
272 PUSHMARK(sp) ;
273 XPUSHs(sv_2mortal(newSVpv(a, 0)));
274 XPUSHs(sv_2mortal(newSViv(b)));
275 PUTBACK ;
276
277 perl_call_pv("LeftString", G_DISCARD);
278 }
279
280
281Here are a few notes on the C function I<call_LeftString>.
282
283=over 5
284
285=item 1.
286
287The only flag specified this time is G_DISCARD. As we are passing 2
288parameters to the Perl sub this time, we have not specified G_NOARGS.
289
290=item 2.
291
292Parameters are passed to the Perl sub using the Perl stack.
293This is the purpose of the code beginning with the line C<dSP> and ending
294with the line C<PUTBACK>.
295
296
297=item 3.
298
299If you are going to put something onto the Perl stack, you need to know
300where to put it. This is the purpose of the macro C<dSP> -
301it declares and initialises a local copy of the Perl stack pointer.
302
303All the other macros which will be used in this example require you to
304have used this macro.
305
306If you are calling a Perl sub directly from an XSUB function, it is
307not necessary to explicitly use the C<dSP> macro - it will be declared for you.
308
309=item 4.
310
311Any parameters to be pushed onto the stack should be bracketed by the
312C<PUSHMARK> and C<PUTBACK> macros.
313The purpose of these two macros, in this context, is to automatically count
314the number of parameters you are pushing. Then whenever Perl is creating
315the C<@_> array for the sub, it knows how big to make it.
316
317The C<PUSHMARK> macro tells Perl to make a mental note of the current stack
318pointer. Even if you aren't passing any parameters (like in Example 1) you must
319still call the C<PUSHMARK> macro before you can call any of
320the I<perl_call_*> functions - Perl still needs to know that there are
321no parameters.
322
323The C<PUTBACK> macro sets the global copy of the stack pointer to be the
324same as our local copy. If we didn't do this I<perl_call_pv> wouldn't
325know where the two parameters we pushed were - remember that up to now
326all the stack pointer manipulation we have done is with our local copy,
327I<not> the global copy.
328
329=item 5.
330
331Next, we come to XPUSHs. This is where the parameters actually get
332pushed onto the stack. In this case we are pushing a string and an integer.
333
334See the section I<XSUB's AND THE ARGUMENT STACK> in L<perlguts> for
335details on how the XPUSH macros work.
336
337=item 6.
338
339Finally, I<LeftString> can now be called via the I<perl_call_pv> function.
340
341=back
342
343=head2 Example 3: Returning a Scalar
344
345Now for an example of dealing with the values returned from a Perl sub.
346
347Here is a Perl sub, I<Adder>, which takes 2 integer parameters and simply
348returns their sum.
349
350 sub Adder
351 {
352 my($a, $b) = @_ ;
353 $a + $b ;
354 }
355
356As we are now concerned with the return value from I<Adder>, the C function
357is now a bit more complex.
358
359 static void
360 call_Adder(a, b)
361 int a ;
362 int b ;
363 {
364 dSP ;
365 int count ;
366
367 ENTER ;
368 SAVETMPS;
369
370 PUSHMARK(sp) ;
371 XPUSHs(sv_2mortal(newSViv(a)));
372 XPUSHs(sv_2mortal(newSViv(b)));
373 PUTBACK ;
374
375 count = perl_call_pv("Adder", G_SCALAR);
376
377 SPAGAIN ;
378
379 if (count != 1)
380 croak("Big trouble\n") ;
381
382 printf ("The sum of %d and %d is %d\n", a, b, POPi) ;
383
384 PUTBACK ;
385 FREETMPS ;
386 LEAVE ;
387 }
388
389
390Points to note this time are
391
392=over 5
393
394=item 1.
395
396The only flag specified this time was G_SCALAR. That means the @_ array
397will be created and that the value returned by I<Adder> will still
398exist after the call to I<perl_call_pv>.
399
400
401
402=item 2.
403
404Because we are interested in what is returned from I<Adder> we cannot specify
405G_DISCARD. This means that we will have to tidy up the Perl stack and dispose
406of any temporary values ourselves. This is the purpose of
407
408 ENTER ;
409 SAVETMPS ;
410
411at the start of the function, and
412
413 FREETMPS ;
414 LEAVE ;
415
416at the end. The C<ENTER>/C<SAVETMPS> pair creates a boundary for any
417temporaries we create.
418This means that the temporaries we get rid of will be limited to those which
419were created after these calls.
420
421The C<FREETMPS>/C<LEAVE> pair will get rid of any values returned by the Perl
422sub, plus it will also dump the mortal SV's we created.
423Having C<ENTER>/C<SAVETMPS> at the beginning
424of the code makes sure that no other mortals are destroyed.
425
426=item 3.
427
428The purpose of the macro C<SPAGAIN> is to refresh the local copy of the
429stack pointer. This is necessary because it is possible that the memory
430allocated to the Perl stack has been re-allocated whilst in the I<perl_call_pv>
431call.
432
433If you are making use of the Perl stack pointer in your code you must always
434refresh the your local copy using SPAGAIN whenever you make use of
435of the I<perl_call_*> functions or any other Perl internal function.
436
437=item 4.
438
439Although only a single value was expected to be returned from I<Adder>, it is
440still good practice to check the return code from I<perl_call_pv> anyway.
441
442Expecting a single value is not quite the same as knowing that there will
443be one. If someone modified I<Adder> to return a list and we didn't check
444for that possibility and take appropriate action the Perl stack would end
445up in an inconsistant state. That is something you I<really> don't want
446to ever happen.
447
448=item 5.
449
450The C<POPi> macro is used here to pop the return value from the stack. In this
451case we wanted an integer, so C<POPi> was used.
452
453
454Here is the complete list of POP macros available, along with the types they
455return.
456
457 POPs SV
458 POPp pointer
459 POPn double
460 POPi integer
461 POPl long
462
463=item 6.
464
465The final C<PUTBACK> is used to leave the Perl stack in a consistant state
466before exiting the function. This is
467necessary because when we popped the return value from the stack with C<POPi> it
468only updated our local copy of the stack pointer. Remember, C<PUTBACK> sets the
469global stack pointer to be the same as our local copy.
470
471=back
472
473
474=head2 Example 4: Returning a list of values
475
476Now, let's extend the previous example to return both the sum of the parameters
477and the difference.
478
479Here is the Perl sub
480
481 sub AddSubtract
482 {
483 my($a, $b) = @_ ;
484 ($a+$b, $a-$b) ;
485 }
486
487
488and this is the C function
489
490 static void
491 call_AddSubtract(a, b)
492 int a ;
493 int b ;
494 {
495 dSP ;
496 int count ;
497
498 ENTER ;
499 SAVETMPS;
500
501 PUSHMARK(sp) ;
502 XPUSHs(sv_2mortal(newSViv(a)));
503 XPUSHs(sv_2mortal(newSViv(b)));
504 PUTBACK ;
505
506 count = perl_call_pv("AddSubtract", G_ARRAY);
507
508 SPAGAIN ;
509
510 if (count != 2)
511 croak("Big trouble\n") ;
512
513 printf ("%d - %d = %d\n", a, b, POPi) ;
514 printf ("%d + %d = %d\n", a, b, POPi) ;
515
516 PUTBACK ;
517 FREETMPS ;
518 LEAVE ;
519 }
520
521
522Notes
523
524=over 5
525
526=item 1.
527
528We wanted array context, so we used G_ARRAY.
529
530=item 2.
531
532Not surprisingly there are 2 POPi's this time because we were retrieving 2
533values from the stack. The main point to note is that they came off the stack in
534reverse order.
535
536=back
537
538=head2 Example 5: Returning Data from Perl via the parameter list
539
540It is also possible to return values directly via the parameter list -
541whether it is actually desirable to do it is another matter entirely.
542
543The Perl sub, I<Inc>, below takes 2 parameters and increments each.
544
545 sub Inc
546 {
547 ++ $_[0] ;
548 ++ $_[1] ;
549 }
550
551and here is a C function to call it.
552
553 static void
554 call_Inc(a, b)
555 int a ;
556 int b ;
557 {
558 dSP ;
559 int count ;
560 SV * sva ;
561 SV * svb ;
562
563 ENTER ;
564 SAVETMPS;
565
566 sva = sv_2mortal(newSViv(a)) ;
567 svb = sv_2mortal(newSViv(b)) ;
568
569 PUSHMARK(sp) ;
570 XPUSHs(sva);
571 XPUSHs(svb);
572 PUTBACK ;
573
574 count = perl_call_pv("Inc", G_DISCARD);
575
576 if (count != 0)
577 croak ("call_Inc : expected 0 return value from 'Inc', got %d\n", count) ;
578
579 printf ("%d + 1 = %d\n", a, SvIV(sva)) ;
580 printf ("%d + 1 = %d\n", b, SvIV(svb)) ;
581
582 FREETMPS ;
583 LEAVE ;
584 }
585
586
587
588To be able to access the two parameters that were pushed onto the stack
589after they return from I<perl_call_pv> it is necessary to make a note of
590their addresses - thus the two variables C<sva> and C<svb>.
591
592The reason this is necessary is that
593the area of the Perl stack which held them
594will very likely have been overwritten by something else by the time control
595returns from I<perl_call_pv>.
596
597
598
599
600=head2 Example 6: Using G_EVAL
601
602Now an example using G_EVAL. Below is a Perl sub which computes the
603difference of its 2 parameters. If this would result in a negative result,
604the sub calls I<die>.
605
606
607 sub Subtract
608 {
609 my ($a, $b) = @_ ;
610
611 die "death can be fatal\n" if $a < $b ;
612
613 $a - $b ;
614 }
615
616and some C to call it
617
618 static void
619 call_Subtract(a, b)
620 int a ;
621 int b ;
622 {
623 dSP ;
624 int count ;
625 SV * sv ;
626
627 ENTER ;
628 SAVETMPS;
629
630 PUSHMARK(sp) ;
631 XPUSHs(sv_2mortal(newSViv(a)));
632 XPUSHs(sv_2mortal(newSViv(b)));
633 PUTBACK ;
634
635 count = perl_call_pv("Subtract", G_EVAL|G_SCALAR);
636
637 /* Check the eval first */
638 sv = GvSV(gv_fetchpv("@", TRUE, SVt_PV));
639 if (SvTRUE(sv))
640 printf ("Uh oh - %s\n", SvPV(sv, na)) ;
641
642 SPAGAIN ;
643
644 if (count != 1)
645 croak ("call_Subtract : expected 1 return value from 'Subtract', got %d\n", count) ;
646
647
648 printf ("%d - %d = %d\n", a, b, POPi) ;
649
650 PUTBACK ;
651 FREETMPS ;
652 LEAVE ;
653
654 }
655
656If I<call_Subtract> is called thus
657
658 call_Subtract(4, 5)
659
660the following will be printed
661
662 Uh oh - death can be fatal
663
664Notes
665
666=over 5
667
668=item 1.
669
670We want to be able to catch the I<die> so we have used the G_EVAL flag.
671Not specifying this flag would mean that the program would terminate.
672
673=item 2.
674
675The code
676
677 sv = GvSV(gv_fetchpv("@", TRUE, SVt_PV));
678 if (SvTRUE(sv))
679 printf ("Uh oh - %s\n", SvPVx(sv, na)) ;
680
681is the equivalent of this bit of Perl
682
683 print "Uh oh - $@\n" if $@ ;
684
685
686
687=back
688
689
690=head2 Example 7: Using perl_call_sv
691
692In all the previous examples I have 'hard-wried' the name of the Perl sub to
693be called from C.
694Sometimes though, it is necessary to be able to specify the name
695of the Perl sub from within the Perl script.
696
697Consider the Perl code below
698
699 sub fred
700 {
701 print "Hello there\n" ;
702 }
703
704 CallSub("fred") ;
705
706
707here is a snippet of XSUB which defines I<CallSub>.
708
709 void
710 CallSub(name)
711 char * name
712 CODE:
713 PUSHMARK(sp) ;
714 perl_call_pv(name, G_DISCARD|G_NOARGS) ;
715
716That is fine as far as it goes. The thing is, it only allows the Perl sub to be
717specified as a string.
718For perl 4 this was adequate, but Perl 5 allows references to
719subs and anonymous subs. This is where I<perl_call_sv> is useful.
720
721The code below for I<CallSub> is identical to the previous time except that the
722C<name> parameter is now defined as an SV* and we use I<perl_call_sv> instead of
723I<perl_call_pv>.
724
725 void
726 CallSub(name)
727 SV* name
728 CODE:
729 PUSHMARK(sp) ;
730 perl_call_sv(name, G_DISCARD|G_NOARGS) ;
731
732As we are using an SV to call I<fred> the following can all be used
733
734 CallSub("fred") ;
735 Callsub(\&fred) ;
736 $ref = \&fred ;
737 CallSub($ref) ;
738 CallSub( sub { print "Hello there\n" } ) ;
739
740As you can see, I<perl_call_sv> gives you greater flexibility in how you
741can specify the Perl sub.
742
743=head2 Example 8: Using perl_call_argv
744
745Here is a Perl sub which prints whatever parameters are passed to it.
746
747 sub PrintList
748 {
749 my(@list) = @_ ;
750
751 foreach (@list) { print "$_\n" }
752 }
753
754and here is an example of I<perl_call_argv> which will call I<PrintList>.
755
756 call_PrintList
757 {
758 dSP ;
759 char * words[] = {"alpha", "beta", "gamma", "delta", NULL } ;
760
761 perl_call_argv("PrintList", words, G_DISCARD) ;
762 }
763
764Note that it is not necessary to call C<PUSHMARK> in this instance. This is
765because I<perl_call_argv> will do it for you.
766
767=head2 Example 9: Using perl_call_method
768
769[This section is under construction]
770
771Consider the following Perl code
772
773 {
774 package Mine ;
775
776 sub new { bless [@_] }
777 sub Display { print $_[0][1], "\n" }
778 }
779
780 $a = new Mine ('red', 'green', 'blue') ;
781 call_Display($a, 'Display') ;
782
783The method C<Display> just prints out the first element of the list.
784Here is a XSUB implementation of I<call_Display>.
785
786 void
787 call_Display(ref, method)
788 SV * ref
789 char * method
790 CODE:
791 PUSHMARK(sp);
792 XPUSHs(ref);
793 PUTBACK;
794
795 perl_call_method(method, G_DISCARD) ;
796
797
798
799
800=head2 Strategies for storing Context Information
801
802[This section is under construction]
803
804One of the trickiest problems to overcome when designing a callback interface
805is figuring
806out how to store the mapping between the C callback functions and the
807Perl equivalent.
808
809Consider the following example.
810
811=head2 Alternate Stack Manipulation
812
813[This section is under construction]
814
815Although I have only made use of the POP* macros to access values returned
816from Perl subs, it is also possible to bypass these macros and read the
817stack directly.
818
819The code below is example 4 recoded to
820
821=head1 SEE ALSO
822
823L<perlapi>, L<perlguts>, L<perlembed>
824
825=head1 AUTHOR
826
827Paul Marquess <pmarquess@bfsec.bt.co.uk>
828
829Special thanks to the following people who assisted in the creation of the
830document.
831
832Jeff Okamoto, Tim Bunce.
833
834=head1 DATE
835
836Version 0.4, 17th October 1994
837
838