1N/A=head1 NAME
1N/A
1N/Aperlcall - Perl calling conventions from C
1N/A
1N/A=head1 DESCRIPTION
1N/A
1N/AThe purpose of this document is to show you how to call Perl subroutines
1N/Adirectly from C, i.e., how to write I<callbacks>.
1N/A
1N/AApart from discussing the C interface provided by Perl for writing
1N/Acallbacks the document uses a series of examples to show how the
1N/Ainterface actually works in practice. In addition some techniques for
1N/Acoding callbacks are covered.
1N/A
1N/AExamples where callbacks are necessary include
1N/A
1N/A=over 5
1N/A
1N/A=item * An Error Handler
1N/A
1N/AYou have created an XSUB interface to an application's C API.
1N/A
1N/AA fairly common feature in applications is to allow you to define a C
1N/Afunction that will be called whenever something nasty occurs. What we
1N/Awould like is to be able to specify a Perl subroutine that will be
1N/Acalled instead.
1N/A
1N/A=item * An Event Driven Program
1N/A
1N/AThe classic example of where callbacks are used is when writing an
1N/Aevent driven program like for an X windows application. In this case
1N/Ayou register functions to be called whenever specific events occur,
1N/Ae.g., a mouse button is pressed, the cursor moves into a window or a
1N/Amenu item is selected.
1N/A
1N/A=back
1N/A
1N/AAlthough the techniques described here are applicable when embedding
1N/APerl in a C program, this is not the primary goal of this document.
1N/AThere are other details that must be considered and are specific to
1N/Aembedding Perl. For details on embedding Perl in C refer to
1N/AL<perlembed>.
1N/A
1N/ABefore you launch yourself head first into the rest of this document,
1N/Ait would be a good idea to have read the following two documents -
1N/AL<perlxs> and L<perlguts>.
1N/A
1N/A=head1 THE CALL_ FUNCTIONS
1N/A
1N/AAlthough this stuff is easier to explain using examples, you first need
1N/Abe aware of a few important definitions.
1N/A
1N/APerl has a number of C functions that allow you to call Perl
1N/Asubroutines. They are
1N/A
1N/A I32 call_sv(SV* sv, I32 flags) ;
1N/A I32 call_pv(char *subname, I32 flags) ;
1N/A I32 call_method(char *methname, I32 flags) ;
1N/A I32 call_argv(char *subname, I32 flags, register char **argv) ;
1N/A
1N/AThe key function is I<call_sv>. All the other functions are
1N/Afairly simple wrappers which make it easier to call Perl subroutines in
1N/Aspecial cases. At the end of the day they will all call I<call_sv>
1N/Ato invoke the Perl subroutine.
1N/A
1N/AAll the I<call_*> functions have a C<flags> parameter which is
1N/Aused to pass a bit mask of options to Perl. This bit mask operates
1N/Aidentically for each of the functions. The settings available in the
1N/Abit mask are discussed in L<FLAG VALUES>.
1N/A
1N/AEach of the functions will now be discussed in turn.
1N/A
1N/A=over 5
1N/A
1N/A=item call_sv
1N/A
1N/AI<call_sv> takes two parameters, the first, C<sv>, is an SV*.
1N/AThis allows you to specify the Perl subroutine to be called either as a
1N/AC string (which has first been converted to an SV) or a reference to a
1N/Asubroutine. The section, I<Using call_sv>, shows how you can make
1N/Ause of I<call_sv>.
1N/A
1N/A=item call_pv
1N/A
1N/AThe function, I<call_pv>, is similar to I<call_sv> except it
1N/Aexpects its first parameter to be a C char* which identifies the Perl
1N/Asubroutine you want to call, e.g., C<call_pv("fred", 0)>. If the
1N/Asubroutine you want to call is in another package, just include the
1N/Apackage name in the string, e.g., C<"pkg::fred">.
1N/A
1N/A=item call_method
1N/A
1N/AThe function I<call_method> is used to call a method from a Perl
1N/Aclass. The parameter C<methname> corresponds to the name of the method
1N/Ato be called. Note that the class that the method belongs to is passed
1N/Aon the Perl stack rather than in the parameter list. This class can be
1N/Aeither the name of the class (for a static method) or a reference to an
1N/Aobject (for a virtual method). See L<perlobj> for more information on
1N/Astatic and virtual methods and L<Using call_method> for an example
1N/Aof using I<call_method>.
1N/A
1N/A=item call_argv
1N/A
1N/AI<call_argv> calls the Perl subroutine specified by the C string
1N/Astored in the C<subname> parameter. It also takes the usual C<flags>
1N/Aparameter. The final parameter, C<argv>, consists of a NULL terminated
1N/Alist of C strings to be passed as parameters to the Perl subroutine.
1N/ASee I<Using call_argv>.
1N/A
1N/A=back
1N/A
1N/AAll the functions return an integer. This is a count of the number of
1N/Aitems returned by the Perl subroutine. The actual items returned by the
1N/Asubroutine are stored on the Perl stack.
1N/A
1N/AAs a general rule you should I<always> check the return value from
1N/Athese functions. Even if you are expecting only a particular number of
1N/Avalues to be returned from the Perl subroutine, there is nothing to
1N/Astop someone from doing something unexpected--don't say you haven't
1N/Abeen warned.
1N/A
1N/A=head1 FLAG VALUES
1N/A
1N/AThe C<flags> parameter in all the I<call_*> functions is a bit mask
1N/Awhich can consist of any combination of the symbols defined below,
1N/AOR'ed together.
1N/A
1N/A
1N/A=head2 G_VOID
1N/A
1N/ACalls the Perl subroutine in a void context.
1N/A
1N/AThis flag has 2 effects:
1N/A
1N/A=over 5
1N/A
1N/A=item 1.
1N/A
1N/AIt indicates to the subroutine being called that it is executing in
1N/Aa void context (if it executes I<wantarray> the result will be the
1N/Aundefined value).
1N/A
1N/A=item 2.
1N/A
1N/AIt ensures that nothing is actually returned from the subroutine.
1N/A
1N/A=back
1N/A
1N/AThe value returned by the I<call_*> function indicates how many
1N/Aitems have been returned by the Perl subroutine - in this case it will
1N/Abe 0.
1N/A
1N/A
1N/A=head2 G_SCALAR
1N/A
1N/ACalls the Perl subroutine in a scalar context. This is the default
1N/Acontext flag setting for all the I<call_*> functions.
1N/A
1N/AThis flag has 2 effects:
1N/A
1N/A=over 5
1N/A
1N/A=item 1.
1N/A
1N/AIt indicates to the subroutine being called that it is executing in a
1N/Ascalar context (if it executes I<wantarray> the result will be false).
1N/A
1N/A=item 2.
1N/A
1N/AIt ensures that only a scalar is actually returned from the subroutine.
1N/AThe subroutine can, of course, ignore the I<wantarray> and return a
1N/Alist anyway. If so, then only the last element of the list will be
1N/Areturned.
1N/A
1N/A=back
1N/A
1N/AThe value returned by the I<call_*> function indicates how many
1N/Aitems have been returned by the Perl subroutine - in this case it will
1N/Abe either 0 or 1.
1N/A
1N/AIf 0, then you have specified the G_DISCARD flag.
1N/A
1N/AIf 1, then the item actually returned by the Perl subroutine will be
1N/Astored on the Perl stack - the section I<Returning a Scalar> shows how
1N/Ato access this value on the stack. Remember that regardless of how
1N/Amany items the Perl subroutine returns, only the last one will be
1N/Aaccessible from the stack - think of the case where only one value is
1N/Areturned as being a list with only one element. Any other items that
1N/Awere returned will not exist by the time control returns from the
1N/AI<call_*> function. The section I<Returning a list in a scalar
1N/Acontext> shows an example of this behavior.
1N/A
1N/A
1N/A=head2 G_ARRAY
1N/A
1N/ACalls the Perl subroutine in a list context.
1N/A
1N/AAs with G_SCALAR, this flag has 2 effects:
1N/A
1N/A=over 5
1N/A
1N/A=item 1.
1N/A
1N/AIt indicates to the subroutine being called that it is executing in a
1N/Alist context (if it executes I<wantarray> the result will be true).
1N/A
1N/A
1N/A=item 2.
1N/A
1N/AIt ensures that all items returned from the subroutine will be
1N/Aaccessible when control returns from the I<call_*> function.
1N/A
1N/A=back
1N/A
1N/AThe value returned by the I<call_*> function indicates how many
1N/Aitems have been returned by the Perl subroutine.
1N/A
1N/AIf 0, then you have specified the G_DISCARD flag.
1N/A
1N/AIf not 0, then it will be a count of the number of items returned by
1N/Athe subroutine. These items will be stored on the Perl stack. The
1N/Asection I<Returning a list of values> gives an example of using the
1N/AG_ARRAY flag and the mechanics of accessing the returned items from the
1N/APerl stack.
1N/A
1N/A=head2 G_DISCARD
1N/A
1N/ABy default, the I<call_*> functions place the items returned from
1N/Aby the Perl subroutine on the stack. If you are not interested in
1N/Athese items, then setting this flag will make Perl get rid of them
1N/Aautomatically for you. Note that it is still possible to indicate a
1N/Acontext to the Perl subroutine by using either G_SCALAR or G_ARRAY.
1N/A
1N/AIf you do not set this flag then it is I<very> important that you make
1N/Asure that any temporaries (i.e., parameters passed to the Perl
1N/Asubroutine and values returned from the subroutine) are disposed of
1N/Ayourself. The section I<Returning a Scalar> gives details of how to
1N/Adispose of these temporaries explicitly and the section I<Using Perl to
1N/Adispose of temporaries> discusses the specific circumstances where you
1N/Acan ignore the problem and let Perl deal with it for you.
1N/A
1N/A=head2 G_NOARGS
1N/A
1N/AWhenever a Perl subroutine is called using one of the I<call_*>
1N/Afunctions, it is assumed by default that parameters are to be passed to
1N/Athe subroutine. If you are not passing any parameters to the Perl
1N/Asubroutine, you can save a bit of time by setting this flag. It has
1N/Athe effect of not creating the C<@_> array for the Perl subroutine.
1N/A
1N/AAlthough the functionality provided by this flag may seem
1N/Astraightforward, it should be used only if there is a good reason to do
1N/Aso. The reason for being cautious is that even if you have specified
1N/Athe G_NOARGS flag, it is still possible for the Perl subroutine that
1N/Ahas been called to think that you have passed it parameters.
1N/A
1N/AIn fact, what can happen is that the Perl subroutine you have called
1N/Acan access the C<@_> array from a previous Perl subroutine. This will
1N/Aoccur when the code that is executing the I<call_*> function has
1N/Aitself been called from another Perl subroutine. The code below
1N/Aillustrates this
1N/A
1N/A sub fred
1N/A { print "@_\n" }
1N/A
1N/A sub joe
1N/A { &fred }
1N/A
1N/A &joe(1,2,3) ;
1N/A
1N/AThis will print
1N/A
1N/A 1 2 3
1N/A
1N/AWhat has happened is that C<fred> accesses the C<@_> array which
1N/Abelongs to C<joe>.
1N/A
1N/A
1N/A=head2 G_EVAL
1N/A
1N/AIt is possible for the Perl subroutine you are calling to terminate
1N/Aabnormally, e.g., by calling I<die> explicitly or by not actually
1N/Aexisting. By default, when either of these events occurs, the
1N/Aprocess will terminate immediately. If you want to trap this
1N/Atype of event, specify the G_EVAL flag. It will put an I<eval { }>
1N/Aaround the subroutine call.
1N/A
1N/AWhenever control returns from the I<call_*> function you need to
1N/Acheck the C<$@> variable as you would in a normal Perl script.
1N/A
1N/AThe value returned from the I<call_*> function is dependent on
1N/Awhat other flags have been specified and whether an error has
1N/Aoccurred. Here are all the different cases that can occur:
1N/A
1N/A=over 5
1N/A
1N/A=item *
1N/A
1N/AIf the I<call_*> function returns normally, then the value
1N/Areturned is as specified in the previous sections.
1N/A
1N/A=item *
1N/A
1N/AIf G_DISCARD is specified, the return value will always be 0.
1N/A
1N/A=item *
1N/A
1N/AIf G_ARRAY is specified I<and> an error has occurred, the return value
1N/Awill always be 0.
1N/A
1N/A=item *
1N/A
1N/AIf G_SCALAR is specified I<and> an error has occurred, the return value
1N/Awill be 1 and the value on the top of the stack will be I<undef>. This
1N/Ameans that if you have already detected the error by checking C<$@> and
1N/Ayou want the program to continue, you must remember to pop the I<undef>
1N/Afrom the stack.
1N/A
1N/A=back
1N/A
1N/ASee I<Using G_EVAL> for details on using G_EVAL.
1N/A
1N/A=head2 G_KEEPERR
1N/A
1N/AYou may have noticed that using the G_EVAL flag described above will
1N/AB<always> clear the C<$@> variable and set it to a string describing
1N/Athe error iff there was an error in the called code. This unqualified
1N/Aresetting of C<$@> can be problematic in the reliable identification of
1N/Aerrors using the C<eval {}> mechanism, because the possibility exists
1N/Athat perl will call other code (end of block processing code, for
1N/Aexample) between the time the error causes C<$@> to be set within
1N/AC<eval {}>, and the subsequent statement which checks for the value of
1N/AC<$@> gets executed in the user's script.
1N/A
1N/AThis scenario will mostly be applicable to code that is meant to be
1N/Acalled from within destructors, asynchronous callbacks, signal
1N/Ahandlers, C<__DIE__> or C<__WARN__> hooks, and C<tie> functions. In
1N/Asuch situations, you will not want to clear C<$@> at all, but simply to
1N/Aappend any new errors to any existing value of C<$@>.
1N/A
1N/AThe G_KEEPERR flag is meant to be used in conjunction with G_EVAL in
1N/AI<call_*> functions that are used to implement such code. This flag
1N/Ahas no effect when G_EVAL is not used.
1N/A
1N/AWhen G_KEEPERR is used, any errors in the called code will be prefixed
1N/Awith the string "\t(in cleanup)", and appended to the current value
1N/Aof C<$@>.
1N/A
1N/AThe G_KEEPERR flag was introduced in Perl version 5.002.
1N/A
1N/ASee I<Using G_KEEPERR> for an example of a situation that warrants the
1N/Ause of this flag.
1N/A
1N/A=head2 Determining the Context
1N/A
1N/AAs mentioned above, you can determine the context of the currently
1N/Aexecuting subroutine in Perl with I<wantarray>. The equivalent test
1N/Acan be made in C by using the C<GIMME_V> macro, which returns
1N/AC<G_ARRAY> if you have been called in a list context, C<G_SCALAR> if
1N/Ain a scalar context, or C<G_VOID> if in a void context (i.e. the
1N/Areturn value will not be used). An older version of this macro is
1N/Acalled C<GIMME>; in a void context it returns C<G_SCALAR> instead of
1N/AC<G_VOID>. An example of using the C<GIMME_V> macro is shown in
1N/Asection I<Using GIMME_V>.
1N/A
1N/A=head1 KNOWN PROBLEMS
1N/A
1N/AThis section outlines all known problems that exist in the
1N/AI<call_*> functions.
1N/A
1N/A=over 5
1N/A
1N/A=item 1.
1N/A
1N/AIf you are intending to make use of both the G_EVAL and G_SCALAR flags
1N/Ain your code, use a version of Perl greater than 5.000. There is a bug
1N/Ain version 5.000 of Perl which means that the combination of these two
1N/Aflags will not work as described in the section I<FLAG VALUES>.
1N/A
1N/ASpecifically, if the two flags are used when calling a subroutine and
1N/Athat subroutine does not call I<die>, the value returned by
1N/AI<call_*> will be wrong.
1N/A
1N/A
1N/A=item 2.
1N/A
1N/AIn Perl 5.000 and 5.001 there is a problem with using I<call_*> if
1N/Athe Perl sub you are calling attempts to trap a I<die>.
1N/A
1N/AThe symptom of this problem is that the called Perl sub will continue
1N/Ato completion, but whenever it attempts to pass control back to the
1N/AXSUB, the program will immediately terminate.
1N/A
1N/AFor example, say you want to call this Perl sub
1N/A
1N/A sub fred
1N/A {
1N/A eval { die "Fatal Error" ; }
1N/A print "Trapped error: $@\n"
1N/A if $@ ;
1N/A }
1N/A
1N/Avia this XSUB
1N/A
1N/A void
1N/A Call_fred()
1N/A CODE:
1N/A PUSHMARK(SP) ;
1N/A call_pv("fred", G_DISCARD|G_NOARGS) ;
1N/A fprintf(stderr, "back in Call_fred\n") ;
1N/A
1N/AWhen C<Call_fred> is executed it will print
1N/A
1N/A Trapped error: Fatal Error
1N/A
1N/AAs control never returns to C<Call_fred>, the C<"back in Call_fred">
1N/Astring will not get printed.
1N/A
1N/ATo work around this problem, you can either upgrade to Perl 5.002 or
1N/Ahigher, or use the G_EVAL flag with I<call_*> as shown below
1N/A
1N/A void
1N/A Call_fred()
1N/A CODE:
1N/A PUSHMARK(SP) ;
1N/A call_pv("fred", G_EVAL|G_DISCARD|G_NOARGS) ;
1N/A fprintf(stderr, "back in Call_fred\n") ;
1N/A
1N/A=back
1N/A
1N/A
1N/A
1N/A=head1 EXAMPLES
1N/A
1N/AEnough of the definition talk, let's have a few examples.
1N/A
1N/APerl provides many macros to assist in accessing the Perl stack.
1N/AWherever possible, these macros should always be used when interfacing
1N/Ato Perl internals. We hope this should make the code less vulnerable
1N/Ato any changes made to Perl in the future.
1N/A
1N/AAnother point worth noting is that in the first series of examples I
1N/Ahave made use of only the I<call_pv> function. This has been done
1N/Ato keep the code simpler and ease you into the topic. Wherever
1N/Apossible, if the choice is between using I<call_pv> and
1N/AI<call_sv>, you should always try to use I<call_sv>. See
1N/AI<Using call_sv> for details.
1N/A
1N/A=head2 No Parameters, Nothing returned
1N/A
1N/AThis first trivial example will call a Perl subroutine, I<PrintUID>, to
1N/Aprint out the UID of the process.
1N/A
1N/A sub PrintUID
1N/A {
1N/A print "UID is $<\n" ;
1N/A }
1N/A
1N/Aand here is a C function to call it
1N/A
1N/A static void
1N/A call_PrintUID()
1N/A {
1N/A dSP ;
1N/A
1N/A PUSHMARK(SP) ;
1N/A call_pv("PrintUID", G_DISCARD|G_NOARGS) ;
1N/A }
1N/A
1N/ASimple, eh.
1N/A
1N/AA few points to note about this example.
1N/A
1N/A=over 5
1N/A
1N/A=item 1.
1N/A
1N/AIgnore C<dSP> and C<PUSHMARK(SP)> for now. They will be discussed in
1N/Athe next example.
1N/A
1N/A=item 2.
1N/A
1N/AWe aren't passing any parameters to I<PrintUID> so G_NOARGS can be
1N/Aspecified.
1N/A
1N/A=item 3.
1N/A
1N/AWe aren't interested in anything returned from I<PrintUID>, so
1N/AG_DISCARD is specified. Even if I<PrintUID> was changed to
1N/Areturn some value(s), having specified G_DISCARD will mean that they
1N/Awill be wiped by the time control returns from I<call_pv>.
1N/A
1N/A=item 4.
1N/A
1N/AAs I<call_pv> is being used, the Perl subroutine is specified as a
1N/AC string. In this case the subroutine name has been 'hard-wired' into the
1N/Acode.
1N/A
1N/A=item 5.
1N/A
1N/ABecause we specified G_DISCARD, it is not necessary to check the value
1N/Areturned from I<call_pv>. It will always be 0.
1N/A
1N/A=back
1N/A
1N/A=head2 Passing Parameters
1N/A
1N/ANow let's make a slightly more complex example. This time we want to
1N/Acall a Perl subroutine, C<LeftString>, which will take 2 parameters--a
1N/Astring ($s) and an integer ($n). The subroutine will simply
1N/Aprint the first $n characters of the string.
1N/A
1N/ASo the Perl subroutine would look like this
1N/A
1N/A sub LeftString
1N/A {
1N/A my($s, $n) = @_ ;
1N/A print substr($s, 0, $n), "\n" ;
1N/A }
1N/A
1N/AThe C function required to call I<LeftString> would look like this.
1N/A
1N/A static void
1N/A call_LeftString(a, b)
1N/A char * a ;
1N/A int b ;
1N/A {
1N/A dSP ;
1N/A
1N/A ENTER ;
1N/A SAVETMPS ;
1N/A
1N/A PUSHMARK(SP) ;
1N/A XPUSHs(sv_2mortal(newSVpv(a, 0)));
1N/A XPUSHs(sv_2mortal(newSViv(b)));
1N/A PUTBACK ;
1N/A
1N/A call_pv("LeftString", G_DISCARD);
1N/A
1N/A FREETMPS ;
1N/A LEAVE ;
1N/A }
1N/A
1N/AHere are a few notes on the C function I<call_LeftString>.
1N/A
1N/A=over 5
1N/A
1N/A=item 1.
1N/A
1N/AParameters are passed to the Perl subroutine using the Perl stack.
1N/AThis is the purpose of the code beginning with the line C<dSP> and
1N/Aending with the line C<PUTBACK>. The C<dSP> declares a local copy
1N/Aof the stack pointer. This local copy should B<always> be accessed
1N/Aas C<SP>.
1N/A
1N/A=item 2.
1N/A
1N/AIf you are going to put something onto the Perl stack, you need to know
1N/Awhere to put it. This is the purpose of the macro C<dSP>--it declares
1N/Aand initializes a I<local> copy of the Perl stack pointer.
1N/A
1N/AAll the other macros which will be used in this example require you to
1N/Ahave used this macro.
1N/A
1N/AThe exception to this rule is if you are calling a Perl subroutine
1N/Adirectly from an XSUB function. In this case it is not necessary to
1N/Ause the C<dSP> macro explicitly--it will be declared for you
1N/Aautomatically.
1N/A
1N/A=item 3.
1N/A
1N/AAny parameters to be pushed onto the stack should be bracketed by the
1N/AC<PUSHMARK> and C<PUTBACK> macros. The purpose of these two macros, in
1N/Athis context, is to count the number of parameters you are
1N/Apushing automatically. Then whenever Perl is creating the C<@_> array for the
1N/Asubroutine, it knows how big to make it.
1N/A
1N/AThe C<PUSHMARK> macro tells Perl to make a mental note of the current
1N/Astack pointer. Even if you aren't passing any parameters (like the
1N/Aexample shown in the section I<No Parameters, Nothing returned>) you
1N/Amust still call the C<PUSHMARK> macro before you can call any of the
1N/AI<call_*> functions--Perl still needs to know that there are no
1N/Aparameters.
1N/A
1N/AThe C<PUTBACK> macro sets the global copy of the stack pointer to be
1N/Athe same as our local copy. If we didn't do this I<call_pv>
1N/Awouldn't know where the two parameters we pushed were--remember that
1N/Aup to now all the stack pointer manipulation we have done is with our
1N/Alocal copy, I<not> the global copy.
1N/A
1N/A=item 4.
1N/A
1N/ANext, we come to XPUSHs. This is where the parameters actually get
1N/Apushed onto the stack. In this case we are pushing a string and an
1N/Ainteger.
1N/A
1N/ASee L<perlguts/"XSUBs and the Argument Stack"> for details
1N/Aon how the XPUSH macros work.
1N/A
1N/A=item 5.
1N/A
1N/ABecause we created temporary values (by means of sv_2mortal() calls)
1N/Awe will have to tidy up the Perl stack and dispose of mortal SVs.
1N/A
1N/AThis is the purpose of
1N/A
1N/A ENTER ;
1N/A SAVETMPS ;
1N/A
1N/Aat the start of the function, and
1N/A
1N/A FREETMPS ;
1N/A LEAVE ;
1N/A
1N/Aat the end. The C<ENTER>/C<SAVETMPS> pair creates a boundary for any
1N/Atemporaries we create. This means that the temporaries we get rid of
1N/Awill be limited to those which were created after these calls.
1N/A
1N/AThe C<FREETMPS>/C<LEAVE> pair will get rid of any values returned by
1N/Athe Perl subroutine (see next example), plus it will also dump the
1N/Amortal SVs we have created. Having C<ENTER>/C<SAVETMPS> at the
1N/Abeginning of the code makes sure that no other mortals are destroyed.
1N/A
1N/AThink of these macros as working a bit like using C<{> and C<}> in Perl
1N/Ato limit the scope of local variables.
1N/A
1N/ASee the section I<Using Perl to dispose of temporaries> for details of
1N/Aan alternative to using these macros.
1N/A
1N/A=item 6.
1N/A
1N/AFinally, I<LeftString> can now be called via the I<call_pv> function.
1N/AThe only flag specified this time is G_DISCARD. Because we are passing
1N/A2 parameters to the Perl subroutine this time, we have not specified
1N/AG_NOARGS.
1N/A
1N/A=back
1N/A
1N/A=head2 Returning a Scalar
1N/A
1N/ANow for an example of dealing with the items returned from a Perl
1N/Asubroutine.
1N/A
1N/AHere is a Perl subroutine, I<Adder>, that takes 2 integer parameters
1N/Aand simply returns their sum.
1N/A
1N/A sub Adder
1N/A {
1N/A my($a, $b) = @_ ;
1N/A $a + $b ;
1N/A }
1N/A
1N/ABecause we are now concerned with the return value from I<Adder>, the C
1N/Afunction required to call it is now a bit more complex.
1N/A
1N/A static void
1N/A call_Adder(a, b)
1N/A int a ;
1N/A int b ;
1N/A {
1N/A dSP ;
1N/A int count ;
1N/A
1N/A ENTER ;
1N/A SAVETMPS;
1N/A
1N/A PUSHMARK(SP) ;
1N/A XPUSHs(sv_2mortal(newSViv(a)));
1N/A XPUSHs(sv_2mortal(newSViv(b)));
1N/A PUTBACK ;
1N/A
1N/A count = call_pv("Adder", G_SCALAR);
1N/A
1N/A SPAGAIN ;
1N/A
1N/A if (count != 1)
1N/A croak("Big trouble\n") ;
1N/A
1N/A printf ("The sum of %d and %d is %d\n", a, b, POPi) ;
1N/A
1N/A PUTBACK ;
1N/A FREETMPS ;
1N/A LEAVE ;
1N/A }
1N/A
1N/APoints to note this time are
1N/A
1N/A=over 5
1N/A
1N/A=item 1.
1N/A
1N/AThe only flag specified this time was G_SCALAR. That means the C<@_>
1N/Aarray will be created and that the value returned by I<Adder> will
1N/Astill exist after the call to I<call_pv>.
1N/A
1N/A=item 2.
1N/A
1N/AThe purpose of the macro C<SPAGAIN> is to refresh the local copy of the
1N/Astack pointer. This is necessary because it is possible that the memory
1N/Aallocated to the Perl stack has been reallocated whilst in the
1N/AI<call_pv> call.
1N/A
1N/AIf you are making use of the Perl stack pointer in your code you must
1N/Aalways refresh the local copy using SPAGAIN whenever you make use
1N/Aof the I<call_*> functions or any other Perl internal function.
1N/A
1N/A=item 3.
1N/A
1N/AAlthough only a single value was expected to be returned from I<Adder>,
1N/Ait is still good practice to check the return code from I<call_pv>
1N/Aanyway.
1N/A
1N/AExpecting a single value is not quite the same as knowing that there
1N/Awill be one. If someone modified I<Adder> to return a list and we
1N/Adidn't check for that possibility and take appropriate action the Perl
1N/Astack would end up in an inconsistent state. That is something you
1N/AI<really> don't want to happen ever.
1N/A
1N/A=item 4.
1N/A
1N/AThe C<POPi> macro is used here to pop the return value from the stack.
1N/AIn this case we wanted an integer, so C<POPi> was used.
1N/A
1N/A
1N/AHere is the complete list of POP macros available, along with the types
1N/Athey return.
1N/A
1N/A POPs SV
1N/A POPp pointer
1N/A POPn double
1N/A POPi integer
1N/A POPl long
1N/A
1N/A=item 5.
1N/A
1N/AThe final C<PUTBACK> is used to leave the Perl stack in a consistent
1N/Astate before exiting the function. This is necessary because when we
1N/Apopped the return value from the stack with C<POPi> it updated only our
1N/Alocal copy of the stack pointer. Remember, C<PUTBACK> sets the global
1N/Astack pointer to be the same as our local copy.
1N/A
1N/A=back
1N/A
1N/A
1N/A=head2 Returning a list of values
1N/A
1N/ANow, let's extend the previous example to return both the sum of the
1N/Aparameters and the difference.
1N/A
1N/AHere is the Perl subroutine
1N/A
1N/A sub AddSubtract
1N/A {
1N/A my($a, $b) = @_ ;
1N/A ($a+$b, $a-$b) ;
1N/A }
1N/A
1N/Aand this is the C function
1N/A
1N/A static void
1N/A call_AddSubtract(a, b)
1N/A int a ;
1N/A int b ;
1N/A {
1N/A dSP ;
1N/A int count ;
1N/A
1N/A ENTER ;
1N/A SAVETMPS;
1N/A
1N/A PUSHMARK(SP) ;
1N/A XPUSHs(sv_2mortal(newSViv(a)));
1N/A XPUSHs(sv_2mortal(newSViv(b)));
1N/A PUTBACK ;
1N/A
1N/A count = call_pv("AddSubtract", G_ARRAY);
1N/A
1N/A SPAGAIN ;
1N/A
1N/A if (count != 2)
1N/A croak("Big trouble\n") ;
1N/A
1N/A printf ("%d - %d = %d\n", a, b, POPi) ;
1N/A printf ("%d + %d = %d\n", a, b, POPi) ;
1N/A
1N/A PUTBACK ;
1N/A FREETMPS ;
1N/A LEAVE ;
1N/A }
1N/A
1N/AIf I<call_AddSubtract> is called like this
1N/A
1N/A call_AddSubtract(7, 4) ;
1N/A
1N/Athen here is the output
1N/A
1N/A 7 - 4 = 3
1N/A 7 + 4 = 11
1N/A
1N/ANotes
1N/A
1N/A=over 5
1N/A
1N/A=item 1.
1N/A
1N/AWe wanted list context, so G_ARRAY was used.
1N/A
1N/A=item 2.
1N/A
1N/ANot surprisingly C<POPi> is used twice this time because we were
1N/Aretrieving 2 values from the stack. The important thing to note is that
1N/Awhen using the C<POP*> macros they come off the stack in I<reverse>
1N/Aorder.
1N/A
1N/A=back
1N/A
1N/A=head2 Returning a list in a scalar context
1N/A
1N/ASay the Perl subroutine in the previous section was called in a scalar
1N/Acontext, like this
1N/A
1N/A static void
1N/A call_AddSubScalar(a, b)
1N/A int a ;
1N/A int b ;
1N/A {
1N/A dSP ;
1N/A int count ;
1N/A int i ;
1N/A
1N/A ENTER ;
1N/A SAVETMPS;
1N/A
1N/A PUSHMARK(SP) ;
1N/A XPUSHs(sv_2mortal(newSViv(a)));
1N/A XPUSHs(sv_2mortal(newSViv(b)));
1N/A PUTBACK ;
1N/A
1N/A count = call_pv("AddSubtract", G_SCALAR);
1N/A
1N/A SPAGAIN ;
1N/A
1N/A printf ("Items Returned = %d\n", count) ;
1N/A
1N/A for (i = 1 ; i <= count ; ++i)
1N/A printf ("Value %d = %d\n", i, POPi) ;
1N/A
1N/A PUTBACK ;
1N/A FREETMPS ;
1N/A LEAVE ;
1N/A }
1N/A
1N/AThe other modification made is that I<call_AddSubScalar> will print the
1N/Anumber of items returned from the Perl subroutine and their value (for
1N/Asimplicity it assumes that they are integer). So if
1N/AI<call_AddSubScalar> is called
1N/A
1N/A call_AddSubScalar(7, 4) ;
1N/A
1N/Athen the output will be
1N/A
1N/A Items Returned = 1
1N/A Value 1 = 3
1N/A
1N/AIn this case the main point to note is that only the last item in the
1N/Alist is returned from the subroutine, I<AddSubtract> actually made it back to
1N/AI<call_AddSubScalar>.
1N/A
1N/A
1N/A=head2 Returning Data from Perl via the parameter list
1N/A
1N/AIt is also possible to return values directly via the parameter list -
1N/Awhether it is actually desirable to do it is another matter entirely.
1N/A
1N/AThe Perl subroutine, I<Inc>, below takes 2 parameters and increments
1N/Aeach directly.
1N/A
1N/A sub Inc
1N/A {
1N/A ++ $_[0] ;
1N/A ++ $_[1] ;
1N/A }
1N/A
1N/Aand here is a C function to call it.
1N/A
1N/A static void
1N/A call_Inc(a, b)
1N/A int a ;
1N/A int b ;
1N/A {
1N/A dSP ;
1N/A int count ;
1N/A SV * sva ;
1N/A SV * svb ;
1N/A
1N/A ENTER ;
1N/A SAVETMPS;
1N/A
1N/A sva = sv_2mortal(newSViv(a)) ;
1N/A svb = sv_2mortal(newSViv(b)) ;
1N/A
1N/A PUSHMARK(SP) ;
1N/A XPUSHs(sva);
1N/A XPUSHs(svb);
1N/A PUTBACK ;
1N/A
1N/A count = call_pv("Inc", G_DISCARD);
1N/A
1N/A if (count != 0)
1N/A croak ("call_Inc: expected 0 values from 'Inc', got %d\n",
1N/A count) ;
1N/A
1N/A printf ("%d + 1 = %d\n", a, SvIV(sva)) ;
1N/A printf ("%d + 1 = %d\n", b, SvIV(svb)) ;
1N/A
1N/A FREETMPS ;
1N/A LEAVE ;
1N/A }
1N/A
1N/ATo be able to access the two parameters that were pushed onto the stack
1N/Aafter they return from I<call_pv> it is necessary to make a note
1N/Aof their addresses--thus the two variables C<sva> and C<svb>.
1N/A
1N/AThe reason this is necessary is that the area of the Perl stack which
1N/Aheld them will very likely have been overwritten by something else by
1N/Athe time control returns from I<call_pv>.
1N/A
1N/A
1N/A
1N/A
1N/A=head2 Using G_EVAL
1N/A
1N/ANow an example using G_EVAL. Below is a Perl subroutine which computes
1N/Athe difference of its 2 parameters. If this would result in a negative
1N/Aresult, the subroutine calls I<die>.
1N/A
1N/A sub Subtract
1N/A {
1N/A my ($a, $b) = @_ ;
1N/A
1N/A die "death can be fatal\n" if $a < $b ;
1N/A
1N/A $a - $b ;
1N/A }
1N/A
1N/Aand some C to call it
1N/A
1N/A static void
1N/A call_Subtract(a, b)
1N/A int a ;
1N/A int b ;
1N/A {
1N/A dSP ;
1N/A int count ;
1N/A
1N/A ENTER ;
1N/A SAVETMPS;
1N/A
1N/A PUSHMARK(SP) ;
1N/A XPUSHs(sv_2mortal(newSViv(a)));
1N/A XPUSHs(sv_2mortal(newSViv(b)));
1N/A PUTBACK ;
1N/A
1N/A count = call_pv("Subtract", G_EVAL|G_SCALAR);
1N/A
1N/A SPAGAIN ;
1N/A
1N/A /* Check the eval first */
1N/A if (SvTRUE(ERRSV))
1N/A {
1N/A STRLEN n_a;
1N/A printf ("Uh oh - %s\n", SvPV(ERRSV, n_a)) ;
1N/A POPs ;
1N/A }
1N/A else
1N/A {
1N/A if (count != 1)
1N/A croak("call_Subtract: wanted 1 value from 'Subtract', got %d\n",
1N/A count) ;
1N/A
1N/A printf ("%d - %d = %d\n", a, b, POPi) ;
1N/A }
1N/A
1N/A PUTBACK ;
1N/A FREETMPS ;
1N/A LEAVE ;
1N/A }
1N/A
1N/AIf I<call_Subtract> is called thus
1N/A
1N/A call_Subtract(4, 5)
1N/A
1N/Athe following will be printed
1N/A
1N/A Uh oh - death can be fatal
1N/A
1N/ANotes
1N/A
1N/A=over 5
1N/A
1N/A=item 1.
1N/A
1N/AWe want to be able to catch the I<die> so we have used the G_EVAL
1N/Aflag. Not specifying this flag would mean that the program would
1N/Aterminate immediately at the I<die> statement in the subroutine
1N/AI<Subtract>.
1N/A
1N/A=item 2.
1N/A
1N/AThe code
1N/A
1N/A if (SvTRUE(ERRSV))
1N/A {
1N/A STRLEN n_a;
1N/A printf ("Uh oh - %s\n", SvPV(ERRSV, n_a)) ;
1N/A POPs ;
1N/A }
1N/A
1N/Ais the direct equivalent of this bit of Perl
1N/A
1N/A print "Uh oh - $@\n" if $@ ;
1N/A
1N/AC<PL_errgv> is a perl global of type C<GV *> that points to the
1N/Asymbol table entry containing the error. C<ERRSV> therefore
1N/Arefers to the C equivalent of C<$@>.
1N/A
1N/A=item 3.
1N/A
1N/ANote that the stack is popped using C<POPs> in the block where
1N/AC<SvTRUE(ERRSV)> is true. This is necessary because whenever a
1N/AI<call_*> function invoked with G_EVAL|G_SCALAR returns an error,
1N/Athe top of the stack holds the value I<undef>. Because we want the
1N/Aprogram to continue after detecting this error, it is essential that
1N/Athe stack is tidied up by removing the I<undef>.
1N/A
1N/A=back
1N/A
1N/A
1N/A=head2 Using G_KEEPERR
1N/A
1N/AConsider this rather facetious example, where we have used an XS
1N/Aversion of the call_Subtract example above inside a destructor:
1N/A
1N/A package Foo;
1N/A sub new { bless {}, $_[0] }
1N/A sub Subtract {
1N/A my($a,$b) = @_;
1N/A die "death can be fatal" if $a < $b ;
1N/A $a - $b;
1N/A }
1N/A sub DESTROY { call_Subtract(5, 4); }
1N/A sub foo { die "foo dies"; }
1N/A
1N/A package main;
1N/A eval { Foo->new->foo };
1N/A print "Saw: $@" if $@; # should be, but isn't
1N/A
1N/AThis example will fail to recognize that an error occurred inside the
1N/AC<eval {}>. Here's why: the call_Subtract code got executed while perl
1N/Awas cleaning up temporaries when exiting the eval block, and because
1N/Acall_Subtract is implemented with I<call_pv> using the G_EVAL
1N/Aflag, it promptly reset C<$@>. This results in the failure of the
1N/Aoutermost test for C<$@>, and thereby the failure of the error trap.
1N/A
1N/AAppending the G_KEEPERR flag, so that the I<call_pv> call in
1N/Acall_Subtract reads:
1N/A
1N/A count = call_pv("Subtract", G_EVAL|G_SCALAR|G_KEEPERR);
1N/A
1N/Awill preserve the error and restore reliable error handling.
1N/A
1N/A=head2 Using call_sv
1N/A
1N/AIn all the previous examples I have 'hard-wired' the name of the Perl
1N/Asubroutine to be called from C. Most of the time though, it is more
1N/Aconvenient to be able to specify the name of the Perl subroutine from
1N/Awithin the Perl script.
1N/A
1N/AConsider the Perl code below
1N/A
1N/A sub fred
1N/A {
1N/A print "Hello there\n" ;
1N/A }
1N/A
1N/A CallSubPV("fred") ;
1N/A
1N/AHere is a snippet of XSUB which defines I<CallSubPV>.
1N/A
1N/A void
1N/A CallSubPV(name)
1N/A char * name
1N/A CODE:
1N/A PUSHMARK(SP) ;
1N/A call_pv(name, G_DISCARD|G_NOARGS) ;
1N/A
1N/AThat is fine as far as it goes. The thing is, the Perl subroutine
1N/Acan be specified as only a string. For Perl 4 this was adequate,
1N/Abut Perl 5 allows references to subroutines and anonymous subroutines.
1N/AThis is where I<call_sv> is useful.
1N/A
1N/AThe code below for I<CallSubSV> is identical to I<CallSubPV> except
1N/Athat the C<name> parameter is now defined as an SV* and we use
1N/AI<call_sv> instead of I<call_pv>.
1N/A
1N/A void
1N/A CallSubSV(name)
1N/A SV * name
1N/A CODE:
1N/A PUSHMARK(SP) ;
1N/A call_sv(name, G_DISCARD|G_NOARGS) ;
1N/A
1N/ABecause we are using an SV to call I<fred> the following can all be used
1N/A
1N/A CallSubSV("fred") ;
1N/A CallSubSV(\&fred) ;
1N/A $ref = \&fred ;
1N/A CallSubSV($ref) ;
1N/A CallSubSV( sub { print "Hello there\n" } ) ;
1N/A
1N/AAs you can see, I<call_sv> gives you much greater flexibility in
1N/Ahow you can specify the Perl subroutine.
1N/A
1N/AYou should note that if it is necessary to store the SV (C<name> in the
1N/Aexample above) which corresponds to the Perl subroutine so that it can
1N/Abe used later in the program, it not enough just to store a copy of the
1N/Apointer to the SV. Say the code above had been like this
1N/A
1N/A static SV * rememberSub ;
1N/A
1N/A void
1N/A SaveSub1(name)
1N/A SV * name
1N/A CODE:
1N/A rememberSub = name ;
1N/A
1N/A void
1N/A CallSavedSub1()
1N/A CODE:
1N/A PUSHMARK(SP) ;
1N/A call_sv(rememberSub, G_DISCARD|G_NOARGS) ;
1N/A
1N/AThe reason this is wrong is that by the time you come to use the
1N/Apointer C<rememberSub> in C<CallSavedSub1>, it may or may not still refer
1N/Ato the Perl subroutine that was recorded in C<SaveSub1>. This is
1N/Aparticularly true for these cases
1N/A
1N/A SaveSub1(\&fred) ;
1N/A CallSavedSub1() ;
1N/A
1N/A SaveSub1( sub { print "Hello there\n" } ) ;
1N/A CallSavedSub1() ;
1N/A
1N/ABy the time each of the C<SaveSub1> statements above have been executed,
1N/Athe SV*s which corresponded to the parameters will no longer exist.
1N/AExpect an error message from Perl of the form
1N/A
1N/A Can't use an undefined value as a subroutine reference at ...
1N/A
1N/Afor each of the C<CallSavedSub1> lines.
1N/A
1N/ASimilarly, with this code
1N/A
1N/A $ref = \&fred ;
1N/A SaveSub1($ref) ;
1N/A $ref = 47 ;
1N/A CallSavedSub1() ;
1N/A
1N/Ayou can expect one of these messages (which you actually get is dependent on
1N/Athe version of Perl you are using)
1N/A
1N/A Not a CODE reference at ...
1N/A Undefined subroutine &main::47 called ...
1N/A
1N/AThe variable $ref may have referred to the subroutine C<fred>
1N/Awhenever the call to C<SaveSub1> was made but by the time
1N/AC<CallSavedSub1> gets called it now holds the number C<47>. Because we
1N/Asaved only a pointer to the original SV in C<SaveSub1>, any changes to
1N/A$ref will be tracked by the pointer C<rememberSub>. This means that
1N/Awhenever C<CallSavedSub1> gets called, it will attempt to execute the
1N/Acode which is referenced by the SV* C<rememberSub>. In this case
1N/Athough, it now refers to the integer C<47>, so expect Perl to complain
1N/Aloudly.
1N/A
1N/AA similar but more subtle problem is illustrated with this code
1N/A
1N/A $ref = \&fred ;
1N/A SaveSub1($ref) ;
1N/A $ref = \&joe ;
1N/A CallSavedSub1() ;
1N/A
1N/AThis time whenever C<CallSavedSub1> get called it will execute the Perl
1N/Asubroutine C<joe> (assuming it exists) rather than C<fred> as was
1N/Aoriginally requested in the call to C<SaveSub1>.
1N/A
1N/ATo get around these problems it is necessary to take a full copy of the
1N/ASV. The code below shows C<SaveSub2> modified to do that
1N/A
1N/A static SV * keepSub = (SV*)NULL ;
1N/A
1N/A void
1N/A SaveSub2(name)
1N/A SV * name
1N/A CODE:
1N/A /* Take a copy of the callback */
1N/A if (keepSub == (SV*)NULL)
1N/A /* First time, so create a new SV */
1N/A keepSub = newSVsv(name) ;
1N/A else
1N/A /* Been here before, so overwrite */
1N/A SvSetSV(keepSub, name) ;
1N/A
1N/A void
1N/A CallSavedSub2()
1N/A CODE:
1N/A PUSHMARK(SP) ;
1N/A call_sv(keepSub, G_DISCARD|G_NOARGS) ;
1N/A
1N/ATo avoid creating a new SV every time C<SaveSub2> is called,
1N/Athe function first checks to see if it has been called before. If not,
1N/Athen space for a new SV is allocated and the reference to the Perl
1N/Asubroutine, C<name> is copied to the variable C<keepSub> in one
1N/Aoperation using C<newSVsv>. Thereafter, whenever C<SaveSub2> is called
1N/Athe existing SV, C<keepSub>, is overwritten with the new value using
1N/AC<SvSetSV>.
1N/A
1N/A=head2 Using call_argv
1N/A
1N/AHere is a Perl subroutine which prints whatever parameters are passed
1N/Ato it.
1N/A
1N/A sub PrintList
1N/A {
1N/A my(@list) = @_ ;
1N/A
1N/A foreach (@list) { print "$_\n" }
1N/A }
1N/A
1N/Aand here is an example of I<call_argv> which will call
1N/AI<PrintList>.
1N/A
1N/A static char * words[] = {"alpha", "beta", "gamma", "delta", NULL} ;
1N/A
1N/A static void
1N/A call_PrintList()
1N/A {
1N/A dSP ;
1N/A
1N/A call_argv("PrintList", G_DISCARD, words) ;
1N/A }
1N/A
1N/ANote that it is not necessary to call C<PUSHMARK> in this instance.
1N/AThis is because I<call_argv> will do it for you.
1N/A
1N/A=head2 Using call_method
1N/A
1N/AConsider the following Perl code
1N/A
1N/A {
1N/A package Mine ;
1N/A
1N/A sub new
1N/A {
1N/A my($type) = shift ;
1N/A bless [@_]
1N/A }
1N/A
1N/A sub Display
1N/A {
1N/A my ($self, $index) = @_ ;
1N/A print "$index: $$self[$index]\n" ;
1N/A }
1N/A
1N/A sub PrintID
1N/A {
1N/A my($class) = @_ ;
1N/A print "This is Class $class version 1.0\n" ;
1N/A }
1N/A }
1N/A
1N/AIt implements just a very simple class to manage an array. Apart from
1N/Athe constructor, C<new>, it declares methods, one static and one
1N/Avirtual. The static method, C<PrintID>, prints out simply the class
1N/Aname and a version number. The virtual method, C<Display>, prints out a
1N/Asingle element of the array. Here is an all Perl example of using it.
1N/A
1N/A $a = new Mine ('red', 'green', 'blue') ;
1N/A $a->Display(1) ;
1N/A PrintID Mine;
1N/A
1N/Awill print
1N/A
1N/A 1: green
1N/A This is Class Mine version 1.0
1N/A
1N/ACalling a Perl method from C is fairly straightforward. The following
1N/Athings are required
1N/A
1N/A=over 5
1N/A
1N/A=item *
1N/A
1N/Aa reference to the object for a virtual method or the name of the class
1N/Afor a static method.
1N/A
1N/A=item *
1N/A
1N/Athe name of the method.
1N/A
1N/A=item *
1N/A
1N/Aany other parameters specific to the method.
1N/A
1N/A=back
1N/A
1N/AHere is a simple XSUB which illustrates the mechanics of calling both
1N/Athe C<PrintID> and C<Display> methods from C.
1N/A
1N/A void
1N/A call_Method(ref, method, index)
1N/A SV * ref
1N/A char * method
1N/A int index
1N/A CODE:
1N/A PUSHMARK(SP);
1N/A XPUSHs(ref);
1N/A XPUSHs(sv_2mortal(newSViv(index))) ;
1N/A PUTBACK;
1N/A
1N/A call_method(method, G_DISCARD) ;
1N/A
1N/A void
1N/A call_PrintID(class, method)
1N/A char * class
1N/A char * method
1N/A CODE:
1N/A PUSHMARK(SP);
1N/A XPUSHs(sv_2mortal(newSVpv(class, 0))) ;
1N/A PUTBACK;
1N/A
1N/A call_method(method, G_DISCARD) ;
1N/A
1N/A
1N/ASo the methods C<PrintID> and C<Display> can be invoked like this
1N/A
1N/A $a = new Mine ('red', 'green', 'blue') ;
1N/A call_Method($a, 'Display', 1) ;
1N/A call_PrintID('Mine', 'PrintID') ;
1N/A
1N/AThe only thing to note is that in both the static and virtual methods,
1N/Athe method name is not passed via the stack--it is used as the first
1N/Aparameter to I<call_method>.
1N/A
1N/A=head2 Using GIMME_V
1N/A
1N/AHere is a trivial XSUB which prints the context in which it is
1N/Acurrently executing.
1N/A
1N/A void
1N/A PrintContext()
1N/A CODE:
1N/A I32 gimme = GIMME_V;
1N/A if (gimme == G_VOID)
1N/A printf ("Context is Void\n") ;
1N/A else if (gimme == G_SCALAR)
1N/A printf ("Context is Scalar\n") ;
1N/A else
1N/A printf ("Context is Array\n") ;
1N/A
1N/Aand here is some Perl to test it
1N/A
1N/A PrintContext ;
1N/A $a = PrintContext ;
1N/A @a = PrintContext ;
1N/A
1N/AThe output from that will be
1N/A
1N/A Context is Void
1N/A Context is Scalar
1N/A Context is Array
1N/A
1N/A=head2 Using Perl to dispose of temporaries
1N/A
1N/AIn the examples given to date, any temporaries created in the callback
1N/A(i.e., parameters passed on the stack to the I<call_*> function or
1N/Avalues returned via the stack) have been freed by one of these methods
1N/A
1N/A=over 5
1N/A
1N/A=item *
1N/A
1N/Aspecifying the G_DISCARD flag with I<call_*>.
1N/A
1N/A=item *
1N/A
1N/Aexplicitly disposed of using the C<ENTER>/C<SAVETMPS> -
1N/AC<FREETMPS>/C<LEAVE> pairing.
1N/A
1N/A=back
1N/A
1N/AThere is another method which can be used, namely letting Perl do it
1N/Afor you automatically whenever it regains control after the callback
1N/Ahas terminated. This is done by simply not using the
1N/A
1N/A ENTER ;
1N/A SAVETMPS ;
1N/A ...
1N/A FREETMPS ;
1N/A LEAVE ;
1N/A
1N/Asequence in the callback (and not, of course, specifying the G_DISCARD
1N/Aflag).
1N/A
1N/AIf you are going to use this method you have to be aware of a possible
1N/Amemory leak which can arise under very specific circumstances. To
1N/Aexplain these circumstances you need to know a bit about the flow of
1N/Acontrol between Perl and the callback routine.
1N/A
1N/AThe examples given at the start of the document (an error handler and
1N/Aan event driven program) are typical of the two main sorts of flow
1N/Acontrol that you are likely to encounter with callbacks. There is a
1N/Avery important distinction between them, so pay attention.
1N/A
1N/AIn the first example, an error handler, the flow of control could be as
1N/Afollows. You have created an interface to an external library.
1N/AControl can reach the external library like this
1N/A
1N/A perl --> XSUB --> external library
1N/A
1N/AWhilst control is in the library, an error condition occurs. You have
1N/Apreviously set up a Perl callback to handle this situation, so it will
1N/Aget executed. Once the callback has finished, control will drop back to
1N/APerl again. Here is what the flow of control will be like in that
1N/Asituation
1N/A
1N/A perl --> XSUB --> external library
1N/A ...
1N/A error occurs
1N/A ...
1N/A external library --> call_* --> perl
1N/A |
1N/A perl <-- XSUB <-- external library <-- call_* <----+
1N/A
1N/AAfter processing of the error using I<call_*> is completed,
1N/Acontrol reverts back to Perl more or less immediately.
1N/A
1N/AIn the diagram, the further right you go the more deeply nested the
1N/Ascope is. It is only when control is back with perl on the extreme
1N/Aleft of the diagram that you will have dropped back to the enclosing
1N/Ascope and any temporaries you have left hanging around will be freed.
1N/A
1N/AIn the second example, an event driven program, the flow of control
1N/Awill be more like this
1N/A
1N/A perl --> XSUB --> event handler
1N/A ...
1N/A event handler --> call_* --> perl
1N/A |
1N/A event handler <-- call_* <----+
1N/A ...
1N/A event handler --> call_* --> perl
1N/A |
1N/A event handler <-- call_* <----+
1N/A ...
1N/A event handler --> call_* --> perl
1N/A |
1N/A event handler <-- call_* <----+
1N/A
1N/AIn this case the flow of control can consist of only the repeated
1N/Asequence
1N/A
1N/A event handler --> call_* --> perl
1N/A
1N/Afor practically the complete duration of the program. This means that
1N/Acontrol may I<never> drop back to the surrounding scope in Perl at the
1N/Aextreme left.
1N/A
1N/ASo what is the big problem? Well, if you are expecting Perl to tidy up
1N/Athose temporaries for you, you might be in for a long wait. For Perl
1N/Ato dispose of your temporaries, control must drop back to the
1N/Aenclosing scope at some stage. In the event driven scenario that may
1N/Anever happen. This means that as time goes on, your program will
1N/Acreate more and more temporaries, none of which will ever be freed. As
1N/Aeach of these temporaries consumes some memory your program will
1N/Aeventually consume all the available memory in your system--kapow!
1N/A
1N/ASo here is the bottom line--if you are sure that control will revert
1N/Aback to the enclosing Perl scope fairly quickly after the end of your
1N/Acallback, then it isn't absolutely necessary to dispose explicitly of
1N/Aany temporaries you may have created. Mind you, if you are at all
1N/Auncertain about what to do, it doesn't do any harm to tidy up anyway.
1N/A
1N/A
1N/A=head2 Strategies for storing Callback Context Information
1N/A
1N/A
1N/APotentially one of the trickiest problems to overcome when designing a
1N/Acallback interface can be figuring out how to store the mapping between
1N/Athe C callback function and the Perl equivalent.
1N/A
1N/ATo help understand why this can be a real problem first consider how a
1N/Acallback is set up in an all C environment. Typically a C API will
1N/Aprovide a function to register a callback. This will expect a pointer
1N/Ato a function as one of its parameters. Below is a call to a
1N/Ahypothetical function C<register_fatal> which registers the C function
1N/Ato get called when a fatal error occurs.
1N/A
1N/A register_fatal(cb1) ;
1N/A
1N/AThe single parameter C<cb1> is a pointer to a function, so you must
1N/Ahave defined C<cb1> in your code, say something like this
1N/A
1N/A static void
1N/A cb1()
1N/A {
1N/A printf ("Fatal Error\n") ;
1N/A exit(1) ;
1N/A }
1N/A
1N/ANow change that to call a Perl subroutine instead
1N/A
1N/A static SV * callback = (SV*)NULL;
1N/A
1N/A static void
1N/A cb1()
1N/A {
1N/A dSP ;
1N/A
1N/A PUSHMARK(SP) ;
1N/A
1N/A /* Call the Perl sub to process the callback */
1N/A call_sv(callback, G_DISCARD) ;
1N/A }
1N/A
1N/A
1N/A void
1N/A register_fatal(fn)
1N/A SV * fn
1N/A CODE:
1N/A /* Remember the Perl sub */
1N/A if (callback == (SV*)NULL)
1N/A callback = newSVsv(fn) ;
1N/A else
1N/A SvSetSV(callback, fn) ;
1N/A
1N/A /* register the callback with the external library */
1N/A register_fatal(cb1) ;
1N/A
1N/Awhere the Perl equivalent of C<register_fatal> and the callback it
1N/Aregisters, C<pcb1>, might look like this
1N/A
1N/A # Register the sub pcb1
1N/A register_fatal(\&pcb1) ;
1N/A
1N/A sub pcb1
1N/A {
1N/A die "I'm dying...\n" ;
1N/A }
1N/A
1N/AThe mapping between the C callback and the Perl equivalent is stored in
1N/Athe global variable C<callback>.
1N/A
1N/AThis will be adequate if you ever need to have only one callback
1N/Aregistered at any time. An example could be an error handler like the
1N/Acode sketched out above. Remember though, repeated calls to
1N/AC<register_fatal> will replace the previously registered callback
1N/Afunction with the new one.
1N/A
1N/ASay for example you want to interface to a library which allows asynchronous
1N/Afile i/o. In this case you may be able to register a callback whenever
1N/Aa read operation has completed. To be of any use we want to be able to
1N/Acall separate Perl subroutines for each file that is opened. As it
1N/Astands, the error handler example above would not be adequate as it
1N/Aallows only a single callback to be defined at any time. What we
1N/Arequire is a means of storing the mapping between the opened file and
1N/Athe Perl subroutine we want to be called for that file.
1N/A
1N/ASay the i/o library has a function C<asynch_read> which associates a C
1N/Afunction C<ProcessRead> with a file handle C<fh>--this assumes that it
1N/Ahas also provided some routine to open the file and so obtain the file
1N/Ahandle.
1N/A
1N/A asynch_read(fh, ProcessRead)
1N/A
1N/AThis may expect the C I<ProcessRead> function of this form
1N/A
1N/A void
1N/A ProcessRead(fh, buffer)
1N/A int fh ;
1N/A char * buffer ;
1N/A {
1N/A ...
1N/A }
1N/A
1N/ATo provide a Perl interface to this library we need to be able to map
1N/Abetween the C<fh> parameter and the Perl subroutine we want called. A
1N/Ahash is a convenient mechanism for storing this mapping. The code
1N/Abelow shows a possible implementation
1N/A
1N/A static HV * Mapping = (HV*)NULL ;
1N/A
1N/A void
1N/A asynch_read(fh, callback)
1N/A int fh
1N/A SV * callback
1N/A CODE:
1N/A /* If the hash doesn't already exist, create it */
1N/A if (Mapping == (HV*)NULL)
1N/A Mapping = newHV() ;
1N/A
1N/A /* Save the fh -> callback mapping */
1N/A hv_store(Mapping, (char*)&fh, sizeof(fh), newSVsv(callback), 0) ;
1N/A
1N/A /* Register with the C Library */
1N/A asynch_read(fh, asynch_read_if) ;
1N/A
1N/Aand C<asynch_read_if> could look like this
1N/A
1N/A static void
1N/A asynch_read_if(fh, buffer)
1N/A int fh ;
1N/A char * buffer ;
1N/A {
1N/A dSP ;
1N/A SV ** sv ;
1N/A
1N/A /* Get the callback associated with fh */
1N/A sv = hv_fetch(Mapping, (char*)&fh , sizeof(fh), FALSE) ;
1N/A if (sv == (SV**)NULL)
1N/A croak("Internal error...\n") ;
1N/A
1N/A PUSHMARK(SP) ;
1N/A XPUSHs(sv_2mortal(newSViv(fh))) ;
1N/A XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
1N/A PUTBACK ;
1N/A
1N/A /* Call the Perl sub */
1N/A call_sv(*sv, G_DISCARD) ;
1N/A }
1N/A
1N/AFor completeness, here is C<asynch_close>. This shows how to remove
1N/Athe entry from the hash C<Mapping>.
1N/A
1N/A void
1N/A asynch_close(fh)
1N/A int fh
1N/A CODE:
1N/A /* Remove the entry from the hash */
1N/A (void) hv_delete(Mapping, (char*)&fh, sizeof(fh), G_DISCARD) ;
1N/A
1N/A /* Now call the real asynch_close */
1N/A asynch_close(fh) ;
1N/A
1N/ASo the Perl interface would look like this
1N/A
1N/A sub callback1
1N/A {
1N/A my($handle, $buffer) = @_ ;
1N/A }
1N/A
1N/A # Register the Perl callback
1N/A asynch_read($fh, \&callback1) ;
1N/A
1N/A asynch_close($fh) ;
1N/A
1N/AThe mapping between the C callback and Perl is stored in the global
1N/Ahash C<Mapping> this time. Using a hash has the distinct advantage that
1N/Ait allows an unlimited number of callbacks to be registered.
1N/A
1N/AWhat if the interface provided by the C callback doesn't contain a
1N/Aparameter which allows the file handle to Perl subroutine mapping? Say
1N/Ain the asynchronous i/o package, the callback function gets passed only
1N/Athe C<buffer> parameter like this
1N/A
1N/A void
1N/A ProcessRead(buffer)
1N/A char * buffer ;
1N/A {
1N/A ...
1N/A }
1N/A
1N/AWithout the file handle there is no straightforward way to map from the
1N/AC callback to the Perl subroutine.
1N/A
1N/AIn this case a possible way around this problem is to predefine a
1N/Aseries of C functions to act as the interface to Perl, thus
1N/A
1N/A #define MAX_CB 3
1N/A #define NULL_HANDLE -1
1N/A typedef void (*FnMap)() ;
1N/A
1N/A struct MapStruct {
1N/A FnMap Function ;
1N/A SV * PerlSub ;
1N/A int Handle ;
1N/A } ;
1N/A
1N/A static void fn1() ;
1N/A static void fn2() ;
1N/A static void fn3() ;
1N/A
1N/A static struct MapStruct Map [MAX_CB] =
1N/A {
1N/A { fn1, NULL, NULL_HANDLE },
1N/A { fn2, NULL, NULL_HANDLE },
1N/A { fn3, NULL, NULL_HANDLE }
1N/A } ;
1N/A
1N/A static void
1N/A Pcb(index, buffer)
1N/A int index ;
1N/A char * buffer ;
1N/A {
1N/A dSP ;
1N/A
1N/A PUSHMARK(SP) ;
1N/A XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
1N/A PUTBACK ;
1N/A
1N/A /* Call the Perl sub */
1N/A call_sv(Map[index].PerlSub, G_DISCARD) ;
1N/A }
1N/A
1N/A static void
1N/A fn1(buffer)
1N/A char * buffer ;
1N/A {
1N/A Pcb(0, buffer) ;
1N/A }
1N/A
1N/A static void
1N/A fn2(buffer)
1N/A char * buffer ;
1N/A {
1N/A Pcb(1, buffer) ;
1N/A }
1N/A
1N/A static void
1N/A fn3(buffer)
1N/A char * buffer ;
1N/A {
1N/A Pcb(2, buffer) ;
1N/A }
1N/A
1N/A void
1N/A array_asynch_read(fh, callback)
1N/A int fh
1N/A SV * callback
1N/A CODE:
1N/A int index ;
1N/A int null_index = MAX_CB ;
1N/A
1N/A /* Find the same handle or an empty entry */
1N/A for (index = 0 ; index < MAX_CB ; ++index)
1N/A {
1N/A if (Map[index].Handle == fh)
1N/A break ;
1N/A
1N/A if (Map[index].Handle == NULL_HANDLE)
1N/A null_index = index ;
1N/A }
1N/A
1N/A if (index == MAX_CB && null_index == MAX_CB)
1N/A croak ("Too many callback functions registered\n") ;
1N/A
1N/A if (index == MAX_CB)
1N/A index = null_index ;
1N/A
1N/A /* Save the file handle */
1N/A Map[index].Handle = fh ;
1N/A
1N/A /* Remember the Perl sub */
1N/A if (Map[index].PerlSub == (SV*)NULL)
1N/A Map[index].PerlSub = newSVsv(callback) ;
1N/A else
1N/A SvSetSV(Map[index].PerlSub, callback) ;
1N/A
1N/A asynch_read(fh, Map[index].Function) ;
1N/A
1N/A void
1N/A array_asynch_close(fh)
1N/A int fh
1N/A CODE:
1N/A int index ;
1N/A
1N/A /* Find the file handle */
1N/A for (index = 0; index < MAX_CB ; ++ index)
1N/A if (Map[index].Handle == fh)
1N/A break ;
1N/A
1N/A if (index == MAX_CB)
1N/A croak ("could not close fh %d\n", fh) ;
1N/A
1N/A Map[index].Handle = NULL_HANDLE ;
1N/A SvREFCNT_dec(Map[index].PerlSub) ;
1N/A Map[index].PerlSub = (SV*)NULL ;
1N/A
1N/A asynch_close(fh) ;
1N/A
1N/AIn this case the functions C<fn1>, C<fn2>, and C<fn3> are used to
1N/Aremember the Perl subroutine to be called. Each of the functions holds
1N/Aa separate hard-wired index which is used in the function C<Pcb> to
1N/Aaccess the C<Map> array and actually call the Perl subroutine.
1N/A
1N/AThere are some obvious disadvantages with this technique.
1N/A
1N/AFirstly, the code is considerably more complex than with the previous
1N/Aexample.
1N/A
1N/ASecondly, there is a hard-wired limit (in this case 3) to the number of
1N/Acallbacks that can exist simultaneously. The only way to increase the
1N/Alimit is by modifying the code to add more functions and then
1N/Arecompiling. None the less, as long as the number of functions is
1N/Achosen with some care, it is still a workable solution and in some
1N/Acases is the only one available.
1N/A
1N/ATo summarize, here are a number of possible methods for you to consider
1N/Afor storing the mapping between C and the Perl callback
1N/A
1N/A=over 5
1N/A
1N/A=item 1. Ignore the problem - Allow only 1 callback
1N/A
1N/AFor a lot of situations, like interfacing to an error handler, this may
1N/Abe a perfectly adequate solution.
1N/A
1N/A=item 2. Create a sequence of callbacks - hard wired limit
1N/A
1N/AIf it is impossible to tell from the parameters passed back from the C
1N/Acallback what the context is, then you may need to create a sequence of C
1N/Acallback interface functions, and store pointers to each in an array.
1N/A
1N/A=item 3. Use a parameter to map to the Perl callback
1N/A
1N/AA hash is an ideal mechanism to store the mapping between C and Perl.
1N/A
1N/A=back
1N/A
1N/A
1N/A=head2 Alternate Stack Manipulation
1N/A
1N/A
1N/AAlthough I have made use of only the C<POP*> macros to access values
1N/Areturned from Perl subroutines, it is also possible to bypass these
1N/Amacros and read the stack using the C<ST> macro (See L<perlxs> for a
1N/Afull description of the C<ST> macro).
1N/A
1N/AMost of the time the C<POP*> macros should be adequate, the main
1N/Aproblem with them is that they force you to process the returned values
1N/Ain sequence. This may not be the most suitable way to process the
1N/Avalues in some cases. What we want is to be able to access the stack in
1N/Aa random order. The C<ST> macro as used when coding an XSUB is ideal
1N/Afor this purpose.
1N/A
1N/AThe code below is the example given in the section I<Returning a list
1N/Aof values> recoded to use C<ST> instead of C<POP*>.
1N/A
1N/A static void
1N/A call_AddSubtract2(a, b)
1N/A int a ;
1N/A int b ;
1N/A {
1N/A dSP ;
1N/A I32 ax ;
1N/A int count ;
1N/A
1N/A ENTER ;
1N/A SAVETMPS;
1N/A
1N/A PUSHMARK(SP) ;
1N/A XPUSHs(sv_2mortal(newSViv(a)));
1N/A XPUSHs(sv_2mortal(newSViv(b)));
1N/A PUTBACK ;
1N/A
1N/A count = call_pv("AddSubtract", G_ARRAY);
1N/A
1N/A SPAGAIN ;
1N/A SP -= count ;
1N/A ax = (SP - PL_stack_base) + 1 ;
1N/A
1N/A if (count != 2)
1N/A croak("Big trouble\n") ;
1N/A
1N/A printf ("%d + %d = %d\n", a, b, SvIV(ST(0))) ;
1N/A printf ("%d - %d = %d\n", a, b, SvIV(ST(1))) ;
1N/A
1N/A PUTBACK ;
1N/A FREETMPS ;
1N/A LEAVE ;
1N/A }
1N/A
1N/ANotes
1N/A
1N/A=over 5
1N/A
1N/A=item 1.
1N/A
1N/ANotice that it was necessary to define the variable C<ax>. This is
1N/Abecause the C<ST> macro expects it to exist. If we were in an XSUB it
1N/Awould not be necessary to define C<ax> as it is already defined for
1N/Ayou.
1N/A
1N/A=item 2.
1N/A
1N/AThe code
1N/A
1N/A SPAGAIN ;
1N/A SP -= count ;
1N/A ax = (SP - PL_stack_base) + 1 ;
1N/A
1N/Asets the stack up so that we can use the C<ST> macro.
1N/A
1N/A=item 3.
1N/A
1N/AUnlike the original coding of this example, the returned
1N/Avalues are not accessed in reverse order. So C<ST(0)> refers to the
1N/Afirst value returned by the Perl subroutine and C<ST(count-1)>
1N/Arefers to the last.
1N/A
1N/A=back
1N/A
1N/A=head2 Creating and calling an anonymous subroutine in C
1N/A
1N/AAs we've already shown, C<call_sv> can be used to invoke an
1N/Aanonymous subroutine. However, our example showed a Perl script
1N/Ainvoking an XSUB to perform this operation. Let's see how it can be
1N/Adone inside our C code:
1N/A
1N/A ...
1N/A
1N/A SV *cvrv = eval_pv("sub { print 'You will not find me cluttering any namespace!' }", TRUE);
1N/A
1N/A ...
1N/A
1N/A call_sv(cvrv, G_VOID|G_NOARGS);
1N/A
1N/AC<eval_pv> is used to compile the anonymous subroutine, which
1N/Awill be the return value as well (read more about C<eval_pv> in
1N/AL<perlapi/eval_pv>). Once this code reference is in hand, it
1N/Acan be mixed in with all the previous examples we've shown.
1N/A
1N/A=head1 SEE ALSO
1N/A
1N/AL<perlxs>, L<perlguts>, L<perlembed>
1N/A
1N/A=head1 AUTHOR
1N/A
1N/APaul Marquess
1N/A
1N/ASpecial thanks to the following people who assisted in the creation of
1N/Athe document.
1N/A
1N/AJeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem, Gurusamy Sarathy
1N/Aand Larry Wall.
1N/A
1N/A=head1 DATE
1N/A
1N/AVersion 1.3, 14th Apr 1997