<STRONG><P CLASS=block> perlembed - how to embed perl in your C program</P></STRONG>
</TD></TR>
</TABLE>
<A NAME="__index__"></A>
<!-- INDEX BEGIN -->
<UL>
<LI><A HREF="#name">NAME</A></LI>
<LI><A HREF="#description">DESCRIPTION</A></LI>
<UL>
<LI><A HREF="#preamble">PREAMBLE</A></LI>
<LI><A HREF="#roadmap">ROADMAP</A></LI>
<LI><A HREF="#compiling your c program">Compiling your C program</A></LI>
<LI><A HREF="#adding a perl interpreter to your c program">Adding a Perl interpreter to your C program</A></LI>
<LI><A HREF="#calling a perl subroutine from your c program">Calling a Perl subroutine from your C program</A></LI>
<LI><A HREF="#evaluating a perl statement from your c program">Evaluating a Perl statement from your C program</A></LI>
<LI><A HREF="#performing perl pattern matches and substitutions from your c program">Performing Perl pattern matches and substitutions from your C program</A></LI>
<LI><A HREF="#fiddling with the perl stack from your c program">Fiddling with the Perl stack from your C program</A></LI>
<LI><A HREF="#maintaining a persistent interpreter">Maintaining a persistent interpreter</A></LI>
<LI><A HREF="#using perl modules, which themselves use c libraries, from your c program">Using Perl modules, which themselves use C libraries, from your C program</A></LI>
</UL>
<LI><A HREF="#embedding perl under win32">Embedding Perl under Win32</A></LI>
<LI><A HREF="#moral">MORAL</A></LI>
<LI><A HREF="#author">AUTHOR</A></LI>
<LI><A HREF="#copyright">COPYRIGHT</A></LI>
</UL>
<!-- INDEX END -->
<HR>
<P>
<H1><A NAME="name">NAME</A></H1>
<P>perlembed - how to embed perl in your C program</P>
<P>
<HR>
<H1><A NAME="description">DESCRIPTION</A></H1>
<P>
<H2><A NAME="preamble">PREAMBLE</A></H2>
<P>Do you want to:</P>
<DL>
<DT><STRONG><A NAME="item_Use_C_from_Perl%3F"><STRONG>Use C from Perl?</STRONG></A></STRONG><BR>
<DT><STRONG><A NAME="item_Use_a_Unix_program_from_Perl%3F"><STRONG>Use a Unix program from Perl?</STRONG></A></STRONG><BR>
<DD>
Read about back-quotes and about <A HREF="../../lib/Pod/perlfunc.html#item_system"><CODE>system</CODE></A> and <A HREF="../../lib/Pod/perlfunc.html#item_exec"><CODE>exec</CODE></A> in <A HREF="../../lib/Pod/perlfunc.html">the perlfunc manpage</A>.
<P></P>
<DT><STRONG><A NAME="item_Use_Perl_from_Perl%3F"><STRONG>Use Perl from Perl?</STRONG></A></STRONG><BR>
<DD>
Read about <A HREF="../../lib/Pod/perlfunc.html#do">do in the perlfunc manpage</A> and <A HREF="../../lib/Pod/perlfunc.html#eval">eval in the perlfunc manpage</A> and <A HREF="../../lib/Pod/perlfunc.html#require">require in the perlfunc manpage</A>
and <A HREF="../../lib/Pod/perlfunc.html#use">use in the perlfunc manpage</A>.
<P></P>
<DT><STRONG><A NAME="item_Use_C_from_C%3F"><STRONG>Use C from C?</STRONG></A></STRONG><BR>
<DD>
Rethink your design.
<P></P>
<DT><STRONG><A NAME="item_Use_Perl_from_C%3F"><STRONG>Use Perl from C?</STRONG></A></STRONG><BR>
<DD>
Read on...
<P></P></DL>
<P>
<H2><A NAME="roadmap">ROADMAP</A></H2>
<P><A HREF="#compiling your c program">Compiling your C program</A></P>
<P><A HREF="#adding a perl interpreter to your c program">Adding a Perl interpreter to your C program</A></P>
<P><A HREF="#calling a perl subroutine from your c program">Calling a Perl subroutine from your C program</A></P>
<P><A HREF="#evaluating a perl statement from your c program">Evaluating a Perl statement from your C program</A></P>
<P><A HREF="#performing perl pattern matches and substitutions from your c program">Performing Perl pattern matches and substitutions from your C program</A></P>
<P><A HREF="#fiddling with the perl stack from your c program">Fiddling with the Perl stack from your C program</A></P>
<P><A HREF="#maintaining a persistent interpreter">Maintaining a persistent interpreter</A></P>
<P><A HREF="#using perl modules, which themselves use c libraries, from your c program">Using Perl modules, which themselves use C libraries, from your C program</A></P>
<P><A HREF="#embedding perl under win32">Embedding Perl under Win32</A></P>
<P>
<H2><A NAME="compiling your c program">Compiling your C program</A></H2>
<P>If you have trouble compiling the scripts in this documentation,
you're not alone. The cardinal rule: COMPILE THE PROGRAMS IN EXACTLY
THE SAME WAY THAT YOUR PERL WAS COMPILED. (Sorry for yelling.)</P>
<P>Also, every C program that uses Perl must link in the <EM>perl library</EM>.
What's that, you ask? Perl is itself written in C; the perl library
is the collection of compiled C programs that were used to create your
perl executable (<EM>/usr/bin/perl</EM> or equivalent). (Corollary: you
can't use Perl from your C program unless Perl has been compiled on
your machine, or installed properly--that's why you shouldn't blithely
copy Perl executables from machine to machine without also copying the
<EM>lib</EM> directory.)</P>
<P>When you use Perl from C, your C program will--usually--allocate,
``run'', and deallocate a <EM>PerlInterpreter</EM> object, which is defined by
the perl library.</P>
<P>If your copy of Perl is recent enough to contain this documentation
(version 5.002 or later), then the perl library (and <EM>EXTERN.h</EM> and
<EM>perl.h</EM>, which you'll also need) will reside in a directory
<P>yielding the number of seconds that elapsed between January 1, 1970
(the beginning of the Unix epoch), and the moment I began writing this
sentence.</P>
<P>In this particular case we don't have to call <EM>perl_run</EM>, but in
general it's considered good practice to ensure proper initialization
of library code, including execution of all object <CODE>DESTROY</CODE> methods
and package <CODE>END {}</CODE> blocks.</P>
<P>If you want to pass arguments to the Perl subroutine, you can add
strings to the <CODE>NULL</CODE>-terminated <CODE>args</CODE> list passed to
<EM>call_argv</EM>. For other data types, or to examine return values,
you'll need to manipulate the Perl stack. That's demonstrated in the
last section of this document: <A HREF="#fiddling with the perl stack from your c program">Fiddling with the Perl stack from your C program</A>.</P>
<P>
<H2><A NAME="evaluating a perl statement from your c program">Evaluating a Perl statement from your C program</A></H2>
<P>Perl provides two API functions to evaluate pieces of Perl code.
These are <A HREF="../../lib/Pod/perlapi.html#eval_sv">eval_sv in the perlapi manpage</A> and <A HREF="../../lib/Pod/perlapi.html#eval_pv">eval_pv in the perlapi manpage</A>.</P>
<P>Arguably, these are the only routines you'll ever need to execute
snippets of Perl code from within your C program. Your code can be as
long as you wish; it can contain multiple statements; it can employ
<A HREF="../../lib/Pod/perlfunc.html#use">use in the perlfunc manpage</A>, <A HREF="../../lib/Pod/perlfunc.html#require">require in the perlfunc manpage</A>, and <A HREF="../../lib/Pod/perlfunc.html#do">do in the perlfunc manpage</A> to
include external Perl files.</P>
<P><EM>eval_pv</EM> lets us evaluate individual Perl strings, and then
extract variables for coercion into C types. The following program,
<EM>string.c</EM>, executes three Perl strings, extracting an <A HREF="../../lib/Pod/perlfunc.html#item_int"><CODE>int</CODE></A> from
the first, a <CODE>float</CODE> from the second, and a <CODE>char *</CODE> from the third.</P>
<P>All of those strange functions with <EM>sv</EM> in their names help convert Perl scalars to C types. They're described in <A HREF="../../lib/Pod/perlguts.html">the perlguts manpage</A> and <A HREF="../../lib/Pod/perlapi.html">the perlapi manpage</A>.</P>
<P>If you compile and run <EM>string.c</EM>, you'll see the results of using
<EM>SvIV()</EM> to create an <A HREF="../../lib/Pod/perlfunc.html#item_int"><CODE>int</CODE></A>, <EM>SvNV()</EM> to create a <CODE>float</CODE>, and
<EM>SvPV()</EM> to create a string:</P>
<PRE>
a = 9
a = 9.859600
a = Just Another Perl Hacker</PRE>
<P>In the example above, we've created a global variable to temporarily
store the computed value of our eval'd expression. It is also
possible and in most cases a better strategy to fetch the return value
<P>This way, we avoid namespace pollution by not creating global
variables and we've simplified our code as well.</P>
<P>
<H2><A NAME="performing perl pattern matches and substitutions from your c program">Performing Perl pattern matches and substitutions from your C program</A></H2>
<P>The <EM>eval_sv()</EM> function lets us evaluate strings of Perl code, so we can
define some functions that use it to ``specialize'' in matches and
substitutions: <EM>match()</EM>, <EM>substitute()</EM>, and <EM>matches()</EM>.</P>
<PRE>
I32 match(SV *string, char *pattern);</PRE>
<P>Given a string and a pattern (e.g., <CODE>m/clasp/</CODE> or <CODE>/\b\w*\b/</CODE>, which
in your C program might appear as ``/\\b\\w*\\b/''), <CODE>match()</CODE>
returns 1 if the string matches the pattern and 0 otherwise.</P>
<PRE>
int substitute(SV **string, char *pattern);</PRE>
<P>Given a pointer to an <A HREF="../../lib/Pod/perlguts.html#item_SV"><CODE>SV</CODE></A> and an <CODE>=~</CODE> operation (e.g.,
<CODE>s/bob/robert/g</CODE> or <CODE>tr[A-Z][a-z]</CODE>), <CODE>substitute()</CODE> modifies the string
within the <A HREF="../../lib/Pod/perlguts.html#item_AV"><CODE>AV</CODE></A> at according to the operation, returning the number of substitutions
made.</P>
<PRE>
int matches(SV *string, char *pattern, AV **matches);</PRE>
<P>Given an <A HREF="../../lib/Pod/perlguts.html#item_SV"><CODE>SV</CODE></A>, a pattern, and a pointer to an empty <A HREF="../../lib/Pod/perlguts.html#item_AV"><CODE>AV</CODE></A>,
<CODE>matches()</CODE> evaluates <CODE>$string =~ $pattern</CODE> in an array context, and
fills in <EM>matches</EM> with the array elements, returning the number of matches found.</P>
<P>Here's a sample program, <EM>match.c</EM>, that uses all three (long lines have
been wrapped here):</P>
<PRE>
#include <EXTERN.h>
#include <perl.h></PRE>
<PRE>
/** my_eval_sv(code, error_check)
** kinda like eval_sv(),
** but we pop the return value off the stack
**/
SV* my_eval_sv(SV *sv, I32 croak_on_error)
{
dSP;
SV* retval;
STRLEN n_a;</PRE>
<PRE>
PUSHMARK(SP);
eval_sv(sv, G_SCALAR);</PRE>
<PRE>
SPAGAIN;
retval = POPs;
PUTBACK;</PRE>
<PRE>
if (croak_on_error && SvTRUE(ERRSV))
croak(SvPVx(ERRSV, n_a));</PRE>
<PRE>
return retval;
}</PRE>
<PRE>
/** match(string, pattern)
**
** Used for matches in a scalar context.
**
** Returns 1 if the match was successful; 0 otherwise.
**/</PRE>
<PRE>
I32 match(SV *string, char *pattern)
{
SV *command = NEWSV(1099, 0), *retval;
STRLEN n_a;</PRE>
<PRE>
sv_setpvf(command, "my $string = '%s'; $string =~ %s",
SvPV(string,n_a), pattern);</PRE>
<PRE>
retval = my_eval_sv(command, TRUE);
SvREFCNT_dec(command);</PRE>
<PRE>
return SvIV(retval);
}</PRE>
<PRE>
/** substitute(string, pattern)
**
** Used for =~ operations that modify their left-hand side (s/// and tr///)
sv_setpv(text, "When he is at a convenience store and the bill comes to some amount like 76 cents, Maynard is aware that there is something he *should* do, something that will enable him to get back a quarter, but he has no idea *what*. He fumbles through his red squeezey changepurse and gives the boy three extra pennies with his dollar, hoping that he might luck into the correct amount. The boy gives him back two of his own pennies and then the big shiny quarter that is his prize. -RICHH");</PRE>
<PRE>
if (match(text, "m/quarter/")) /** Does text contain 'quarter'? **/
printf("match: Text contains the word 'quarter'.\n\n");
else
printf("match: Text doesn't contain the word 'quarter'.\n\n");</PRE>
<PRE>
if (match(text, "m/eighth/")) /** Does text contain 'eighth'? **/
printf("match: Text contains the word 'eighth'.\n\n");
else
printf("match: Text doesn't contain the word 'eighth'.\n\n");</PRE>
<H2><A NAME="fiddling with the perl stack from your c program">Fiddling with the Perl stack from your C program</A></H2>
<P>When trying to explain stacks, most computer science textbooks mumble
something about spring-loaded columns of cafeteria plates: the last
thing you pushed on the stack is the first thing you pop off. That'll
do for our purposes: your C program will push some arguments onto ``the Perl
stack'', shut its eyes while some magic happens, and then pop the
results--the return value of your Perl subroutine--off the stack.</P>
<P>First you'll need to know how to convert between C types and Perl
types, with <CODE>newSViv()</CODE> and <CODE>sv_setnv()</CODE> and <CODE>newAV()</CODE> and all their
friends. They're described in <A HREF="../../lib/Pod/perlguts.html">the perlguts manpage</A> and <A HREF="../../lib/Pod/perlapi.html">the perlapi manpage</A>.</P>
<P>Then you'll need to know how to manipulate the Perl stack. That's
described in <A HREF="../../lib/Pod/perlcall.html">the perlcall manpage</A>.</P>
<P>Once you've understood those, embedding Perl in C is easy.</P>
<P>Because C has no builtin function for integer exponentiation, let's
make Perl's ** operator available to it (this is less useful than it
sounds, because Perl implements ** with C's <EM>pow()</EM> function). First
I'll create a stub exponentiation function in <EM>power.pl</EM>:</P>
<PRE>
sub expo {
my ($a, $b) = @_;
return $a ** $b;
}</PRE>
<P>Now I'll create a C program, <EM>power.c</EM>, with a function
<EM>PerlPower()</EM> that contains all the perlguts necessary to push the
two arguments into <EM>expo()</EM> and to pop the return value out. Take a
deep breath...</P>
<PRE>
#include <EXTERN.h>
#include <perl.h></PRE>
<PRE>
static PerlInterpreter *my_perl;</PRE>
<PRE>
static void
PerlPower(int a, int b)
{
dSP; /* initialize stack pointer */
ENTER; /* everything created after here */
SAVETMPS; /* ...is a temporary variable. */
PUSHMARK(SP); /* remember the stack pointer */
XPUSHs(sv_2mortal(newSViv(a))); /* push the base onto the stack */
XPUSHs(sv_2mortal(newSViv(b))); /* push the exponent onto stack */
PUTBACK; /* make local stack pointer global */
call_pv("expo", G_SCALAR); /* call the function */
SPAGAIN; /* refresh stack pointer */
/* pop the return value from stack */
printf ("%d to the %dth power is %d.\n", a, b, POPi);
<H2><A NAME="using perl modules, which themselves use c libraries, from your c program">Using Perl modules, which themselves use C libraries, from your C program</A></H2>
<P>If you've played with the examples above and tried to embed a script
that <EM>use()</EM>s a Perl module (such as <EM>Socket</EM>) which itself uses a C or C++ library,
this probably happened:</P>
<PRE>
Can't load module Socket, dynamic loading not available in this perl.
(You may need to build a new perl executable which either supports
dynamic loading or has the Socket module statically linked into it.)</PRE>
<P>What's wrong?</P>
<P>Your interpreter doesn't know how to communicate with these extensions
on its own. A little glue will help. Up until now you've been
calling <EM>perl_parse()</EM>, handing it NULL for the second argument:</P>