xref: /openbsd/gnu/usr.bin/perl/pod/perlembed.pod (revision d415bd75)
1=head1 NAME
2
3perlembed - how to embed perl in your C program
4
5=head1 DESCRIPTION
6
7=head2 PREAMBLE
8
9Do you want to:
10
11=over 5
12
13=item B<Use C from Perl?>
14
15Read L<perlxstut>, L<perlxs>, L<h2xs>, L<perlguts>, and L<perlapi>.
16
17=item B<Use a Unix program from Perl?>
18
19Read about back-quotes and about C<system> and C<exec> in L<perlfunc>.
20
21=item B<Use Perl from Perl?>
22
23Read about L<perlfunc/do> and L<perlfunc/eval> and L<perlfunc/require>
24and L<perlfunc/use>.
25
26=item B<Use C from C?>
27
28Rethink your design.
29
30=item B<Use Perl from C?>
31
32Read on...
33
34=back
35
36=head2 ROADMAP
37
38=over 5
39
40=item *
41
42Compiling your C program
43
44=item *
45
46Adding a Perl interpreter to your C program
47
48=item *
49
50Calling a Perl subroutine from your C program
51
52=item *
53
54Evaluating a Perl statement from your C program
55
56=item *
57
58Performing Perl pattern matches and substitutions from your C program
59
60=item *
61
62Fiddling with the Perl stack from your C program
63
64=item *
65
66Maintaining a persistent interpreter
67
68=item *
69
70Maintaining multiple interpreter instances
71
72=item *
73
74Using Perl modules, which themselves use C libraries, from your C program
75
76=item *
77
78Embedding Perl under Win32
79
80=back
81
82=head2 Compiling your C program
83
84If you have trouble compiling the scripts in this documentation,
85you're not alone.  The cardinal rule: COMPILE THE PROGRAMS IN EXACTLY
86THE SAME WAY THAT YOUR PERL WAS COMPILED.  (Sorry for yelling.)
87
88Also, every C program that uses Perl must link in the I<perl library>.
89What's that, you ask?  Perl is itself written in C; the perl library
90is the collection of compiled C programs that were used to create your
91perl executable (I</usr/bin/perl> or equivalent).  (Corollary: you
92can't use Perl from your C program unless Perl has been compiled on
93your machine, or installed properly--that's why you shouldn't blithely
94copy Perl executables from machine to machine without also copying the
95I<lib> directory.)
96
97When you use Perl from C, your C program will--usually--allocate,
98"run", and deallocate a I<PerlInterpreter> object, which is defined by
99the perl library.
100
101=for apidoc Ayh||PerlInterpreter
102
103If your copy of Perl is recent enough to contain this documentation
104(version 5.002 or later), then the perl library (and I<EXTERN.h> and
105I<perl.h>, which you'll also need) will reside in a directory
106that looks like this:
107
108    /usr/local/lib/perl5/your_architecture_here/CORE
109
110or perhaps just
111
112    /usr/local/lib/perl5/CORE
113
114or maybe something like
115
116    /usr/opt/perl5/CORE
117
118Execute this statement for a hint about where to find CORE:
119
120    perl -MConfig -e 'print $Config{archlib}'
121
122Here's how you'd compile the example in the next section,
123L</Adding a Perl interpreter to your C program>, on my Linux box:
124
125    % gcc -O2 -Dbool=char -DHAS_BOOL -I/usr/local/include
126    -I/usr/local/lib/perl5/i586-linux/5.003/CORE
127    -L/usr/local/lib/perl5/i586-linux/5.003/CORE
128    -o interp interp.c -lperl -lm
129
130(That's all one line.)  On my DEC Alpha running old 5.003_05, the
131incantation is a bit different:
132
133    % cc -O2 -Olimit 2900 -I/usr/local/include
134    -I/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE
135    -L/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE -L/usr/local/lib
136    -D__LANGUAGE_C__ -D_NO_PROTO -o interp interp.c -lperl -lm
137
138How can you figure out what to add?  Assuming your Perl is post-5.001,
139execute a C<perl -V> command and pay special attention to the "cc" and
140"ccflags" information.
141
142You'll have to choose the appropriate compiler (I<cc>, I<gcc>, et al.) for
143your machine: C<perl -MConfig -e 'print $Config{cc}'> will tell you what
144to use.
145
146You'll also have to choose the appropriate library directory
147(I</usr/local/lib/...>) for your machine.  If your compiler complains
148that certain functions are undefined, or that it can't locate
149I<-lperl>, then you need to change the path following the C<-L>.  If it
150complains that it can't find I<EXTERN.h> and I<perl.h>, you need to
151change the path following the C<-I>.
152
153You may have to add extra libraries as well.  Which ones?
154Perhaps those printed by
155
156   perl -MConfig -e 'print $Config{libs}'
157
158Provided your perl binary was properly configured and installed the
159B<ExtUtils::Embed> module will determine all of this information for
160you:
161
162   % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
163
164If the B<ExtUtils::Embed> module isn't part of your Perl distribution,
165you can retrieve it from
166L<https://metacpan.org/pod/ExtUtils::Embed>
167(If this documentation came from your Perl distribution, then you're
168running 5.004 or better and you already have it.)
169
170The B<ExtUtils::Embed> kit on CPAN also contains all source code for
171the examples in this document, tests, additional examples and other
172information you may find useful.
173
174=head2 Adding a Perl interpreter to your C program
175
176In a sense, perl (the C program) is a good example of embedding Perl
177(the language), so I'll demonstrate embedding with I<miniperlmain.c>,
178included in the source distribution.  Here's a bastardized, non-portable
179version of I<miniperlmain.c> containing the essentials of embedding:
180
181 #include <EXTERN.h>               /* from the Perl distribution     */
182 #include <perl.h>                 /* from the Perl distribution     */
183
184 static PerlInterpreter *my_perl;  /***    The Perl interpreter    ***/
185
186 int main(int argc, char **argv, char **env)
187 {
188	PERL_SYS_INIT3(&argc,&argv,&env);
189        my_perl = perl_alloc();
190        perl_construct(my_perl);
191	PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
192        perl_parse(my_perl, NULL, argc, argv, (char **)NULL);
193        perl_run(my_perl);
194        perl_destruct(my_perl);
195        perl_free(my_perl);
196	PERL_SYS_TERM();
197	exit(EXIT_SUCCESS);
198 }
199
200Notice that we don't use the C<env> pointer.  Normally handed to
201C<perl_parse> as its final argument, C<env> here is replaced by
202C<NULL>, which means that the current environment will be used.
203
204The macros PERL_SYS_INIT3() and PERL_SYS_TERM() provide system-specific
205tune up of the C runtime environment necessary to run Perl interpreters;
206they should only be called once regardless of how many interpreters you
207create or destroy. Call PERL_SYS_INIT3() before you create your first
208interpreter, and PERL_SYS_TERM() after you free your last interpreter.
209
210Since PERL_SYS_INIT3() may change C<env>, it may be more appropriate to
211provide C<env> as an argument to perl_parse().
212
213Also notice that no matter what arguments you pass to perl_parse(),
214PERL_SYS_INIT3() must be invoked on the C main() argc, argv and env and
215only once.
216
217Mind that argv[argc] must be NULL, same as those passed to a main
218function in C.
219
220Now compile this program (I'll call it I<interp.c>) into an executable:
221
222    % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
223
224After a successful compilation, you'll be able to use I<interp> just
225like perl itself:
226
227    % interp
228    print "Pretty Good Perl \n";
229    print "10890 - 9801 is ", 10890 - 9801;
230    <CTRL-D>
231    Pretty Good Perl
232    10890 - 9801 is 1089
233
234or
235
236    % interp -e 'printf("%x", 3735928559)'
237    deadbeef
238
239You can also read and execute Perl statements from a file while in the
240midst of your C program, by placing the filename in I<argv[1]> before
241calling I<perl_run>.
242
243=head2 Calling a Perl subroutine from your C program
244
245To call individual Perl subroutines, you can use any of the B<call_*>
246functions documented in L<perlcall>.
247In this example we'll use C<call_argv>.
248
249That's shown below, in a program I'll call I<showtime.c>.
250
251    #include <EXTERN.h>
252    #include <perl.h>
253
254    static PerlInterpreter *my_perl;
255
256    int main(int argc, char **argv, char **env)
257    {
258        char *args[] = { NULL };
259	PERL_SYS_INIT3(&argc,&argv,&env);
260        my_perl = perl_alloc();
261        perl_construct(my_perl);
262
263        perl_parse(my_perl, NULL, argc, argv, NULL);
264	PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
265
266        /*** skipping perl_run() ***/
267
268        call_argv("showtime", G_DISCARD | G_NOARGS, args);
269
270        perl_destruct(my_perl);
271        perl_free(my_perl);
272	PERL_SYS_TERM();
273	exit(EXIT_SUCCESS);
274    }
275
276where I<showtime> is a Perl subroutine that takes no arguments (that's the
277I<G_NOARGS>) and for which I'll ignore the return value (that's the
278I<G_DISCARD>).  Those flags, and others, are discussed in L<perlcall>.
279
280I'll define the I<showtime> subroutine in a file called I<showtime.pl>:
281
282 print "I shan't be printed.";
283
284 sub showtime {
285     print time;
286 }
287
288Simple enough. Now compile and run:
289
290 % cc -o showtime showtime.c \
291     `perl -MExtUtils::Embed -e ccopts -e ldopts`
292 % showtime showtime.pl
293 818284590
294
295yielding the number of seconds that elapsed between January 1, 1970
296(the beginning of the Unix epoch), and the moment I began writing this
297sentence.
298
299In this particular case we don't have to call I<perl_run>, as we set
300the PL_exit_flag PERL_EXIT_DESTRUCT_END which executes END blocks in
301perl_destruct.
302
303If you want to pass arguments to the Perl subroutine, you can add
304strings to the C<NULL>-terminated C<args> list passed to
305I<call_argv>.  For other data types, or to examine return values,
306you'll need to manipulate the Perl stack.  That's demonstrated in
307L</Fiddling with the Perl stack from your C program>.
308
309=head2 Evaluating a Perl statement from your C program
310
311Perl provides two API functions to evaluate pieces of Perl code.
312These are L<perlapi/eval_sv> and L<perlapi/eval_pv>.
313
314Arguably, these are the only routines you'll ever need to execute
315snippets of Perl code from within your C program.  Your code can be as
316long as you wish; it can contain multiple statements; it can employ
317L<perlfunc/use>, L<perlfunc/require>, and L<perlfunc/do> to
318include external Perl files.
319
320I<eval_pv> lets us evaluate individual Perl strings, and then
321extract variables for coercion into C types.  The following program,
322I<string.c>, executes three Perl strings, extracting an C<int> from
323the first, a C<float> from the second, and a C<char *> from the third.
324
325 #include <EXTERN.h>
326 #include <perl.h>
327
328 static PerlInterpreter *my_perl;
329
330 main (int argc, char **argv, char **env)
331 {
332     char *embedding[] = { "", "-e", "0", NULL };
333
334     PERL_SYS_INIT3(&argc,&argv,&env);
335     my_perl = perl_alloc();
336     perl_construct( my_perl );
337
338     perl_parse(my_perl, NULL, 3, embedding, NULL);
339     PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
340     perl_run(my_perl);
341
342     /** Treat $a as an integer **/
343     eval_pv("$a = 3; $a **= 2", TRUE);
344     printf("a = %d\n", SvIV(get_sv("a", 0)));
345
346     /** Treat $a as a float **/
347     eval_pv("$a = 3.14; $a **= 2", TRUE);
348     printf("a = %f\n", SvNV(get_sv("a", 0)));
349
350     /** Treat $a as a string **/
351     eval_pv(
352       "$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);", TRUE);
353     printf("a = %s\n", SvPV_nolen(get_sv("a", 0)));
354
355     perl_destruct(my_perl);
356     perl_free(my_perl);
357     PERL_SYS_TERM();
358 }
359
360All of those strange functions with I<sv> in their names help convert Perl
361scalars to C types.  They're described in L<perlguts> and L<perlapi>.
362
363If you compile and run I<string.c>, you'll see the results of using
364I<SvIV()> to create an C<int>, I<SvNV()> to create a C<float>, and
365I<SvPV()> to create a string:
366
367   a = 9
368   a = 9.859600
369   a = Just Another Perl Hacker
370
371In the example above, we've created a global variable to temporarily
372store the computed value of our eval'ed expression.  It is also
373possible and in most cases a better strategy to fetch the return value
374from I<eval_pv()> instead.  Example:
375
376   ...
377   SV *val = eval_pv("reverse 'rekcaH lreP rehtonA tsuJ'", TRUE);
378   printf("%s\n", SvPV_nolen(val));
379   ...
380
381This way, we avoid namespace pollution by not creating global
382variables and we've simplified our code as well.
383
384=head2 Performing Perl pattern matches and substitutions from your C program
385
386The I<eval_sv()> function lets us evaluate strings of Perl code, so we can
387define some functions that use it to "specialize" in matches and
388substitutions: I<match()>, I<substitute()>, and I<matches()>.
389
390   I32 match(SV *string, char *pattern);
391
392Given a string and a pattern (e.g., C<m/clasp/> or C</\b\w*\b/>, which
393in your C program might appear as "/\\b\\w*\\b/"), match()
394returns 1 if the string matches the pattern and 0 otherwise.
395
396   int substitute(SV **string, char *pattern);
397
398Given a pointer to an C<SV> and an C<=~> operation (e.g.,
399C<s/bob/robert/g> or C<tr[A-Z][a-z]>), substitute() modifies the string
400within the C<SV> as according to the operation, returning the number of
401substitutions made.
402
403   SSize_t matches(SV *string, char *pattern, AV **matches);
404
405Given an C<SV>, a pattern, and a pointer to an empty C<AV>,
406matches() evaluates C<$string =~ $pattern> in a list context, and
407fills in I<matches> with the array elements, returning the number of matches
408found.
409
410Here's a sample program, I<match.c>, that uses all three (long lines have
411been wrapped here):
412
413 #include <EXTERN.h>
414 #include <perl.h>
415
416 static PerlInterpreter *my_perl;
417
418 /** my_eval_sv(code, error_check)
419 ** kinda like eval_sv(),
420 ** but we pop the return value off the stack
421 **/
422 SV* my_eval_sv(SV *sv, I32 croak_on_error)
423 {
424     dSP;
425     SV* retval;
426
427
428     PUSHMARK(SP);
429     eval_sv(sv, G_SCALAR);
430
431     SPAGAIN;
432     retval = POPs;
433     PUTBACK;
434
435     if (croak_on_error && SvTRUE(ERRSV))
436        croak_sv(ERRSV);
437
438     return retval;
439 }
440
441 /** match(string, pattern)
442 **
443 ** Used for matches in a scalar context.
444 **
445 ** Returns 1 if the match was successful; 0 otherwise.
446 **/
447
448 I32 match(SV *string, char *pattern)
449 {
450     SV *command = newSV(0), *retval;
451
452     sv_setpvf(command, "my $string = '%s'; $string =~ %s",
453 	      SvPV_nolen(string), pattern);
454
455     retval = my_eval_sv(command, TRUE);
456     SvREFCNT_dec(command);
457
458     return SvIV(retval);
459 }
460
461 /** substitute(string, pattern)
462 **
463 ** Used for =~ operations that
464 ** modify their left-hand side (s/// and tr///)
465 **
466 ** Returns the number of successful matches, and
467 ** modifies the input string if there were any.
468 **/
469
470 I32 substitute(SV **string, char *pattern)
471 {
472     SV *command = newSV(0), *retval;
473
474     sv_setpvf(command, "$string = '%s'; ($string =~ %s)",
475 	      SvPV_nolen(*string), pattern);
476
477     retval = my_eval_sv(command, TRUE);
478     SvREFCNT_dec(command);
479
480     *string = get_sv("string", 0);
481     return SvIV(retval);
482 }
483
484 /** matches(string, pattern, matches)
485 **
486 ** Used for matches in a list context.
487 **
488 ** Returns the number of matches,
489 ** and fills in **matches with the matching substrings
490 **/
491
492 SSize_t matches(SV *string, char *pattern, AV **match_list)
493 {
494     SV *command = newSV(0);
495     SSize_t num_matches;
496
497     sv_setpvf(command, "my $string = '%s'; @array = ($string =~ %s)",
498 	      SvPV_nolen(string), pattern);
499
500     my_eval_sv(command, TRUE);
501     SvREFCNT_dec(command);
502
503     *match_list = get_av("array", 0);
504     num_matches = av_top_index(*match_list) + 1;
505
506     return num_matches;
507 }
508
509 main (int argc, char **argv, char **env)
510 {
511     char *embedding[] = { "", "-e", "0", NULL };
512     AV *match_list;
513     I32 num_matches, i;
514     SV *text;
515
516     PERL_SYS_INIT3(&argc,&argv,&env);
517     my_perl = perl_alloc();
518     perl_construct(my_perl);
519     perl_parse(my_perl, NULL, 3, embedding, NULL);
520     PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
521
522     text = newSV(0);
523     sv_setpv(text, "When he is at a convenience store and the "
524	"bill comes to some amount like 76 cents, Maynard is "
525	"aware that there is something he *should* do, something "
526	"that will enable him to get back a quarter, but he has "
527	"no idea *what*.  He fumbles through his red squeezey "
528	"changepurse and gives the boy three extra pennies with "
529	"his dollar, hoping that he might luck into the correct "
530	"amount.  The boy gives him back two of his own pennies "
531	"and then the big shiny quarter that is his prize. "
532	"-RICHH");
533
534     if (match(text, "m/quarter/")) /** Does text contain 'quarter'? **/
535 	printf("match: Text contains the word 'quarter'.\n\n");
536     else
537 	printf("match: Text doesn't contain the word 'quarter'.\n\n");
538
539     if (match(text, "m/eighth/")) /** Does text contain 'eighth'? **/
540 	printf("match: Text contains the word 'eighth'.\n\n");
541     else
542 	printf("match: Text doesn't contain the word 'eighth'.\n\n");
543
544     /** Match all occurrences of /wi../ **/
545     num_matches = matches(text, "m/(wi..)/g", &match_list);
546     printf("matches: m/(wi..)/g found %d matches...\n", num_matches);
547
548     for (i = 0; i < num_matches; i++)
549         printf("match: %s\n",
550                  SvPV_nolen(*av_fetch(match_list, i, FALSE)));
551     printf("\n");
552
553     /** Remove all vowels from text **/
554     num_matches = substitute(&text, "s/[aeiou]//gi");
555     if (num_matches) {
556 	printf("substitute: s/[aeiou]//gi...%lu substitutions made.\n",
557 	       (unsigned long)num_matches);
558 	printf("Now text is: %s\n\n", SvPV_nolen(text));
559     }
560
561     /** Attempt a substitution **/
562     if (!substitute(&text, "s/Perl/C/")) {
563 	printf("substitute: s/Perl/C...No substitution made.\n\n");
564     }
565
566     SvREFCNT_dec(text);
567     PL_perl_destruct_level = 1;
568     perl_destruct(my_perl);
569     perl_free(my_perl);
570     PERL_SYS_TERM();
571 }
572
573which produces the output (again, long lines have been wrapped here)
574
575  match: Text contains the word 'quarter'.
576
577  match: Text doesn't contain the word 'eighth'.
578
579  matches: m/(wi..)/g found 2 matches...
580  match: will
581  match: with
582
583  substitute: s/[aeiou]//gi...139 substitutions made.
584  Now text is: Whn h s t  cnvnnc str nd th bll cms t sm mnt lk 76 cnts,
585  Mynrd s wr tht thr s smthng h *shld* d, smthng tht wll nbl hm t gt
586  bck qrtr, bt h hs n d *wht*.  H fmbls thrgh hs rd sqzy chngprs nd
587  gvs th by thr xtr pnns wth hs dllr, hpng tht h mght lck nt th crrct
588  mnt.  Th by gvs hm bck tw f hs wn pnns nd thn th bg shny qrtr tht s
589  hs prz. -RCHH
590
591  substitute: s/Perl/C...No substitution made.
592
593=head2 Fiddling with the Perl stack from your C program
594
595When trying to explain stacks, most computer science textbooks mumble
596something about spring-loaded columns of cafeteria plates: the last
597thing you pushed on the stack is the first thing you pop off.  That'll
598do for our purposes: your C program will push some arguments onto "the Perl
599stack", shut its eyes while some magic happens, and then pop the
600results--the return value of your Perl subroutine--off the stack.
601
602First you'll need to know how to convert between C types and Perl
603types, with newSViv() and sv_setnv() and newAV() and all their
604friends.  They're described in L<perlguts> and L<perlapi>.
605
606Then you'll need to know how to manipulate the Perl stack.  That's
607described in L<perlcall>.
608
609Once you've understood those, embedding Perl in C is easy.
610
611Because C has no builtin function for integer exponentiation, let's
612make Perl's ** operator available to it (this is less useful than it
613sounds, because Perl implements ** with C's I<pow()> function).  First
614I'll create a stub exponentiation function in I<power.pl>:
615
616    sub expo {
617        my ($a, $b) = @_;
618        return $a ** $b;
619    }
620
621Now I'll create a C program, I<power.c>, with a function
622I<PerlPower()> that contains all the perlguts necessary to push the
623two arguments into I<expo()> and to pop the return value out.  Take a
624deep breath...
625
626 #include <EXTERN.h>
627 #include <perl.h>
628
629 static PerlInterpreter *my_perl;
630
631 static void
632 PerlPower(int a, int b)
633 {
634   dSP;                            /* initialize stack pointer      */
635   ENTER;                          /* everything created after here */
636   SAVETMPS;                       /* ...is a temporary variable.   */
637   PUSHMARK(SP);                   /* remember the stack pointer    */
638   XPUSHs(sv_2mortal(newSViv(a))); /* push the base onto the stack  */
639   XPUSHs(sv_2mortal(newSViv(b))); /* push the exponent onto stack  */
640   PUTBACK;                      /* make local stack pointer global */
641   call_pv("expo", G_SCALAR);      /* call the function             */
642   SPAGAIN;                        /* refresh stack pointer         */
643                                 /* pop the return value from stack */
644   printf ("%d to the %dth power is %d.\n", a, b, POPi);
645   PUTBACK;
646   FREETMPS;                       /* free that return value        */
647   LEAVE;                       /* ...and the XPUSHed "mortal" args.*/
648 }
649
650 int main (int argc, char **argv, char **env)
651 {
652   char *my_argv[] = { "", "power.pl", NULL };
653
654   PERL_SYS_INIT3(&argc,&argv,&env);
655   my_perl = perl_alloc();
656   perl_construct( my_perl );
657
658   perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL);
659   PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
660   perl_run(my_perl);
661
662   PerlPower(3, 4);                      /*** Compute 3 ** 4 ***/
663
664   perl_destruct(my_perl);
665   perl_free(my_perl);
666   PERL_SYS_TERM();
667   exit(EXIT_SUCCESS);
668 }
669
670
671
672Compile and run:
673
674    % cc -o power power.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
675
676    % power
677    3 to the 4th power is 81.
678
679=head2 Maintaining a persistent interpreter
680
681When developing interactive and/or potentially long-running
682applications, it's a good idea to maintain a persistent interpreter
683rather than allocating and constructing a new interpreter multiple
684times.  The major reason is speed: since Perl will only be loaded into
685memory once.
686
687However, you have to be more cautious with namespace and variable
688scoping when using a persistent interpreter.  In previous examples
689we've been using global variables in the default package C<main>.  We
690knew exactly what code would be run, and assumed we could avoid
691variable collisions and outrageous symbol table growth.
692
693Let's say your application is a server that will occasionally run Perl
694code from some arbitrary file.  Your server has no way of knowing what
695code it's going to run.  Very dangerous.
696
697If the file is pulled in by C<perl_parse()>, compiled into a newly
698constructed interpreter, and subsequently cleaned out with
699C<perl_destruct()> afterwards, you're shielded from most namespace
700troubles.
701
702One way to avoid namespace collisions in this scenario is to translate
703the filename into a guaranteed-unique package name, and then compile
704the code into that package using L<perlfunc/eval>.  In the example
705below, each file will only be compiled once.  Or, the application
706might choose to clean out the symbol table associated with the file
707after it's no longer needed.  Using L<perlapi/call_argv>, We'll
708call the subroutine C<Embed::Persistent::eval_file> which lives in the
709file C<persistent.pl> and pass the filename and boolean cleanup/cache
710flag as arguments.
711
712Note that the process will continue to grow for each file that it
713uses.  In addition, there might be C<AUTOLOAD>ed subroutines and other
714conditions that cause Perl's symbol table to grow.  You might want to
715add some logic that keeps track of the process size, or restarts
716itself after a certain number of requests, to ensure that memory
717consumption is minimized.  You'll also want to scope your variables
718with L<perlfunc/my> whenever possible.
719
720
721 package Embed::Persistent;
722 #persistent.pl
723
724 use strict;
725 our %Cache;
726 use Symbol qw(delete_package);
727
728 sub valid_package_name {
729     my($string) = @_;
730     $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;
731     # second pass only for words starting with a digit
732     $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg;
733
734     # Dress it up as a real package name
735     $string =~ s|/|::|g;
736     return "Embed" . $string;
737 }
738
739 sub eval_file {
740     my($filename, $delete) = @_;
741     my $package = valid_package_name($filename);
742     my $mtime = -M $filename;
743     if(defined $Cache{$package}{mtime}
744        &&
745        $Cache{$package}{mtime} <= $mtime)
746     {
747        # we have compiled this subroutine already,
748        # it has not been updated on disk, nothing left to do
749        print STDERR "already compiled $package->handler\n";
750     }
751     else {
752        local *FH;
753        open FH, $filename or die "open '$filename' $!";
754        local($/) = undef;
755        my $sub = <FH>;
756        close FH;
757
758        #wrap the code into a subroutine inside our unique package
759        my $eval = qq{package $package; sub handler { $sub; }};
760        {
761            # hide our variables within this block
762            my($filename,$mtime,$package,$sub);
763            eval $eval;
764        }
765        die $@ if $@;
766
767        #cache it unless we're cleaning out each time
768        $Cache{$package}{mtime} = $mtime unless $delete;
769     }
770
771     eval {$package->handler;};
772     die $@ if $@;
773
774     delete_package($package) if $delete;
775
776     #take a look if you want
777     #print Devel::Symdump->rnew($package)->as_string, $/;
778 }
779
780 1;
781
782 __END__
783
784 /* persistent.c */
785 #include <EXTERN.h>
786 #include <perl.h>
787
788 /* 1 = clean out filename's symbol table after each request,
789    0 = don't
790 */
791 #ifndef DO_CLEAN
792 #define DO_CLEAN 0
793 #endif
794
795 #define BUFFER_SIZE 1024
796
797 static PerlInterpreter *my_perl = NULL;
798
799 int
800 main(int argc, char **argv, char **env)
801 {
802     char *embedding[] = { "", "persistent.pl", NULL };
803     char *args[] = { "", DO_CLEAN, NULL };
804     char filename[BUFFER_SIZE];
805     int failing, exitstatus;
806
807     PERL_SYS_INIT3(&argc,&argv,&env);
808     if((my_perl = perl_alloc()) == NULL) {
809        fprintf(stderr, "no memory!");
810        exit(EXIT_FAILURE);
811     }
812     perl_construct(my_perl);
813
814     PL_origalen = 1; /* don't let $0 assignment update the
815                         proctitle or embedding[0] */
816     failing = perl_parse(my_perl, NULL, 2, embedding, NULL);
817     PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
818     if(!failing)
819	failing = perl_run(my_perl);
820     if(!failing) {
821        while(printf("Enter file name: ") &&
822              fgets(filename, BUFFER_SIZE, stdin)) {
823
824            filename[strlen(filename)-1] = '\0'; /* strip \n */
825            /* call the subroutine,
826                     passing it the filename as an argument */
827            args[0] = filename;
828            call_argv("Embed::Persistent::eval_file",
829                           G_DISCARD | G_EVAL, args);
830
831            /* check $@ */
832            if(SvTRUE(ERRSV))
833                fprintf(stderr, "eval error: %s\n", SvPV_nolen(ERRSV));
834        }
835     }
836
837     PL_perl_destruct_level = 0;
838     exitstatus = perl_destruct(my_perl);
839     perl_free(my_perl);
840     PERL_SYS_TERM();
841     exit(exitstatus);
842 }
843
844Now compile:
845
846 % cc -o persistent persistent.c \
847        `perl -MExtUtils::Embed -e ccopts -e ldopts`
848
849Here's an example script file:
850
851 #test.pl
852 my $string = "hello";
853 foo($string);
854
855 sub foo {
856     print "foo says: @_\n";
857 }
858
859Now run:
860
861 % persistent
862 Enter file name: test.pl
863 foo says: hello
864 Enter file name: test.pl
865 already compiled Embed::test_2epl->handler
866 foo says: hello
867 Enter file name: ^C
868
869=head2 Execution of END blocks
870
871Traditionally END blocks have been executed at the end of the perl_run.
872This causes problems for applications that never call perl_run. Since
873perl 5.7.2 you can specify C<PL_exit_flags |= PERL_EXIT_DESTRUCT_END>
874to get the new behaviour. This also enables the running of END blocks if
875the perl_parse fails and C<perl_destruct> will return the exit value.
876
877=head2 $0 assignments
878
879When a perl script assigns a value to $0 then the perl runtime will
880try to make this value show up as the program name reported by "ps" by
881updating the memory pointed to by the argv passed to perl_parse() and
882also calling API functions like setproctitle() where available.  This
883behaviour might not be appropriate when embedding perl and can be
884disabled by assigning the value C<1> to the variable C<PL_origalen>
885before perl_parse() is called.
886
887=for apidoc Amnh||PL_origalen
888
889The F<persistent.c> example above is for instance likely to segfault
890when $0 is assigned to if the C<PL_origalen = 1;> assignment is
891removed.  This because perl will try to write to the read only memory
892of the C<embedding[]> strings.
893
894=head2 Maintaining multiple interpreter instances
895
896Some rare applications will need to create more than one interpreter
897during a session.  Such an application might sporadically decide to
898release any resources associated with the interpreter.
899
900The program must take care to ensure that this takes place I<before>
901the next interpreter is constructed.  By default, when perl is not
902built with any special options, the global variable
903C<PL_perl_destruct_level> is set to C<0>, since extra cleaning isn't
904usually needed when a program only ever creates a single interpreter
905in its entire lifetime.
906
907Setting C<PL_perl_destruct_level> to C<1> makes everything squeaky clean:
908
909 while(1) {
910     ...
911     /* reset global variables here with PL_perl_destruct_level = 1 */
912     PL_perl_destruct_level = 1;
913     perl_construct(my_perl);
914     ...
915     /* clean and reset _everything_ during perl_destruct */
916     PL_perl_destruct_level = 1;
917     perl_destruct(my_perl);
918     perl_free(my_perl);
919     ...
920     /* let's go do it again! */
921 }
922
923When I<perl_destruct()> is called, the interpreter's syntax parse tree
924and symbol tables are cleaned up, and global variables are reset.  The
925second assignment to C<PL_perl_destruct_level> is needed because
926perl_construct resets it to C<0>.
927
928Now suppose we have more than one interpreter instance running at the
929same time.  This is feasible, but only if you used the Configure option
930C<-Dusemultiplicity> or the options C<-Dusethreads -Duseithreads> when
931building perl.  By default, enabling one of these Configure options
932sets the per-interpreter global variable C<PL_perl_destruct_level> to
933C<1>, so that thorough cleaning is automatic and interpreter variables
934are initialized correctly.  Even if you don't intend to run two or
935more interpreters at the same time, but to run them sequentially, like
936in the above example, it is recommended to build perl with the
937C<-Dusemultiplicity> option otherwise some interpreter variables may
938not be initialized correctly between consecutive runs and your
939application may crash.
940
941See also L<perlxs/Thread-aware system interfaces>.
942
943Using C<-Dusethreads -Duseithreads> rather than C<-Dusemultiplicity>
944is more appropriate if you intend to run multiple interpreters
945concurrently in different threads, because it enables support for
946linking in the thread libraries of your system with the interpreter.
947
948Let's give it a try:
949
950
951 #include <EXTERN.h>
952 #include <perl.h>
953
954 /* we're going to embed two interpreters */
955
956 #define SAY_HELLO "-e", "print qq(Hi, I'm $^X\n)"
957
958 int main(int argc, char **argv, char **env)
959 {
960     PerlInterpreter *one_perl, *two_perl;
961     char *one_args[] = { "one_perl", SAY_HELLO, NULL };
962     char *two_args[] = { "two_perl", SAY_HELLO, NULL };
963
964     PERL_SYS_INIT3(&argc,&argv,&env);
965     one_perl = perl_alloc();
966     two_perl = perl_alloc();
967
968     PERL_SET_CONTEXT(one_perl);
969     perl_construct(one_perl);
970     PERL_SET_CONTEXT(two_perl);
971     perl_construct(two_perl);
972
973     PERL_SET_CONTEXT(one_perl);
974     perl_parse(one_perl, NULL, 3, one_args, (char **)NULL);
975     PERL_SET_CONTEXT(two_perl);
976     perl_parse(two_perl, NULL, 3, two_args, (char **)NULL);
977
978     PERL_SET_CONTEXT(one_perl);
979     perl_run(one_perl);
980     PERL_SET_CONTEXT(two_perl);
981     perl_run(two_perl);
982
983     PERL_SET_CONTEXT(one_perl);
984     perl_destruct(one_perl);
985     PERL_SET_CONTEXT(two_perl);
986     perl_destruct(two_perl);
987
988     PERL_SET_CONTEXT(one_perl);
989     perl_free(one_perl);
990     PERL_SET_CONTEXT(two_perl);
991     perl_free(two_perl);
992     PERL_SYS_TERM();
993     exit(EXIT_SUCCESS);
994 }
995
996Note the calls to PERL_SET_CONTEXT().  These are necessary to initialize
997the global state that tracks which interpreter is the "current" one on
998the particular process or thread that may be running it.  It should
999always be used if you have more than one interpreter and are making
1000perl API calls on both interpreters in an interleaved fashion.
1001
1002PERL_SET_CONTEXT(interp) should also be called whenever C<interp> is
1003used by a thread that did not create it (using either perl_alloc(), or
1004the more esoteric perl_clone()).
1005
1006Compile as usual:
1007
1008 % cc -o multiplicity multiplicity.c \
1009  `perl -MExtUtils::Embed -e ccopts -e ldopts`
1010
1011Run it, Run it:
1012
1013 % multiplicity
1014 Hi, I'm one_perl
1015 Hi, I'm two_perl
1016
1017=head2 Using Perl modules, which themselves use C libraries, from your C
1018program
1019
1020If you've played with the examples above and tried to embed a script
1021that I<use()>s a Perl module (such as I<Socket>) which itself uses a C or C++
1022library, this probably happened:
1023
1024
1025 Can't load module Socket, dynamic loading not available in this perl.
1026  (You may need to build a new perl executable which either supports
1027  dynamic loading or has the Socket module statically linked into it.)
1028
1029
1030What's wrong?
1031
1032Your interpreter doesn't know how to communicate with these extensions
1033on its own.  A little glue will help.  Up until now you've been
1034calling I<perl_parse()>, handing it NULL for the second argument:
1035
1036 perl_parse(my_perl, NULL, argc, my_argv, NULL);
1037
1038That's where the glue code can be inserted to create the initial contact
1039between Perl and linked C/C++ routines. Let's take a look some pieces of
1040I<perlmain.c> to see how Perl does this:
1041
1042 static void xs_init (pTHX);
1043
1044 EXTERN_C void boot_DynaLoader (pTHX_ CV* cv);
1045 EXTERN_C void boot_Socket (pTHX_ CV* cv);
1046
1047
1048 EXTERN_C void
1049 xs_init(pTHX)
1050 {
1051        char *file = __FILE__;
1052        /* DynaLoader is a special case */
1053        newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
1054        newXS("Socket::bootstrap", boot_Socket, file);
1055 }
1056
1057Simply put: for each extension linked with your Perl executable
1058(determined during its initial configuration on your
1059computer or when adding a new extension),
1060a Perl subroutine is created to incorporate the extension's
1061routines.  Normally, that subroutine is named
1062I<Module::bootstrap()> and is invoked when you say I<use Module>.  In
1063turn, this hooks into an XSUB, I<boot_Module>, which creates a Perl
1064counterpart for each of the extension's XSUBs.  Don't worry about this
1065part; leave that to the I<xsubpp> and extension authors.  If your
1066extension is dynamically loaded, DynaLoader creates I<Module::bootstrap()>
1067for you on the fly.  In fact, if you have a working DynaLoader then there
1068is rarely any need to link in any other extensions statically.
1069
1070
1071Once you have this code, slap it into the second argument of I<perl_parse()>:
1072
1073
1074 perl_parse(my_perl, xs_init, argc, my_argv, NULL);
1075
1076
1077Then compile:
1078
1079 % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
1080
1081 % interp
1082   use Socket;
1083   use SomeDynamicallyLoadedModule;
1084
1085   print "Now I can use extensions!\n"'
1086
1087B<ExtUtils::Embed> can also automate writing the I<xs_init> glue code.
1088
1089 % perl -MExtUtils::Embed -e xsinit -- -o perlxsi.c
1090 % cc -c perlxsi.c `perl -MExtUtils::Embed -e ccopts`
1091 % cc -c interp.c  `perl -MExtUtils::Embed -e ccopts`
1092 % cc -o interp perlxsi.o interp.o `perl -MExtUtils::Embed -e ldopts`
1093
1094Consult L<perlxs>, L<perlguts>, and L<perlapi> for more details.
1095
1096=head2 Using embedded Perl with POSIX locales
1097
1098(See L<perllocale> for information about these.)
1099When a Perl interpreter normally starts up, it tells the system it wants
1100to use the system's default locale.  This is often, but not necessarily,
1101the "C" or "POSIX" locale.  Absent a S<C<"use locale">> within the perl
1102code, this mostly has no effect (but see L<perllocale/Not within the
1103scope of "use locale">).  Also, there is not a problem if the
1104locale you want to use in your embedded perl is the same as the system
1105default.  However, this doesn't work if you have set up and want to use
1106a locale that isn't the system default one.  Starting in Perl v5.20, you
1107can tell the embedded Perl interpreter that the locale is already
1108properly set up, and to skip doing its own normal initialization.  It
1109skips if the environment variable C<PERL_SKIP_LOCALE_INIT> is set (even
1110if set to 0 or C<"">).  A perl that has this capability will define the
1111C pre-processor symbol C<HAS_SKIP_LOCALE_INIT>.  This allows code that
1112has to work with multiple Perl versions to do some sort of work-around
1113when confronted with an earlier Perl.
1114
1115=for apidoc Amnh||HAS_SKIP_LOCALE_INIT
1116
1117If your program is using the POSIX 2008 multi-thread locale
1118functionality, you should switch into the global locale and set that up
1119properly before starting the Perl interpreter.  It will then properly
1120switch back to using the thread-safe functions.
1121
1122=head1 Hiding Perl_
1123
1124If you completely hide the short forms of the Perl public API,
1125add -DPERL_NO_SHORT_NAMES to the compilation flags.  This means that
1126for example instead of writing
1127
1128    warn("%d bottles of beer on the wall", bottlecount);
1129
1130you will have to write the explicit full form
1131
1132    Perl_warn(aTHX_ "%d bottles of beer on the wall", bottlecount);
1133
1134(See L<perlguts/"Background and MULTIPLICITY"> for the explanation
1135of the C<aTHX_>. )  Hiding the short forms is very useful for avoiding
1136all sorts of nasty (C preprocessor or otherwise) conflicts with other
1137software packages (Perl defines about 2400 APIs with these short names,
1138take or leave few hundred, so there certainly is room for conflict.)
1139
1140=head1 MORAL
1141
1142You can sometimes I<write faster code> in C, but
1143you can always I<write code faster> in Perl.  Because you can use
1144each from the other, combine them as you wish.
1145
1146
1147=head1 AUTHOR
1148
1149Jon Orwant <F<orwant@media.mit.edu>> and Doug MacEachern
1150<F<dougm@covalent.net>>, with small contributions from Tim Bunce, Tom
1151Christiansen, Guy Decoux, Hallvard Furuseth, Dov Grobgeld, and Ilya
1152Zakharevich.
1153
1154Doug MacEachern has an article on embedding in Volume 1, Issue 4 of
1155The Perl Journal ( L<http://www.tpj.com/> ).  Doug is also the developer of the
1156most widely-used Perl embedding: the mod_perl system
1157(perl.apache.org), which embeds Perl in the Apache web server.
1158Oracle, Binary Evolution, ActiveState, and Ben Sugars's nsapi_perl
1159have used this model for Oracle, Netscape and Internet Information
1160Server Perl plugins.
1161
1162=head1 COPYRIGHT
1163
1164Copyright (C) 1995, 1996, 1997, 1998 Doug MacEachern and Jon Orwant.  All
1165Rights Reserved.
1166
1167This document may be distributed under the same terms as Perl itself.
1168