1N/A=head1 NAME
1N/A
1N/Aperlembed - how to embed perl in your C program
1N/A
1N/A=head1 DESCRIPTION
1N/A
1N/A=head2 PREAMBLE
1N/A
1N/ADo you want to:
1N/A
1N/A=over 5
1N/A
1N/A=item B<Use C from Perl?>
1N/A
1N/ARead L<perlxstut>, L<perlxs>, L<h2xs>, L<perlguts>, and L<perlapi>.
1N/A
1N/A=item B<Use a Unix program from Perl?>
1N/A
1N/ARead about back-quotes and about C<system> and C<exec> in L<perlfunc>.
1N/A
1N/A=item B<Use Perl from Perl?>
1N/A
1N/ARead about L<perlfunc/do> and L<perlfunc/eval> and L<perlfunc/require>
1N/Aand L<perlfunc/use>.
1N/A
1N/A=item B<Use C from C?>
1N/A
1N/ARethink your design.
1N/A
1N/A=item B<Use Perl from C?>
1N/A
1N/ARead on...
1N/A
1N/A=back
1N/A
1N/A=head2 ROADMAP
1N/A
1N/A=over 5
1N/A
1N/A=item *
1N/A
1N/ACompiling your C program
1N/A
1N/A=item *
1N/A
1N/AAdding a Perl interpreter to your C program
1N/A
1N/A=item *
1N/A
1N/ACalling a Perl subroutine from your C program
1N/A
1N/A=item *
1N/A
1N/AEvaluating a Perl statement from your C program
1N/A
1N/A=item *
1N/A
1N/APerforming Perl pattern matches and substitutions from your C program
1N/A
1N/A=item *
1N/A
1N/AFiddling with the Perl stack from your C program
1N/A
1N/A=item *
1N/A
1N/AMaintaining a persistent interpreter
1N/A
1N/A=item *
1N/A
1N/AMaintaining multiple interpreter instances
1N/A
1N/A=item *
1N/A
1N/AUsing Perl modules, which themselves use C libraries, from your C program
1N/A
1N/A=item *
1N/A
1N/AEmbedding Perl under Win32
1N/A
1N/A=back
1N/A
1N/A=head2 Compiling your C program
1N/A
1N/AIf you have trouble compiling the scripts in this documentation,
1N/Ayou're not alone. The cardinal rule: COMPILE THE PROGRAMS IN EXACTLY
1N/ATHE SAME WAY THAT YOUR PERL WAS COMPILED. (Sorry for yelling.)
1N/A
1N/AAlso, every C program that uses Perl must link in the I<perl library>.
1N/AWhat's that, you ask? Perl is itself written in C; the perl library
1N/Ais the collection of compiled C programs that were used to create your
1N/Aperl executable (I</usr/bin/perl> or equivalent). (Corollary: you
1N/Acan't use Perl from your C program unless Perl has been compiled on
1N/Ayour machine, or installed properly--that's why you shouldn't blithely
1N/Acopy Perl executables from machine to machine without also copying the
1N/AI<lib> directory.)
1N/A
1N/AWhen you use Perl from C, your C program will--usually--allocate,
1N/A"run", and deallocate a I<PerlInterpreter> object, which is defined by
1N/Athe perl library.
1N/A
1N/AIf your copy of Perl is recent enough to contain this documentation
1N/A(version 5.002 or later), then the perl library (and I<EXTERN.h> and
1N/AI<perl.h>, which you'll also need) will reside in a directory
1N/Athat looks like this:
1N/A
1N/A /usr/local/lib/perl5/your_architecture_here/CORE
1N/A
1N/Aor perhaps just
1N/A
1N/A /usr/local/lib/perl5/CORE
1N/A
1N/Aor maybe something like
1N/A
1N/A /usr/opt/perl5/CORE
1N/A
1N/AExecute this statement for a hint about where to find CORE:
1N/A
1N/A perl -MConfig -e 'print $Config{archlib}'
1N/A
1N/AHere's how you'd compile the example in the next section,
1N/AL<Adding a Perl interpreter to your C program>, on my Linux box:
1N/A
1N/A % gcc -O2 -Dbool=char -DHAS_BOOL -I/usr/local/include
1N/A -I/usr/local/lib/perl5/i586-linux/5.003/CORE
1N/A -L/usr/local/lib/perl5/i586-linux/5.003/CORE
1N/A -o interp interp.c -lperl -lm
1N/A
1N/A(That's all one line.) On my DEC Alpha running old 5.003_05, the
1N/Aincantation is a bit different:
1N/A
1N/A % cc -O2 -Olimit 2900 -DSTANDARD_C -I/usr/local/include
1N/A -I/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE
1N/A -L/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE -L/usr/local/lib
1N/A -D__LANGUAGE_C__ -D_NO_PROTO -o interp interp.c -lperl -lm
1N/A
1N/AHow can you figure out what to add? Assuming your Perl is post-5.001,
1N/Aexecute a C<perl -V> command and pay special attention to the "cc" and
1N/A"ccflags" information.
1N/A
1N/AYou'll have to choose the appropriate compiler (I<cc>, I<gcc>, et al.) for
1N/Ayour machine: C<perl -MConfig -e 'print $Config{cc}'> will tell you what
1N/Ato use.
1N/A
1N/AYou'll also have to choose the appropriate library directory
1N/A(I</usr/local/lib/...>) for your machine. If your compiler complains
1N/Athat certain functions are undefined, or that it can't locate
1N/AI<-lperl>, then you need to change the path following the C<-L>. If it
1N/Acomplains that it can't find I<EXTERN.h> and I<perl.h>, you need to
1N/Achange the path following the C<-I>.
1N/A
1N/AYou may have to add extra libraries as well. Which ones?
1N/APerhaps those printed by
1N/A
1N/A perl -MConfig -e 'print $Config{libs}'
1N/A
1N/AProvided your perl binary was properly configured and installed the
1N/AB<ExtUtils::Embed> module will determine all of this information for
1N/Ayou:
1N/A
1N/A % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
1N/A
1N/AIf the B<ExtUtils::Embed> module isn't part of your Perl distribution,
1N/Ayou can retrieve it from
1N/Ahttp://www.perl.com/perl/CPAN/modules/by-module/ExtUtils/
1N/A(If this documentation came from your Perl distribution, then you're
1N/Arunning 5.004 or better and you already have it.)
1N/A
1N/AThe B<ExtUtils::Embed> kit on CPAN also contains all source code for
1N/Athe examples in this document, tests, additional examples and other
1N/Ainformation you may find useful.
1N/A
1N/A=head2 Adding a Perl interpreter to your C program
1N/A
1N/AIn a sense, perl (the C program) is a good example of embedding Perl
1N/A(the language), so I'll demonstrate embedding with I<miniperlmain.c>,
1N/Aincluded in the source distribution. Here's a bastardized, nonportable
1N/Aversion of I<miniperlmain.c> containing the essentials of embedding:
1N/A
1N/A #include <EXTERN.h> /* from the Perl distribution */
1N/A #include <perl.h> /* from the Perl distribution */
1N/A
1N/A static PerlInterpreter *my_perl; /*** The Perl interpreter ***/
1N/A
1N/A int main(int argc, char **argv, char **env)
1N/A {
1N/A PERL_SYS_INIT3(&argc,&argv,&env);
1N/A my_perl = perl_alloc();
1N/A perl_construct(my_perl);
1N/A PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1N/A perl_parse(my_perl, NULL, argc, argv, (char **)NULL);
1N/A perl_run(my_perl);
1N/A perl_destruct(my_perl);
1N/A perl_free(my_perl);
1N/A PERL_SYS_TERM();
1N/A }
1N/A
1N/ANotice that we don't use the C<env> pointer. Normally handed to
1N/AC<perl_parse> as its final argument, C<env> here is replaced by
1N/AC<NULL>, which means that the current environment will be used. The macros
1N/APERL_SYS_INIT3() and PERL_SYS_TERM() provide system-specific tune up
1N/Aof the C runtime environment necessary to run Perl interpreters; since
1N/APERL_SYS_INIT3() may change C<env>, it may be more appropriate to provide
1N/AC<env> as an argument to perl_parse().
1N/A
1N/ANow compile this program (I'll call it I<interp.c>) into an executable:
1N/A
1N/A % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
1N/A
1N/AAfter a successful compilation, you'll be able to use I<interp> just
1N/Alike perl itself:
1N/A
1N/A % interp
1N/A print "Pretty Good Perl \n";
1N/A print "10890 - 9801 is ", 10890 - 9801;
1N/A <CTRL-D>
1N/A Pretty Good Perl
1N/A 10890 - 9801 is 1089
1N/A
1N/Aor
1N/A
1N/A % interp -e 'printf("%x", 3735928559)'
1N/A deadbeef
1N/A
1N/AYou can also read and execute Perl statements from a file while in the
1N/Amidst of your C program, by placing the filename in I<argv[1]> before
1N/Acalling I<perl_run>.
1N/A
1N/A=head2 Calling a Perl subroutine from your C program
1N/A
1N/ATo call individual Perl subroutines, you can use any of the B<call_*>
1N/Afunctions documented in L<perlcall>.
1N/AIn this example we'll use C<call_argv>.
1N/A
1N/AThat's shown below, in a program I'll call I<showtime.c>.
1N/A
1N/A #include <EXTERN.h>
1N/A #include <perl.h>
1N/A
1N/A static PerlInterpreter *my_perl;
1N/A
1N/A int main(int argc, char **argv, char **env)
1N/A {
1N/A char *args[] = { NULL };
1N/A PERL_SYS_INIT3(&argc,&argv,&env);
1N/A my_perl = perl_alloc();
1N/A perl_construct(my_perl);
1N/A
1N/A perl_parse(my_perl, NULL, argc, argv, NULL);
1N/A PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1N/A
1N/A /*** skipping perl_run() ***/
1N/A
1N/A call_argv("showtime", G_DISCARD | G_NOARGS, args);
1N/A
1N/A perl_destruct(my_perl);
1N/A perl_free(my_perl);
1N/A PERL_SYS_TERM();
1N/A }
1N/A
1N/Awhere I<showtime> is a Perl subroutine that takes no arguments (that's the
1N/AI<G_NOARGS>) and for which I'll ignore the return value (that's the
1N/AI<G_DISCARD>). Those flags, and others, are discussed in L<perlcall>.
1N/A
1N/AI'll define the I<showtime> subroutine in a file called I<showtime.pl>:
1N/A
1N/A print "I shan't be printed.";
1N/A
1N/A sub showtime {
1N/A print time;
1N/A }
1N/A
1N/ASimple enough. Now compile and run:
1N/A
1N/A % cc -o showtime showtime.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
1N/A
1N/A % showtime showtime.pl
1N/A 818284590
1N/A
1N/Ayielding the number of seconds that elapsed between January 1, 1970
1N/A(the beginning of the Unix epoch), and the moment I began writing this
1N/Asentence.
1N/A
1N/AIn this particular case we don't have to call I<perl_run>, as we set
1N/Athe PL_exit_flag PERL_EXIT_DESTRUCT_END which executes END blocks in
1N/Aperl_destruct.
1N/A
1N/AIf you want to pass arguments to the Perl subroutine, you can add
1N/Astrings to the C<NULL>-terminated C<args> list passed to
1N/AI<call_argv>. For other data types, or to examine return values,
1N/Ayou'll need to manipulate the Perl stack. That's demonstrated in
1N/AL<Fiddling with the Perl stack from your C program>.
1N/A
1N/A=head2 Evaluating a Perl statement from your C program
1N/A
1N/APerl provides two API functions to evaluate pieces of Perl code.
1N/AThese are L<perlapi/eval_sv> and L<perlapi/eval_pv>.
1N/A
1N/AArguably, these are the only routines you'll ever need to execute
1N/Asnippets of Perl code from within your C program. Your code can be as
1N/Along as you wish; it can contain multiple statements; it can employ
1N/AL<perlfunc/use>, L<perlfunc/require>, and L<perlfunc/do> to
1N/Ainclude external Perl files.
1N/A
1N/AI<eval_pv> lets us evaluate individual Perl strings, and then
1N/Aextract variables for coercion into C types. The following program,
1N/AI<string.c>, executes three Perl strings, extracting an C<int> from
1N/Athe first, a C<float> from the second, and a C<char *> from the third.
1N/A
1N/A #include <EXTERN.h>
1N/A #include <perl.h>
1N/A
1N/A static PerlInterpreter *my_perl;
1N/A
1N/A main (int argc, char **argv, char **env)
1N/A {
1N/A STRLEN n_a;
1N/A char *embedding[] = { "", "-e", "0" };
1N/A
1N/A PERL_SYS_INIT3(&argc,&argv,&env);
1N/A my_perl = perl_alloc();
1N/A perl_construct( my_perl );
1N/A
1N/A perl_parse(my_perl, NULL, 3, embedding, NULL);
1N/A PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1N/A perl_run(my_perl);
1N/A
1N/A /** Treat $a as an integer **/
1N/A eval_pv("$a = 3; $a **= 2", TRUE);
1N/A printf("a = %d\n", SvIV(get_sv("a", FALSE)));
1N/A
1N/A /** Treat $a as a float **/
1N/A eval_pv("$a = 3.14; $a **= 2", TRUE);
1N/A printf("a = %f\n", SvNV(get_sv("a", FALSE)));
1N/A
1N/A /** Treat $a as a string **/
1N/A eval_pv("$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);", TRUE);
1N/A printf("a = %s\n", SvPV(get_sv("a", FALSE), n_a));
1N/A
1N/A perl_destruct(my_perl);
1N/A perl_free(my_perl);
1N/A PERL_SYS_TERM();
1N/A }
1N/A
1N/AAll of those strange functions with I<sv> in their names help convert Perl scalars to C types. They're described in L<perlguts> and L<perlapi>.
1N/A
1N/AIf you compile and run I<string.c>, you'll see the results of using
1N/AI<SvIV()> to create an C<int>, I<SvNV()> to create a C<float>, and
1N/AI<SvPV()> to create a string:
1N/A
1N/A a = 9
1N/A a = 9.859600
1N/A a = Just Another Perl Hacker
1N/A
1N/AIn the example above, we've created a global variable to temporarily
1N/Astore the computed value of our eval'd expression. It is also
1N/Apossible and in most cases a better strategy to fetch the return value
1N/Afrom I<eval_pv()> instead. Example:
1N/A
1N/A ...
1N/A STRLEN n_a;
1N/A SV *val = eval_pv("reverse 'rekcaH lreP rehtonA tsuJ'", TRUE);
1N/A printf("%s\n", SvPV(val,n_a));
1N/A ...
1N/A
1N/AThis way, we avoid namespace pollution by not creating global
1N/Avariables and we've simplified our code as well.
1N/A
1N/A=head2 Performing Perl pattern matches and substitutions from your C program
1N/A
1N/AThe I<eval_sv()> function lets us evaluate strings of Perl code, so we can
1N/Adefine some functions that use it to "specialize" in matches and
1N/Asubstitutions: I<match()>, I<substitute()>, and I<matches()>.
1N/A
1N/A I32 match(SV *string, char *pattern);
1N/A
1N/AGiven a string and a pattern (e.g., C<m/clasp/> or C</\b\w*\b/>, which
1N/Ain your C program might appear as "/\\b\\w*\\b/"), match()
1N/Areturns 1 if the string matches the pattern and 0 otherwise.
1N/A
1N/A int substitute(SV **string, char *pattern);
1N/A
1N/AGiven a pointer to an C<SV> and an C<=~> operation (e.g.,
1N/AC<s/bob/robert/g> or C<tr[A-Z][a-z]>), substitute() modifies the string
1N/Awithin the C<SV> as according to the operation, returning the number of substitutions
1N/Amade.
1N/A
1N/A int matches(SV *string, char *pattern, AV **matches);
1N/A
1N/AGiven an C<SV>, a pattern, and a pointer to an empty C<AV>,
1N/Amatches() evaluates C<$string =~ $pattern> in a list context, and
1N/Afills in I<matches> with the array elements, returning the number of matches found.
1N/A
1N/AHere's a sample program, I<match.c>, that uses all three (long lines have
1N/Abeen wrapped here):
1N/A
1N/A #include <EXTERN.h>
1N/A #include <perl.h>
1N/A
1N/A static PerlInterpreter *my_perl;
1N/A
1N/A /** my_eval_sv(code, error_check)
1N/A ** kinda like eval_sv(),
1N/A ** but we pop the return value off the stack
1N/A **/
1N/A SV* my_eval_sv(SV *sv, I32 croak_on_error)
1N/A {
1N/A dSP;
1N/A SV* retval;
1N/A STRLEN n_a;
1N/A
1N/A PUSHMARK(SP);
1N/A eval_sv(sv, G_SCALAR);
1N/A
1N/A SPAGAIN;
1N/A retval = POPs;
1N/A PUTBACK;
1N/A
1N/A if (croak_on_error && SvTRUE(ERRSV))
1N/A croak(SvPVx(ERRSV, n_a));
1N/A
1N/A return retval;
1N/A }
1N/A
1N/A /** match(string, pattern)
1N/A **
1N/A ** Used for matches in a scalar context.
1N/A **
1N/A ** Returns 1 if the match was successful; 0 otherwise.
1N/A **/
1N/A
1N/A I32 match(SV *string, char *pattern)
1N/A {
1N/A SV *command = NEWSV(1099, 0), *retval;
1N/A STRLEN n_a;
1N/A
1N/A sv_setpvf(command, "my $string = '%s'; $string =~ %s",
1N/A SvPV(string,n_a), pattern);
1N/A
1N/A retval = my_eval_sv(command, TRUE);
1N/A SvREFCNT_dec(command);
1N/A
1N/A return SvIV(retval);
1N/A }
1N/A
1N/A /** substitute(string, pattern)
1N/A **
1N/A ** Used for =~ operations that modify their left-hand side (s/// and tr///)
1N/A **
1N/A ** Returns the number of successful matches, and
1N/A ** modifies the input string if there were any.
1N/A **/
1N/A
1N/A I32 substitute(SV **string, char *pattern)
1N/A {
1N/A SV *command = NEWSV(1099, 0), *retval;
1N/A STRLEN n_a;
1N/A
1N/A sv_setpvf(command, "$string = '%s'; ($string =~ %s)",
1N/A SvPV(*string,n_a), pattern);
1N/A
1N/A retval = my_eval_sv(command, TRUE);
1N/A SvREFCNT_dec(command);
1N/A
1N/A *string = get_sv("string", FALSE);
1N/A return SvIV(retval);
1N/A }
1N/A
1N/A /** matches(string, pattern, matches)
1N/A **
1N/A ** Used for matches in a list context.
1N/A **
1N/A ** Returns the number of matches,
1N/A ** and fills in **matches with the matching substrings
1N/A **/
1N/A
1N/A I32 matches(SV *string, char *pattern, AV **match_list)
1N/A {
1N/A SV *command = NEWSV(1099, 0);
1N/A I32 num_matches;
1N/A STRLEN n_a;
1N/A
1N/A sv_setpvf(command, "my $string = '%s'; @array = ($string =~ %s)",
1N/A SvPV(string,n_a), pattern);
1N/A
1N/A my_eval_sv(command, TRUE);
1N/A SvREFCNT_dec(command);
1N/A
1N/A *match_list = get_av("array", FALSE);
1N/A num_matches = av_len(*match_list) + 1; /** assume $[ is 0 **/
1N/A
1N/A return num_matches;
1N/A }
1N/A
1N/A main (int argc, char **argv, char **env)
1N/A {
1N/A char *embedding[] = { "", "-e", "0" };
1N/A AV *match_list;
1N/A I32 num_matches, i;
1N/A SV *text;
1N/A STRLEN n_a;
1N/A
1N/A PERL_SYS_INIT3(&argc,&argv,&env);
1N/A my_perl = perl_alloc();
1N/A perl_construct(my_perl);
1N/A perl_parse(my_perl, NULL, 3, embedding, NULL);
1N/A PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1N/A
1N/A text = NEWSV(1099,0);
1N/A sv_setpv(text, "When he is at a convenience store and the "
1N/A "bill comes to some amount like 76 cents, Maynard is "
1N/A "aware that there is something he *should* do, something "
1N/A "that will enable him to get back a quarter, but he has "
1N/A "no idea *what*. He fumbles through his red squeezey "
1N/A "changepurse and gives the boy three extra pennies with "
1N/A "his dollar, hoping that he might luck into the correct "
1N/A "amount. The boy gives him back two of his own pennies "
1N/A "and then the big shiny quarter that is his prize. "
1N/A "-RICHH");
1N/A
1N/A if (match(text, "m/quarter/")) /** Does text contain 'quarter'? **/
1N/A printf("match: Text contains the word 'quarter'.\n\n");
1N/A else
1N/A printf("match: Text doesn't contain the word 'quarter'.\n\n");
1N/A
1N/A if (match(text, "m/eighth/")) /** Does text contain 'eighth'? **/
1N/A printf("match: Text contains the word 'eighth'.\n\n");
1N/A else
1N/A printf("match: Text doesn't contain the word 'eighth'.\n\n");
1N/A
1N/A /** Match all occurrences of /wi../ **/
1N/A num_matches = matches(text, "m/(wi..)/g", &match_list);
1N/A printf("matches: m/(wi..)/g found %d matches...\n", num_matches);
1N/A
1N/A for (i = 0; i < num_matches; i++)
1N/A printf("match: %s\n", SvPV(*av_fetch(match_list, i, FALSE),n_a));
1N/A printf("\n");
1N/A
1N/A /** Remove all vowels from text **/
1N/A num_matches = substitute(&text, "s/[aeiou]//gi");
1N/A if (num_matches) {
1N/A printf("substitute: s/[aeiou]//gi...%d substitutions made.\n",
1N/A num_matches);
1N/A printf("Now text is: %s\n\n", SvPV(text,n_a));
1N/A }
1N/A
1N/A /** Attempt a substitution **/
1N/A if (!substitute(&text, "s/Perl/C/")) {
1N/A printf("substitute: s/Perl/C...No substitution made.\n\n");
1N/A }
1N/A
1N/A SvREFCNT_dec(text);
1N/A PL_perl_destruct_level = 1;
1N/A perl_destruct(my_perl);
1N/A perl_free(my_perl);
1N/A PERL_SYS_TERM();
1N/A }
1N/A
1N/Awhich produces the output (again, long lines have been wrapped here)
1N/A
1N/A match: Text contains the word 'quarter'.
1N/A
1N/A match: Text doesn't contain the word 'eighth'.
1N/A
1N/A matches: m/(wi..)/g found 2 matches...
1N/A match: will
1N/A match: with
1N/A
1N/A substitute: s/[aeiou]//gi...139 substitutions made.
1N/A Now text is: Whn h s t cnvnnc str nd th bll cms t sm mnt lk 76 cnts,
1N/A Mynrd s wr tht thr s smthng h *shld* d, smthng tht wll nbl hm t gt bck
1N/A qrtr, bt h hs n d *wht*. H fmbls thrgh hs rd sqzy chngprs nd gvs th by
1N/A thr xtr pnns wth hs dllr, hpng tht h mght lck nt th crrct mnt. Th by gvs
1N/A hm bck tw f hs wn pnns nd thn th bg shny qrtr tht s hs prz. -RCHH
1N/A
1N/A substitute: s/Perl/C...No substitution made.
1N/A
1N/A=head2 Fiddling with the Perl stack from your C program
1N/A
1N/AWhen trying to explain stacks, most computer science textbooks mumble
1N/Asomething about spring-loaded columns of cafeteria plates: the last
1N/Athing you pushed on the stack is the first thing you pop off. That'll
1N/Ado for our purposes: your C program will push some arguments onto "the Perl
1N/Astack", shut its eyes while some magic happens, and then pop the
1N/Aresults--the return value of your Perl subroutine--off the stack.
1N/A
1N/AFirst you'll need to know how to convert between C types and Perl
1N/Atypes, with newSViv() and sv_setnv() and newAV() and all their
1N/Afriends. They're described in L<perlguts> and L<perlapi>.
1N/A
1N/AThen you'll need to know how to manipulate the Perl stack. That's
1N/Adescribed in L<perlcall>.
1N/A
1N/AOnce you've understood those, embedding Perl in C is easy.
1N/A
1N/ABecause C has no builtin function for integer exponentiation, let's
1N/Amake Perl's ** operator available to it (this is less useful than it
1N/Asounds, because Perl implements ** with C's I<pow()> function). First
1N/AI'll create a stub exponentiation function in I<power.pl>:
1N/A
1N/A sub expo {
1N/A my ($a, $b) = @_;
1N/A return $a ** $b;
1N/A }
1N/A
1N/ANow I'll create a C program, I<power.c>, with a function
1N/AI<PerlPower()> that contains all the perlguts necessary to push the
1N/Atwo arguments into I<expo()> and to pop the return value out. Take a
1N/Adeep breath...
1N/A
1N/A #include <EXTERN.h>
1N/A #include <perl.h>
1N/A
1N/A static PerlInterpreter *my_perl;
1N/A
1N/A static void
1N/A PerlPower(int a, int b)
1N/A {
1N/A dSP; /* initialize stack pointer */
1N/A ENTER; /* everything created after here */
1N/A SAVETMPS; /* ...is a temporary variable. */
1N/A PUSHMARK(SP); /* remember the stack pointer */
1N/A XPUSHs(sv_2mortal(newSViv(a))); /* push the base onto the stack */
1N/A XPUSHs(sv_2mortal(newSViv(b))); /* push the exponent onto stack */
1N/A PUTBACK; /* make local stack pointer global */
1N/A call_pv("expo", G_SCALAR); /* call the function */
1N/A SPAGAIN; /* refresh stack pointer */
1N/A /* pop the return value from stack */
1N/A printf ("%d to the %dth power is %d.\n", a, b, POPi);
1N/A PUTBACK;
1N/A FREETMPS; /* free that return value */
1N/A LEAVE; /* ...and the XPUSHed "mortal" args.*/
1N/A }
1N/A
1N/A int main (int argc, char **argv, char **env)
1N/A {
1N/A char *my_argv[] = { "", "power.pl" };
1N/A
1N/A PERL_SYS_INIT3(&argc,&argv,&env);
1N/A my_perl = perl_alloc();
1N/A perl_construct( my_perl );
1N/A
1N/A perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL);
1N/A PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1N/A perl_run(my_perl);
1N/A
1N/A PerlPower(3, 4); /*** Compute 3 ** 4 ***/
1N/A
1N/A perl_destruct(my_perl);
1N/A perl_free(my_perl);
1N/A PERL_SYS_TERM();
1N/A }
1N/A
1N/A
1N/A
1N/ACompile and run:
1N/A
1N/A % cc -o power power.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
1N/A
1N/A % power
1N/A 3 to the 4th power is 81.
1N/A
1N/A=head2 Maintaining a persistent interpreter
1N/A
1N/AWhen developing interactive and/or potentially long-running
1N/Aapplications, it's a good idea to maintain a persistent interpreter
1N/Arather than allocating and constructing a new interpreter multiple
1N/Atimes. The major reason is speed: since Perl will only be loaded into
1N/Amemory once.
1N/A
1N/AHowever, you have to be more cautious with namespace and variable
1N/Ascoping when using a persistent interpreter. In previous examples
1N/Awe've been using global variables in the default package C<main>. We
1N/Aknew exactly what code would be run, and assumed we could avoid
1N/Avariable collisions and outrageous symbol table growth.
1N/A
1N/ALet's say your application is a server that will occasionally run Perl
1N/Acode from some arbitrary file. Your server has no way of knowing what
1N/Acode it's going to run. Very dangerous.
1N/A
1N/AIf the file is pulled in by C<perl_parse()>, compiled into a newly
1N/Aconstructed interpreter, and subsequently cleaned out with
1N/AC<perl_destruct()> afterwards, you're shielded from most namespace
1N/Atroubles.
1N/A
1N/AOne way to avoid namespace collisions in this scenario is to translate
1N/Athe filename into a guaranteed-unique package name, and then compile
1N/Athe code into that package using L<perlfunc/eval>. In the example
1N/Abelow, each file will only be compiled once. Or, the application
1N/Amight choose to clean out the symbol table associated with the file
1N/Aafter it's no longer needed. Using L<perlapi/call_argv>, We'll
1N/Acall the subroutine C<Embed::Persistent::eval_file> which lives in the
1N/Afile C<persistent.pl> and pass the filename and boolean cleanup/cache
1N/Aflag as arguments.
1N/A
1N/ANote that the process will continue to grow for each file that it
1N/Auses. In addition, there might be C<AUTOLOAD>ed subroutines and other
1N/Aconditions that cause Perl's symbol table to grow. You might want to
1N/Aadd some logic that keeps track of the process size, or restarts
1N/Aitself after a certain number of requests, to ensure that memory
1N/Aconsumption is minimized. You'll also want to scope your variables
1N/Awith L<perlfunc/my> whenever possible.
1N/A
1N/A
1N/A package Embed::Persistent;
1N/A #persistent.pl
1N/A
1N/A use strict;
1N/A our %Cache;
1N/A use Symbol qw(delete_package);
1N/A
1N/A sub valid_package_name {
1N/A my($string) = @_;
1N/A $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;
1N/A # second pass only for words starting with a digit
1N/A $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg;
1N/A
1N/A # Dress it up as a real package name
1N/A $string =~ s|/|::|g;
1N/A return "Embed" . $string;
1N/A }
1N/A
1N/A sub eval_file {
1N/A my($filename, $delete) = @_;
1N/A my $package = valid_package_name($filename);
1N/A my $mtime = -M $filename;
1N/A if(defined $Cache{$package}{mtime}
1N/A &&
1N/A $Cache{$package}{mtime} <= $mtime)
1N/A {
1N/A # we have compiled this subroutine already,
1N/A # it has not been updated on disk, nothing left to do
1N/A print STDERR "already compiled $package->handler\n";
1N/A }
1N/A else {
1N/A local *FH;
1N/A open FH, $filename or die "open '$filename' $!";
1N/A local($/) = undef;
1N/A my $sub = <FH>;
1N/A close FH;
1N/A
1N/A #wrap the code into a subroutine inside our unique package
1N/A my $eval = qq{package $package; sub handler { $sub; }};
1N/A {
1N/A # hide our variables within this block
1N/A my($filename,$mtime,$package,$sub);
1N/A eval $eval;
1N/A }
1N/A die $@ if $@;
1N/A
1N/A #cache it unless we're cleaning out each time
1N/A $Cache{$package}{mtime} = $mtime unless $delete;
1N/A }
1N/A
1N/A eval {$package->handler;};
1N/A die $@ if $@;
1N/A
1N/A delete_package($package) if $delete;
1N/A
1N/A #take a look if you want
1N/A #print Devel::Symdump->rnew($package)->as_string, $/;
1N/A }
1N/A
1N/A 1;
1N/A
1N/A __END__
1N/A
1N/A /* persistent.c */
1N/A #include <EXTERN.h>
1N/A #include <perl.h>
1N/A
1N/A /* 1 = clean out filename's symbol table after each request, 0 = don't */
1N/A #ifndef DO_CLEAN
1N/A #define DO_CLEAN 0
1N/A #endif
1N/A
1N/A #define BUFFER_SIZE 1024
1N/A
1N/A static PerlInterpreter *my_perl = NULL;
1N/A
1N/A int
1N/A main(int argc, char **argv, char **env)
1N/A {
1N/A char *embedding[] = { "", "persistent.pl" };
1N/A char *args[] = { "", DO_CLEAN, NULL };
1N/A char filename[BUFFER_SIZE];
1N/A int exitstatus = 0;
1N/A STRLEN n_a;
1N/A
1N/A PERL_SYS_INIT3(&argc,&argv,&env);
1N/A if((my_perl = perl_alloc()) == NULL) {
1N/A fprintf(stderr, "no memory!");
1N/A exit(1);
1N/A }
1N/A perl_construct(my_perl);
1N/A
1N/A exitstatus = perl_parse(my_perl, NULL, 2, embedding, NULL);
1N/A PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1N/A if(!exitstatus) {
1N/A exitstatus = perl_run(my_perl);
1N/A
1N/A while(printf("Enter file name: ") &&
1N/A fgets(filename, BUFFER_SIZE, stdin)) {
1N/A
1N/A filename[strlen(filename)-1] = '\0'; /* strip \n */
1N/A /* call the subroutine, passing it the filename as an argument */
1N/A args[0] = filename;
1N/A call_argv("Embed::Persistent::eval_file",
1N/A G_DISCARD | G_EVAL, args);
1N/A
1N/A /* check $@ */
1N/A if(SvTRUE(ERRSV))
1N/A fprintf(stderr, "eval error: %s\n", SvPV(ERRSV,n_a));
1N/A }
1N/A }
1N/A
1N/A PL_perl_destruct_level = 0;
1N/A perl_destruct(my_perl);
1N/A perl_free(my_perl);
1N/A PERL_SYS_TERM();
1N/A exit(exitstatus);
1N/A }
1N/A
1N/ANow compile:
1N/A
1N/A % cc -o persistent persistent.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
1N/A
1N/AHere's an example script file:
1N/A
1N/A #test.pl
1N/A my $string = "hello";
1N/A foo($string);
1N/A
1N/A sub foo {
1N/A print "foo says: @_\n";
1N/A }
1N/A
1N/ANow run:
1N/A
1N/A % persistent
1N/A Enter file name: test.pl
1N/A foo says: hello
1N/A Enter file name: test.pl
1N/A already compiled Embed::test_2epl->handler
1N/A foo says: hello
1N/A Enter file name: ^C
1N/A
1N/A=head2 Execution of END blocks
1N/A
1N/ATraditionally END blocks have been executed at the end of the perl_run.
1N/AThis causes problems for applications that never call perl_run. Since
1N/Aperl 5.7.2 you can specify C<PL_exit_flags |= PERL_EXIT_DESTRUCT_END>
1N/Ato get the new behaviour. This also enables the running of END blocks if
1N/Athe perl_parse fails and C<perl_destruct> will return the exit value.
1N/A
1N/A=head2 Maintaining multiple interpreter instances
1N/A
1N/ASome rare applications will need to create more than one interpreter
1N/Aduring a session. Such an application might sporadically decide to
1N/Arelease any resources associated with the interpreter.
1N/A
1N/AThe program must take care to ensure that this takes place I<before>
1N/Athe next interpreter is constructed. By default, when perl is not
1N/Abuilt with any special options, the global variable
1N/AC<PL_perl_destruct_level> is set to C<0>, since extra cleaning isn't
1N/Ausually needed when a program only ever creates a single interpreter
1N/Ain its entire lifetime.
1N/A
1N/ASetting C<PL_perl_destruct_level> to C<1> makes everything squeaky clean:
1N/A
1N/A while(1) {
1N/A ...
1N/A /* reset global variables here with PL_perl_destruct_level = 1 */
1N/A PL_perl_destruct_level = 1;
1N/A perl_construct(my_perl);
1N/A ...
1N/A /* clean and reset _everything_ during perl_destruct */
1N/A PL_perl_destruct_level = 1;
1N/A perl_destruct(my_perl);
1N/A perl_free(my_perl);
1N/A ...
1N/A /* let's go do it again! */
1N/A }
1N/A
1N/AWhen I<perl_destruct()> is called, the interpreter's syntax parse tree
1N/Aand symbol tables are cleaned up, and global variables are reset. The
1N/Asecond assignment to C<PL_perl_destruct_level> is needed because
1N/Aperl_construct resets it to C<0>.
1N/A
1N/ANow suppose we have more than one interpreter instance running at the
1N/Asame time. This is feasible, but only if you used the Configure option
1N/AC<-Dusemultiplicity> or the options C<-Dusethreads -Duseithreads> when
1N/Abuilding perl. By default, enabling one of these Configure options
1N/Asets the per-interpreter global variable C<PL_perl_destruct_level> to
1N/AC<1>, so that thorough cleaning is automatic and interpreter variables
1N/Aare initialized correctly. Even if you don't intend to run two or
1N/Amore interpreters at the same time, but to run them sequentially, like
1N/Ain the above example, it is recommended to build perl with the
1N/AC<-Dusemultiplicity> option otherwise some interpreter variables may
1N/Anot be initialized correctly between consecutive runs and your
1N/Aapplication may crash.
1N/A
1N/AUsing C<-Dusethreads -Duseithreads> rather than C<-Dusemultiplicity>
1N/Ais more appropriate if you intend to run multiple interpreters
1N/Aconcurrently in different threads, because it enables support for
1N/Alinking in the thread libraries of your system with the interpreter.
1N/A
1N/ALet's give it a try:
1N/A
1N/A
1N/A #include <EXTERN.h>
1N/A #include <perl.h>
1N/A
1N/A /* we're going to embed two interpreters */
1N/A /* we're going to embed two interpreters */
1N/A
1N/A #define SAY_HELLO "-e", "print qq(Hi, I'm $^X\n)"
1N/A
1N/A int main(int argc, char **argv, char **env)
1N/A {
1N/A PerlInterpreter *one_perl, *two_perl;
1N/A char *one_args[] = { "one_perl", SAY_HELLO };
1N/A char *two_args[] = { "two_perl", SAY_HELLO };
1N/A
1N/A PERL_SYS_INIT3(&argc,&argv,&env);
1N/A one_perl = perl_alloc();
1N/A two_perl = perl_alloc();
1N/A
1N/A PERL_SET_CONTEXT(one_perl);
1N/A perl_construct(one_perl);
1N/A PERL_SET_CONTEXT(two_perl);
1N/A perl_construct(two_perl);
1N/A
1N/A PERL_SET_CONTEXT(one_perl);
1N/A perl_parse(one_perl, NULL, 3, one_args, (char **)NULL);
1N/A PERL_SET_CONTEXT(two_perl);
1N/A perl_parse(two_perl, NULL, 3, two_args, (char **)NULL);
1N/A
1N/A PERL_SET_CONTEXT(one_perl);
1N/A perl_run(one_perl);
1N/A PERL_SET_CONTEXT(two_perl);
1N/A perl_run(two_perl);
1N/A
1N/A PERL_SET_CONTEXT(one_perl);
1N/A perl_destruct(one_perl);
1N/A PERL_SET_CONTEXT(two_perl);
1N/A perl_destruct(two_perl);
1N/A
1N/A PERL_SET_CONTEXT(one_perl);
1N/A perl_free(one_perl);
1N/A PERL_SET_CONTEXT(two_perl);
1N/A perl_free(two_perl);
1N/A PERL_SYS_TERM();
1N/A }
1N/A
1N/ANote the calls to PERL_SET_CONTEXT(). These are necessary to initialize
1N/Athe global state that tracks which interpreter is the "current" one on
1N/Athe particular process or thread that may be running it. It should
1N/Aalways be used if you have more than one interpreter and are making
1N/Aperl API calls on both interpreters in an interleaved fashion.
1N/A
1N/APERL_SET_CONTEXT(interp) should also be called whenever C<interp> is
1N/Aused by a thread that did not create it (using either perl_alloc(), or
1N/Athe more esoteric perl_clone()).
1N/A
1N/ACompile as usual:
1N/A
1N/A % cc -o multiplicity multiplicity.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
1N/A
1N/ARun it, Run it:
1N/A
1N/A % multiplicity
1N/A Hi, I'm one_perl
1N/A Hi, I'm two_perl
1N/A
1N/A=head2 Using Perl modules, which themselves use C libraries, from your C program
1N/A
1N/AIf you've played with the examples above and tried to embed a script
1N/Athat I<use()>s a Perl module (such as I<Socket>) which itself uses a C or C++ library,
1N/Athis probably happened:
1N/A
1N/A
1N/A Can't load module Socket, dynamic loading not available in this perl.
1N/A (You may need to build a new perl executable which either supports
1N/A dynamic loading or has the Socket module statically linked into it.)
1N/A
1N/A
1N/AWhat's wrong?
1N/A
1N/AYour interpreter doesn't know how to communicate with these extensions
1N/Aon its own. A little glue will help. Up until now you've been
1N/Acalling I<perl_parse()>, handing it NULL for the second argument:
1N/A
1N/A perl_parse(my_perl, NULL, argc, my_argv, NULL);
1N/A
1N/AThat's where the glue code can be inserted to create the initial contact between
1N/APerl and linked C/C++ routines. Let's take a look some pieces of I<perlmain.c>
1N/Ato see how Perl does this:
1N/A
1N/A static void xs_init (pTHX);
1N/A
1N/A EXTERN_C void boot_DynaLoader (pTHX_ CV* cv);
1N/A EXTERN_C void boot_Socket (pTHX_ CV* cv);
1N/A
1N/A
1N/A EXTERN_C void
1N/A xs_init(pTHX)
1N/A {
1N/A char *file = __FILE__;
1N/A /* DynaLoader is a special case */
1N/A newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
1N/A newXS("Socket::bootstrap", boot_Socket, file);
1N/A }
1N/A
1N/ASimply put: for each extension linked with your Perl executable
1N/A(determined during its initial configuration on your
1N/Acomputer or when adding a new extension),
1N/Aa Perl subroutine is created to incorporate the extension's
1N/Aroutines. Normally, that subroutine is named
1N/AI<Module::bootstrap()> and is invoked when you say I<use Module>. In
1N/Aturn, this hooks into an XSUB, I<boot_Module>, which creates a Perl
1N/Acounterpart for each of the extension's XSUBs. Don't worry about this
1N/Apart; leave that to the I<xsubpp> and extension authors. If your
1N/Aextension is dynamically loaded, DynaLoader creates I<Module::bootstrap()>
1N/Afor you on the fly. In fact, if you have a working DynaLoader then there
1N/Ais rarely any need to link in any other extensions statically.
1N/A
1N/A
1N/AOnce you have this code, slap it into the second argument of I<perl_parse()>:
1N/A
1N/A
1N/A perl_parse(my_perl, xs_init, argc, my_argv, NULL);
1N/A
1N/A
1N/AThen compile:
1N/A
1N/A % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
1N/A
1N/A % interp
1N/A use Socket;
1N/A use SomeDynamicallyLoadedModule;
1N/A
1N/A print "Now I can use extensions!\n"'
1N/A
1N/AB<ExtUtils::Embed> can also automate writing the I<xs_init> glue code.
1N/A
1N/A % perl -MExtUtils::Embed -e xsinit -- -o perlxsi.c
1N/A % cc -c perlxsi.c `perl -MExtUtils::Embed -e ccopts`
1N/A % cc -c interp.c `perl -MExtUtils::Embed -e ccopts`
1N/A % cc -o interp perlxsi.o interp.o `perl -MExtUtils::Embed -e ldopts`
1N/A
1N/AConsult L<perlxs>, L<perlguts>, and L<perlapi> for more details.
1N/A
1N/A=head1 Embedding Perl under Win32
1N/A
1N/AIn general, all of the source code shown here should work unmodified under
1N/AWindows.
1N/A
1N/AHowever, there are some caveats about the command-line examples shown.
1N/AFor starters, backticks won't work under the Win32 native command shell.
1N/AThe ExtUtils::Embed kit on CPAN ships with a script called
1N/AB<genmake>, which generates a simple makefile to build a program from
1N/Aa single C source file. It can be used like this:
1N/A
1N/A C:\ExtUtils-Embed\eg> perl genmake interp.c
1N/A C:\ExtUtils-Embed\eg> nmake
1N/A C:\ExtUtils-Embed\eg> interp -e "print qq{I'm embedded in Win32!\n}"
1N/A
1N/AYou may wish to use a more robust environment such as the Microsoft
1N/ADeveloper Studio. In this case, run this to generate perlxsi.c:
1N/A
1N/A perl -MExtUtils::Embed -e xsinit
1N/A
1N/ACreate a new project and Insert -> Files into Project: perlxsi.c,
1N/Aperl.lib, and your own source files, e.g. interp.c. Typically you'll
1N/Afind perl.lib in B<C:\perl\lib\CORE>, if not, you should see the
1N/AB<CORE> directory relative to C<perl -V:archlib>. The studio will
1N/Aalso need this path so it knows where to find Perl include files.
1N/AThis path can be added via the Tools -> Options -> Directories menu.
1N/AFinally, select Build -> Build interp.exe and you're ready to go.
1N/A
1N/A=head1 Hiding Perl_
1N/A
1N/AIf you completely hide the short forms forms of the Perl public API,
1N/Aadd -DPERL_NO_SHORT_NAMES to the compilation flags. This means that
1N/Afor example instead of writing
1N/A
1N/A warn("%d bottles of beer on the wall", bottlecount);
1N/A
1N/Ayou will have to write the explicit full form
1N/A
1N/A Perl_warn(aTHX_ "%d bottles of beer on the wall", bottlecount);
1N/A
1N/A(See L<perlguts/Background and PERL_IMPLICIT_CONTEXT for the explanation
1N/Aof the C<aTHX_>.> ) Hiding the short forms is very useful for avoiding
1N/Aall sorts of nasty (C preprocessor or otherwise) conflicts with other
1N/Asoftware packages (Perl defines about 2400 APIs with these short names,
1N/Atake or leave few hundred, so there certainly is room for conflict.)
1N/A
1N/A=head1 MORAL
1N/A
1N/AYou can sometimes I<write faster code> in C, but
1N/Ayou can always I<write code faster> in Perl. Because you can use
1N/Aeach from the other, combine them as you wish.
1N/A
1N/A
1N/A=head1 AUTHOR
1N/A
1N/AJon Orwant <F<orwant@media.mit.edu>> and Doug MacEachern
1N/A<F<dougm@covalent.net>>, with small contributions from Tim Bunce, Tom
1N/AChristiansen, Guy Decoux, Hallvard Furuseth, Dov Grobgeld, and Ilya
1N/AZakharevich.
1N/A
1N/ADoug MacEachern has an article on embedding in Volume 1, Issue 4 of
1N/AThe Perl Journal ( http://www.tpj.com/ ). Doug is also the developer of the
1N/Amost widely-used Perl embedding: the mod_perl system
1N/A(perl.apache.org), which embeds Perl in the Apache web server.
1N/AOracle, Binary Evolution, ActiveState, and Ben Sugars's nsapi_perl
1N/Ahave used this model for Oracle, Netscape and Internet Information
1N/AServer Perl plugins.
1N/A
1N/AJuly 22, 1998
1N/A
1N/A=head1 COPYRIGHT
1N/A
1N/ACopyright (C) 1995, 1996, 1997, 1998 Doug MacEachern and Jon Orwant. All
1N/ARights Reserved.
1N/A
1N/APermission is granted to make and distribute verbatim copies of this
1N/Adocumentation provided the copyright notice and this permission notice are
1N/Apreserved on all copies.
1N/A
1N/APermission is granted to copy and distribute modified versions of this
1N/Adocumentation under the conditions for verbatim copying, provided also
1N/Athat they are marked clearly as modified versions, that the authors'
1N/Anames and title are unchanged (though subtitles and additional
1N/Aauthors' names may be added), and that the entire resulting derived
1N/Awork is distributed under the terms of a permission notice identical
1N/Ato this one.
1N/A
1N/APermission is granted to copy and distribute translations of this
1N/Adocumentation into another language, under the above conditions for
1N/Amodified versions.