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