<P>The first function calculates the length of the string to be appended by
using <CODE>strlen</CODE>. In the second, you specify the length of the string
yourself. The third function processes its arguments like <A HREF="../../lib/Pod/perlfunc.html#item_sprintf"><CODE>sprintf</CODE></A> and
appends the formatted output. The fourth function works like <CODE>vsprintf</CODE>.
You can specify the address and length of an array of SVs instead of the
va_list argument. The fifth function extends the string stored in the first
SV with the string stored in the second SV. It also forces the second SV
to be interpreted as a string.</P>
<P>The <CODE>sv_cat*()</CODE> functions are not generic enough to operate on values that
have ``magic''. See <A HREF="#magic virtual tables">Magic Virtual Tables</A> later in this document.</P>
<P>If you know the name of a scalar variable, you can get a pointer to its SV
by using the following:</P>
<PRE>
SV* get_sv("package::varname", FALSE);</PRE>
<P>This returns NULL if the variable does not exist.</P>
<P>If you want to know if this variable (or any other SV) is actually <A HREF="../../lib/Pod/perlfunc.html#item_defined"><CODE>defined</CODE></A>,
you can call:</P>
<PRE>
SvOK(SV*)</PRE>
<P>The scalar <A HREF="../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A> value is stored in an SV instance called <CODE>PL_sv_undef</CODE>. Its
address can be used whenever an <CODE>SV*</CODE> is needed.</P>
<P>There are also the two values <CODE>PL_sv_yes</CODE> and <CODE>PL_sv_no</CODE>, which contain Boolean
TRUE and FALSE values, respectively. Like <CODE>PL_sv_undef</CODE>, their addresses can
be used whenever an <CODE>SV*</CODE> is needed.</P>
<P>Do not be fooled into thinking that <CODE>(SV *) 0</CODE> is the same as <CODE>&PL_sv_undef</CODE>.
Take this code:</P>
<PRE>
SV* sv = (SV*) 0;
if (I-am-to-return-a-real-value) {
sv = sv_2mortal(newSViv(42));
}
sv_setsv(ST(0), sv);</PRE>
<P>This code tries to return a new SV (which contains the value 42) if it should
return a real value, or undef otherwise. Instead it has returned a NULL
pointer which, somewhere down the line, will cause a segmentation violation,
bus error, or just weird results. Change the zero to <CODE>&PL_sv_undef</CODE> in the first
line and all will be well.</P>
<P>To free an SV that you've created, call <CODE>SvREFCNT_dec(SV*)</CODE>. Normally this
call is not necessary (see <A HREF="#reference counts and mortality">Reference Counts and Mortality</A>).</P>
<P>
<H2><A NAME="what's really stored in an sv">What's Really Stored in an SV?</A></H2>
<P>Recall that the usual method of determining the type of scalar you have is
to use <CODE>Sv*OK</CODE> macros. Because a scalar can be both a number and a string,
usually these macros will always return TRUE and calling the <CODE>Sv*V</CODE>
macros will do the appropriate conversion of string to integer/double or
integer/double to string.</P>
<P>If you <EM>really</EM> need to know if you have an integer, double, or string
pointer in an SV, you can use the following three macros instead:</P>
<PRE>
SvIOKp(SV*)
SvNOKp(SV*)
SvPOKp(SV*)</PRE>
<P>These will tell you if you truly have an integer, double, or string pointer
stored in your SV. The ``p'' stands for private.</P>
<P>In general, though, it's best to use the <CODE>Sv*V</CODE> macros.</P>
<P>
<H2><A NAME="working with avs">Working with AVs</A></H2>
<P>There are two ways to create and load an AV. The first method creates an
empty AV:</P>
<PRE>
AV* newAV();</PRE>
<P>The second method both creates the AV and initially populates it with SVs:</P>
<PRE>
AV* av_make(I32 num, SV **ptr);</PRE>
<P>The second argument points to an array containing <CODE>num</CODE> <CODE>SV*</CODE>'s. Once the
AV has been created, the SVs can be destroyed, if so desired.</P>
<P>Once the AV has been created, the following operations are possible on AVs:</P>
<PRE>
void av_push(AV*, SV*);
SV* av_pop(AV*);
SV* av_shift(AV*);
void av_unshift(AV*, I32 num);</PRE>
<P>These should be familiar operations, with the exception of <CODE>av_unshift</CODE>.
This routine adds <CODE>num</CODE> elements at the front of the array with the <A HREF="../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A>
value. You must then use <CODE>av_store</CODE> (described below) to assign values
to these new elements.</P>
<P>Here are some other functions:</P>
<PRE>
I32 av_len(AV*);
SV** av_fetch(AV*, I32 key, I32 lval);
SV** av_store(AV*, I32 key, SV* val);</PRE>
<P>The <CODE>av_len</CODE> function returns the highest index value in array (just
like $#array in Perl). If the array is empty, -1 is returned. The
<CODE>av_fetch</CODE> function returns the value at index <CODE>key</CODE>, but if <CODE>lval</CODE>
is non-zero, then <CODE>av_fetch</CODE> will store an undef value at that index.
The <CODE>av_store</CODE> function stores the value <CODE>val</CODE> at index <CODE>key</CODE>, and does
not increment the reference count of <CODE>val</CODE>. Thus the caller is responsible
for taking care of that, and if <CODE>av_store</CODE> returns NULL, the caller will
have to decrement the reference count to avoid a memory leak. Note that
<CODE>av_fetch</CODE> and <CODE>av_store</CODE> both return <CODE>SV**</CODE>'s, not <CODE>SV*</CODE>'s as their
return value.</P>
<PRE>
void av_clear(AV*);
void av_undef(AV*);
void av_extend(AV*, I32 key);</PRE>
<P>The <CODE>av_clear</CODE> function deletes all the elements in the AV* array, but
does not actually delete the array itself. The <CODE>av_undef</CODE> function will
delete all the elements in the array plus the array itself. The
<CODE>av_extend</CODE> function extends the array so that it contains at least <CODE>key+1</CODE>
elements. If <CODE>key+1</CODE> is less than the currently allocated length of the array,
then nothing is done.</P>
<P>If you know the name of an array variable, you can get a pointer to its AV
by using the following:</P>
<PRE>
AV* get_av("package::varname", FALSE);</PRE>
<P>This returns NULL if the variable does not exist.</P>
<P>See <A HREF="#understanding the magic of tied hashes and arrays">Understanding the Magic of Tied Hashes and Arrays</A> for more
information on how to use the array access functions on tied arrays.</P>
<P>
<H2><A NAME="working with hvs">Working with HVs</A></H2>
<P>To create an HV, you use the following routine:</P>
<PRE>
HV* newHV();</PRE>
<P>Once the HV has been created, the following operations are possible on HVs:</P>
<P>To check if you've got an object derived from a specific class you have
to write:</P>
<PRE>
if (sv_isobject(sv) && sv_derived_from(sv, class)) { ... }</PRE>
<P>
<H2><A NAME="creating new variables">Creating New Variables</A></H2>
<P>To create a new Perl variable with an undef value which can be accessed from
your Perl script, use the following routines, depending on the variable type.</P>
<PRE>
SV* get_sv("package::varname", TRUE);
AV* get_av("package::varname", TRUE);
HV* get_hv("package::varname", TRUE);</PRE>
<P>Notice the use of TRUE as the second parameter. The new variable can now
be set, using the routines appropriate to the data type.</P>
<P>There are additional macros whose values may be bitwise OR'ed with the
<CODE>TRUE</CODE> argument to enable certain extra features. Those bits are:</P>
<PRE>
GV_ADDMULTI Marks the variable as multiply defined, thus preventing the
"Name <varname> used only once: possible typo" warning.
GV_ADDWARN Issues the warning "Had to create <varname> unexpectedly" if
the variable did not exist before the function was called.</PRE>
<P>If you do not specify a package name, the variable is created in the current
package.</P>
<P>
<H2><A NAME="reference counts and mortality">Reference Counts and Mortality</A></H2>
<P>Perl uses an reference count-driven garbage collection mechanism. SVs,
AVs, or HVs (xV for short in the following) start their life with a
reference count of 1. If the reference count of an xV ever drops to 0,
then it will be destroyed and its memory made available for reuse.</P>
<P>This normally doesn't happen at the Perl level unless a variable is
undef'ed or the last variable holding a reference to it is changed or
overwritten. At the internal level, however, reference counts can be
manipulated with the following macros:</P>
<PRE>
int SvREFCNT(SV* sv);
SV* SvREFCNT_inc(SV* sv);
void SvREFCNT_dec(SV* sv);</PRE>
<P>However, there is one other function which manipulates the reference
count of its argument. The <CODE>newRV_inc</CODE> function, you will recall,
creates a reference to the specified argument. As a side effect,
it increments the argument's reference count. If this is not what
you want, use <CODE>newRV_noinc</CODE> instead.</P>
<P>For example, imagine you want to return a reference from an XSUB function.
Inside the XSUB routine, you create an SV which initially has a reference
count of one. Then you call <CODE>newRV_inc</CODE>, passing it the just-created SV.
This returns the reference as a new SV, but the reference count of the
SV you passed to <CODE>newRV_inc</CODE> has been incremented to two. Now you
return the reference from the XSUB routine and forget about the SV.
But Perl hasn't! Whenever the returned reference is destroyed, the
reference count of the original SV is decreased to one and nothing happens.
The SV will hang around without any way to access it until Perl itself
terminates. This is a memory leak.</P>
<P>The correct procedure, then, is to use <CODE>newRV_noinc</CODE> instead of
<CODE>newRV_inc</CODE>. Then, if and when the last reference is destroyed,
the reference count of the SV will go to zero and it will be destroyed,
stopping any memory leak.</P>
<P>There are some convenience functions available that can help with the
destruction of xVs. These functions introduce the concept of ``mortality''.
An xV that is mortal has had its reference count marked to be decremented,
but not actually decremented, until ``a short time later''. Generally the
term ``short time later'' means a single Perl statement, such as a call to
an XSUB function. The actual determinant for when mortal xVs have their
reference count decremented depends on two macros, SAVETMPS and FREETMPS.
See <A HREF="../../lib/Pod/perlcall.html">the perlcall manpage</A> and <A HREF="../../lib/Pod/perlxs.html">the perlxs manpage</A> for more details on these macros.</P>
<P>``Mortalization'' then is at its simplest a deferred <CODE>SvREFCNT_dec</CODE>.
However, if you mortalize a variable twice, the reference count will
later be decremented twice.</P>
<P>You should be careful about creating mortal variables. Strange things
can happen if you make the same value mortal within multiple contexts,
or if you make a variable mortal multiple times.</P>
<P>To create a mortal variable, use the functions:</P>
<PRE>
SV* sv_newmortal()
SV* sv_2mortal(SV*)
SV* sv_mortalcopy(SV*)</PRE>
<P>The first call creates a mortal SV, the second converts an existing
SV to a mortal SV (and thus defers a call to <CODE>SvREFCNT_dec</CODE>), and the
third creates a mortal copy of an existing SV.</P>
<P>The mortal routines are not just for SVs -- AVs and HVs can be
made mortal by passing their address (type-casted to <CODE>SV*</CODE>) to the
<CODE>sv_2mortal</CODE> or <CODE>sv_mortalcopy</CODE> routines.</P>
<P>
<H2><A NAME="stashes and globs">Stashes and Globs</A></H2>
<P>A ``stash'' is a hash that contains all of the different objects that
are contained within a package. Each key of the stash is a symbol
name (shared by all the different types of objects that have the same
name), and each value in the hash table is a GV (Glob Value). This GV
in turn contains references to the various objects of that name,
including (but not limited to) the following:</P>
<PRE>
Scalar Value
Array Value
Hash Value
I/O Handle
Format
Subroutine</PRE>
<P>There is a single stash called ``PL_defstash'' that holds the items that exist
in the ``main'' package. To get at the items in other packages, append the
string ``::'' to the package name. The items in the ``Foo'' package are in
the stash ``Foo::'' in PL_defstash. The items in the ``Bar::Baz'' package are
in the stash ``Baz::'' in ``Bar::'''s stash.</P>
<P>To get the stash pointer for a particular package, use the function:</P>
<PRE>
HV* gv_stashpv(const char* name, I32 create)
HV* gv_stashsv(SV*, I32 create)</PRE>
<P>The first function takes a literal string, the second uses the string stored
in the SV. Remember that a stash is just a hash table, so you get back an
<CODE>HV*</CODE>. The <CODE>create</CODE> flag will create a new package if it is set.</P>
<P>The name that <CODE>gv_stash*v</CODE> wants is the name of the package whose symbol table
you want. The default package is called <CODE>main</CODE>. If you have multiply nested
packages, pass their names to <CODE>gv_stash*v</CODE>, separated by <CODE>::</CODE> as in the Perl
language itself.</P>
<P>Alternately, if you have an SV that is a blessed reference, you can find
out the stash pointer by using:</P>
<PRE>
HV* SvSTASH(SvRV(SV*));</PRE>
<P>then use the following to get the package name itself:</P>
<PRE>
char* HvNAME(HV* stash);</PRE>
<P>If you need to bless or re-bless an object you can use the following
function:</P>
<PRE>
SV* sv_bless(SV*, HV* stash)</PRE>
<P>where the first argument, an <CODE>SV*</CODE>, must be a reference, and the second
argument is a stash. The returned <CODE>SV*</CODE> can now be used in the same way
as any other SV.</P>
<P>For more information on references and blessings, consult <A HREF="../../lib/Pod/perlref.html">the perlref manpage</A>.</P>
<P>The <CODE>sv</CODE> argument is a pointer to the SV that is to acquire a new magical
feature.</P>
<P>If <CODE>sv</CODE> is not already magical, Perl uses the <CODE>SvUPGRADE</CODE> macro to
set the <CODE>SVt_PVMG</CODE> flag for the <CODE>sv</CODE>. Perl then continues by adding
it to the beginning of the linked list of magical features. Any prior
entry of the same type of magic is deleted. Note that this can be
overridden, and multiple instances of the same type of magic can be
associated with an SV.</P>
<P>The <CODE>name</CODE> and <CODE>namlen</CODE> arguments are used to associate a string with
the magic, typically the name of a variable. <CODE>namlen</CODE> is stored in the
<CODE>mg_len</CODE> field and if <CODE>name</CODE> is non-null and <CODE>namlen</CODE> >= 0 a malloc'd
copy of the name is stored in <CODE>mg_ptr</CODE> field.</P>
<P>The sv_magic function uses <CODE>how</CODE> to determine which, if any, predefined
``Magic Virtual Table'' should be assigned to the <CODE>mg_virtual</CODE> field.
See the ``Magic Virtual Table'' section below. The <CODE>how</CODE> argument is also
stored in the <CODE>mg_type</CODE> field.</P>
<P>The <CODE>obj</CODE> argument is stored in the <CODE>mg_obj</CODE> field of the <CODE>MAGIC</CODE>
structure. If it is not the same as the <CODE>sv</CODE> argument, the reference
count of the <CODE>obj</CODE> object is incremented. If it is the same, or if
the <CODE>how</CODE> argument is ``#'', or if it is a NULL pointer, then <CODE>obj</CODE> is
merely stored, without the reference count being incremented.</P>
<P>There is also a function to add magic to an <A HREF="../../lib/Pod/perlguts.html#item_HV"><CODE>HV</CODE></A>:</P>
<PRE>
void hv_magic(HV *hv, GV *gv, int how);</PRE>
<P>This simply calls <CODE>sv_magic</CODE> and coerces the <CODE>gv</CODE> argument into an <A HREF="../../lib/Pod/perlguts.html#item_SV"><CODE>SV</CODE></A>.</P>
<P>To remove the magic from an SV, call the function sv_unmagic:</P>
<PRE>
void sv_unmagic(SV *sv, int type);</PRE>
<P>The <CODE>type</CODE> argument should be equal to the <CODE>how</CODE> value when the <A HREF="../../lib/Pod/perlguts.html#item_SV"><CODE>SV</CODE></A>
<P>This construction is <EM>approximately</EM> equivalent to</P>
<PRE>
{
my $oldvar = $var;
$var = 2;
...
$var = $oldvar;
}</PRE>
<P>The biggest difference is that the first construction would
reinstate the initial value of $var, irrespective of how control exits
the block: <A HREF="../../lib/Pod/perlfunc.html#item_goto"><CODE>goto</CODE></A>, <A HREF="../../lib/Pod/perlfunc.html#item_return"><CODE>return</CODE></A>, <A HREF="../../lib/Pod/perlfunc.html#item_die"><CODE>die</CODE></A>/<A HREF="../../lib/Pod/perlfunc.html#item_eval"><CODE>eval</CODE></A> etc. It is a little bit
more efficient as well.</P>
<P>There is a way to achieve a similar task from C via Perl API: create a
<EM>pseudo-block</EM>, and arrange for some changes to be automatically
undone at the end of it, either explicit, or via a non-local exit (via
die()). A <EM>block</EM>-like construct is created by a pair of
<CODE>ENTER</CODE>/<CODE>LEAVE</CODE> macros (see <A HREF="../../lib/Pod/perlcall.html#returning a scalar">Returning a Scalar in the perlcall manpage</A>).
Such a construct may be created specially for some important localized
task, or an existing one (like boundaries of enclosing Perl
subroutine/block, or an existing pair for freeing TMPs) may be
used. (In the second case the overhead of additional localization must
be almost negligible.) Note that any XSUB is automatically enclosed in
an <CODE>ENTER</CODE>/<CODE>LEAVE</CODE> pair.</P>
<P>Inside such a <EM>pseudo-block</EM> the following service is available:</P>
Duplicates the current value of <A HREF="../../lib/Pod/perlguts.html#item_SV"><CODE>SV</CODE></A>, on the exit from the current
<CODE>ENTER</CODE>/<CODE>LEAVE</CODE> <EM>pseudo-block</EM> will restore the value of <A HREF="../../lib/Pod/perlguts.html#item_SV"><CODE>SV</CODE></A>
<P>After the compile tree for a subroutine (or for an <A HREF="../../lib/Pod/perlfunc.html#item_eval"><CODE>eval</CODE></A> or a file)
is created, an additional pass over the code is performed. This pass
is neither top-down or bottom-up, but in the execution order (with
additional complications for conditionals). These optimizations are
done in the subroutine peep(). Optimizations performed at this stage
are subject to the same restrictions as in the pass 2.</P>
<P>
<HR>
<H1><A NAME="how multiple interpreters and concurrency are supported">How multiple interpreters and concurrency are supported</A></H1>
<P>WARNING: This information is subject to radical changes prior to
the Perl 5.6 release. Use with caution.</P>
<P>
<H2><A NAME="background and perl_implicit_context">Background and PERL_IMPLICIT_CONTEXT</A></H2>
<P>The Perl interpreter can be regarded as a closed box: it has an API
for feeding it code or otherwise making it do things, but it also has
functions for its own use. This smells a lot like an object, and
there are ways for you to build Perl so that you can have multiple
interpreters, with one interpreter represented either as a C++ object,
a C structure, or inside a thread. The thread, the C structure, or
the C++ object will contain all the context, the state of that
interpreter.</P>
<P>Three macros control the major Perl build flavors: MULTIPLICITY,
USE_THREADS and PERL_OBJECT. The MULTIPLICITY build has a C structure
that packages all the interpreter state, there is a similar thread-specific
data structure under USE_THREADS, and the PERL_OBJECT build has a C++
class to maintain interpreter state. In all three cases,
PERL_IMPLICIT_CONTEXT is also normally defined, and enables the
support for passing in a ``hidden'' first argument that represents all three
data structures.</P>
<P>All this obviously requires a way for the Perl internal functions to be
C++ methods, subroutines taking some kind of structure as the first
argument, or subroutines taking nothing as the first argument. To
enable these three very different ways of building the interpreter,
the Perl source (as it does in so many other situations) makes heavy
use of macros and subroutine naming conventions.</P>
<P>First problem: deciding which functions will be public API functions and
which will be private. All functions whose names begin <CODE>S_</CODE> are private
(think ``S'' for ``secret'' or ``static''). All other functions begin with
``Perl_'', but just because a function begins with ``Perl_'' does not mean it is
part of the API. The easiest way to be <STRONG>sure</STRONG> a function is part of the API
is to find its entry in <A HREF="../../lib/Pod/perlapi.html">the perlapi manpage</A>. If it exists in <A HREF="../../lib/Pod/perlapi.html">the perlapi manpage</A>, it's part
of the API. If it doesn't, and you think it should be (i.e., you need it fo
r your extension), send mail via <EM>perlbug</EM> explaining why you think it
should be.</P>
<P>(<A HREF="../../lib/Pod/perlapi.html">the perlapi manpage</A> itself is generated by embed.pl, a Perl script that generates
significant portions of the Perl source code. It has a list of almost
all the functions defined by the Perl interpreter along with their calling
characteristics and some flags. Functions that are part of the public API
are marked with an 'A' in its flags.)</P>
<P>Second problem: there must be a syntax so that the same subroutine
declarations and calls can pass a structure as their first argument,
or pass nothing. To solve this, the subroutines are named and
declared in a particular way. Here's a typical start of a static
function used within the Perl guts:</P>
<PRE>
STATIC void
S_incline(pTHX_ char *s)</PRE>
<P>STATIC becomes ``static'' in C, and is #define'd to nothing in C++.</P>
<P>A public function (i.e. part of the internal API, but not necessarily
sanctioned for use in extensions) begins like this:</P>
<PRE>
void
Perl_sv_setsv(pTHX_ SV* dsv, SV* ssv)</PRE>
<P><CODE>pTHX_</CODE> is one of a number of macros (in perl.h) that hide the
details of the interpreter's context. THX stands for ``thread'', ``this'',
or ``thingy'', as the case may be. (And no, George Lucas is not involved. :-)
The first character could be 'p' for a <STRONG>p</STRONG>rototype, 'a' for <STRONG>a</STRONG>rgument,
or 'd' for <STRONG>d</STRONG>eclaration.</P>
<P>When Perl is built without PERL_IMPLICIT_CONTEXT, there is no first
argument containing the interpreter's context. The trailing underscore
in the pTHX_ macro indicates that the macro expansion needs a comma
after the context argument because other arguments follow it. If
PERL_IMPLICIT_CONTEXT is not defined, pTHX_ will be ignored, and the
subroutine is not prototyped to take the extra argument. The form of the
macro without the trailing underscore is used when there are no additional
explicit arguments.</P>
<P>When a core function calls another, it must pass the context. This
is normally hidden via macros. Consider <CODE>sv_setsv</CODE>. It expands
something like this:</P>
<PRE>
ifdef PERL_IMPLICIT_CONTEXT
define sv_setsv(a,b) Perl_sv_setsv(aTHX_ a, b)
/* can't do this for vararg functions, see below */
else
define sv_setsv Perl_sv_setsv
endif</PRE>
<P>This works well, and means that XS authors can gleefully write:</P>
<PRE>
sv_setsv(foo, bar);</PRE>
<P>and still have it work under all the modes Perl could have been
compiled with.</P>
<P>Under PERL_OBJECT in the core, that will translate to either:</P>
<PRE>
CPerlObj::Perl_sv_setsv(foo,bar); # in CPerlObj functions,
# C++ takes care of 'this'
or</PRE>
<PRE>
pPerl->Perl_sv_setsv(foo,bar); # in truly static functions,
# see objXSUB.h</PRE>
<P>Under PERL_OBJECT in extensions (aka PERL_CAPI), or under
MULTIPLICITY/USE_THREADS w/ PERL_IMPLICIT_CONTEXT in both core
and extensions, it will be:</P>
<PRE>
Perl_sv_setsv(aTHX_ foo, bar); # the canonical Perl "API"
# for all build flavors</PRE>
<P>This doesn't work so cleanly for varargs functions, though, as macros
imply that the number of arguments is known in advance. Instead we
either need to spell them out fully, passing <CODE>aTHX_</CODE> as the first
argument (the Perl core tends to do this with functions like
Perl_warner), or use a context-free version.</P>
<P>The context-free version of Perl_warner is called
Perl_warner_nocontext, and does not take the extra argument. Instead
it does dTHX; to get the context from thread-local storage. We
<CODE>#define warner Perl_warner_nocontext</CODE> so that extensions get source
compatibility at the expense of performance. (Passing an arg is
cheaper than grabbing it from thread-local storage.)</P>
<P>You can ignore [pad]THX[xo] when browsing the Perl headers/sources.
Those are strictly for use within the core. Extensions and embedders
need only be aware of [pad]THX.</P>
<P>
<H2><A NAME="how do i use all this in extensions">How do I use all this in extensions?</A></H2>
<P>When Perl is built with PERL_IMPLICIT_CONTEXT, extensions that call
any functions in the Perl API will need to pass the initial context
argument somehow. The kicker is that you will need to write it in
such a way that the extension still compiles when Perl hasn't been
built with PERL_IMPLICIT_CONTEXT enabled.</P>
<P>There are three ways to do this. First, the easy but inefficient way,
which is also the default, in order to maintain source compatibility
with extensions: whenever XSUB.h is #included, it redefines the aTHX
and aTHX_ macros to call a function that will return the context.
Thus, something like:</P>
<PRE>
sv_setsv(asv, bsv);</PRE>
<P>in your extesion will translate to this when PERL_IMPLICIT_CONTEXT is
in effect:</P>
<PRE>
Perl_sv_setsv(Perl_get_context(), asv, bsv);</PRE>
<P>or to this otherwise:</P>
<PRE>
Perl_sv_setsv(asv, bsv);</PRE>
<P>You have to do nothing new in your extension to get this; since
the Perl library provides Perl_get_context(), it will all just
work.</P>
<P>The second, more efficient way is to use the following template for
your Foo.xs:</P>
<PRE>
#define PERL_NO_GET_CONTEXT /* we want efficiency */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"</PRE>
<PRE>
static my_private_function(int arg1, int arg2);</PRE>
<PRE>
static SV *
my_private_function(int arg1, int arg2)
{
dTHX; /* fetch context */
... call many Perl API functions ...
}</PRE>
<PRE>
[... etc ...]</PRE>
<PRE>
MODULE = Foo PACKAGE = Foo</PRE>
<PRE>
/* typical XSUB */</PRE>
<PRE>
void
my_xsub(arg)
int arg
CODE:
my_private_function(arg, 10);</PRE>
<P>Note that the only two changes from the normal way of writing an
extension is the addition of a <CODE>#define PERL_NO_GET_CONTEXT</CODE> before
including the Perl headers, followed by a <CODE>dTHX;</CODE> declaration at
the start of every function that will call the Perl API. (You'll
know which functions need this, because the C compiler will complain
that there's an undeclared identifier in those functions.) No changes
are needed for the XSUBs themselves, because the <CODE>XS()</CODE> macro is
correctly defined to pass in the implicit context if needed.</P>
<P>The third, even more efficient way is to ape how it is done within
the Perl guts:</P>
<PRE>
#define PERL_NO_GET_CONTEXT /* we want efficiency */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"</PRE>
<PRE>
/* pTHX_ only needed for functions that call Perl API */
static my_private_function(pTHX_ int arg1, int arg2);</PRE>
<PRE>
static SV *
my_private_function(pTHX_ int arg1, int arg2)
{
/* dTHX; not needed here, because THX is an argument */
... call Perl API functions ...
}</PRE>
<PRE>
[... etc ...]</PRE>
<PRE>
MODULE = Foo PACKAGE = Foo</PRE>
<PRE>
/* typical XSUB */</PRE>
<PRE>
void
my_xsub(arg)
int arg
CODE:
my_private_function(aTHX_ arg, 10);</PRE>
<P>This implementation never has to fetch the context using a function
call, since it is always passed as an extra argument. Depending on
your needs for simplicity or efficiency, you may mix the previous
two approaches freely.</P>
<P>Never add a comma after <CODE>pTHX</CODE> yourself--always use the form of the
macro with the underscore for functions that take explicit arguments,
or the form without the argument for functions with no explicit arguments.</P>
<P>
<H2><A NAME="future plans and perl_implicit_sys">Future Plans and PERL_IMPLICIT_SYS</A></H2>
<P>Just as PERL_IMPLICIT_CONTEXT provides a way to bundle up everything
that the interpreter knows about itself and pass it around, so too are
there plans to allow the interpreter to bundle up everything it knows
about the environment it's running on. This is enabled with the
PERL_IMPLICIT_SYS macro. Currently it only works with PERL_OBJECT,
but is mostly there for MULTIPLICITY and USE_THREADS (see inside
iperlsys.h).</P>
<P>This allows the ability to provide an extra pointer (called the ``host''
environment) for all the system calls. This makes it possible for
all the system stuff to maintain their own state, broken down into
seven C structures. These are thin wrappers around the usual system
calls (see win32/perllib.c) for the default perl executable, but for a
more ambitious host (like the one that would do <A HREF="../../lib/Pod/perlfunc.html#item_fork"><CODE>fork()</CODE></A> emulation) all
the extra work needed to pretend that different interpreters are
actually different ``processes'', would be done here.</P>
<P>The Perl engine/interpreter and the host are orthogonal entities.
There could be one or more interpreters in a process, and one or
more ``hosts'', with free association between them.</P>
<P>
<HR>
<H1><A NAME="authors">AUTHORS</A></H1>
<P>Until May 1997, this document was maintained by Jeff Okamoto
<<A HREF="mailto:okamoto@corp.hp.com">okamoto@corp.hp.com</A>>. It is now maintained as part of Perl itself
by the Perl 5 Porters <<A HREF="mailto:perl5-porters@perl.org">perl5-porters@perl.org</A>>.</P>
<P>With lots of help and suggestions from Dean Roehrich, Malcolm Beattie,
Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil
Bowers, Matthew Green, Tim Bunce, Spider Boardman, Ulrich Pfeifer,
Stephen McCamant, and Gurusamy Sarathy.</P>
<P>API Listing originally by Dean Roehrich <<A HREF="mailto:roehrich@cray.com">roehrich@cray.com</A>>.</P>
<P>Modifications to autogenerate the API listing (<A HREF="../../lib/Pod/perlapi.html">the perlapi manpage</A>) by Benjamin