Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1069 lines
34 KiB

  1. =head1 NAME
  2. perlembed - how to embed perl in your C program
  3. =head1 DESCRIPTION
  4. =head2 PREAMBLE
  5. Do you want to:
  6. =over 5
  7. =item B<Use C from Perl?>
  8. Read L<perlxstut>, L<perlxs>, L<h2xs>, L<perlguts>, and L<perlapi>.
  9. =item B<Use a Unix program from Perl?>
  10. Read about back-quotes and about C<system> and C<exec> in L<perlfunc>.
  11. =item B<Use Perl from Perl?>
  12. Read about L<perlfunc/do> and L<perlfunc/eval> and L<perlfunc/require>
  13. and L<perlfunc/use>.
  14. =item B<Use C from C?>
  15. Rethink your design.
  16. =item B<Use Perl from C?>
  17. Read on...
  18. =back
  19. =head2 ROADMAP
  20. =over 5
  21. =item *
  22. Compiling your C program
  23. =item *
  24. Adding a Perl interpreter to your C program
  25. =item *
  26. Calling a Perl subroutine from your C program
  27. =item *
  28. Evaluating a Perl statement from your C program
  29. =item *
  30. Performing Perl pattern matches and substitutions from your C program
  31. =item *
  32. Fiddling with the Perl stack from your C program
  33. =item *
  34. Maintaining a persistent interpreter
  35. =item *
  36. Maintaining multiple interpreter instances
  37. =item *
  38. Using Perl modules, which themselves use C libraries, from your C program
  39. =item *
  40. Embedding Perl under Win32
  41. =back
  42. =head2 Compiling your C program
  43. If you have trouble compiling the scripts in this documentation,
  44. you're not alone. The cardinal rule: COMPILE THE PROGRAMS IN EXACTLY
  45. THE SAME WAY THAT YOUR PERL WAS COMPILED. (Sorry for yelling.)
  46. Also, every C program that uses Perl must link in the I<perl library>.
  47. What's that, you ask? Perl is itself written in C; the perl library
  48. is the collection of compiled C programs that were used to create your
  49. perl executable (I</usr/bin/perl> or equivalent). (Corollary: you
  50. can't use Perl from your C program unless Perl has been compiled on
  51. your machine, or installed properly--that's why you shouldn't blithely
  52. copy Perl executables from machine to machine without also copying the
  53. I<lib> directory.)
  54. When you use Perl from C, your C program will--usually--allocate,
  55. "run", and deallocate a I<PerlInterpreter> object, which is defined by
  56. the perl library.
  57. If your copy of Perl is recent enough to contain this documentation
  58. (version 5.002 or later), then the perl library (and I<EXTERN.h> and
  59. I<perl.h>, which you'll also need) will reside in a directory
  60. that looks like this:
  61. /usr/local/lib/perl5/your_architecture_here/CORE
  62. or perhaps just
  63. /usr/local/lib/perl5/CORE
  64. or maybe something like
  65. /usr/opt/perl5/CORE
  66. Execute this statement for a hint about where to find CORE:
  67. perl -MConfig -e 'print $Config{archlib}'
  68. Here's how you'd compile the example in the next section,
  69. L<Adding a Perl interpreter to your C program>, on my Linux box:
  70. % gcc -O2 -Dbool=char -DHAS_BOOL -I/usr/local/include
  71. -I/usr/local/lib/perl5/i586-linux/5.003/CORE
  72. -L/usr/local/lib/perl5/i586-linux/5.003/CORE
  73. -o interp interp.c -lperl -lm
  74. (That's all one line.) On my DEC Alpha running old 5.003_05, the
  75. incantation is a bit different:
  76. % cc -O2 -Olimit 2900 -DSTANDARD_C -I/usr/local/include
  77. -I/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE
  78. -L/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE -L/usr/local/lib
  79. -D__LANGUAGE_C__ -D_NO_PROTO -o interp interp.c -lperl -lm
  80. How can you figure out what to add? Assuming your Perl is post-5.001,
  81. execute a C<perl -V> command and pay special attention to the "cc" and
  82. "ccflags" information.
  83. You'll have to choose the appropriate compiler (I<cc>, I<gcc>, et al.) for
  84. your machine: C<perl -MConfig -e 'print $Config{cc}'> will tell you what
  85. to use.
  86. You'll also have to choose the appropriate library directory
  87. (I</usr/local/lib/...>) for your machine. If your compiler complains
  88. that certain functions are undefined, or that it can't locate
  89. I<-lperl>, then you need to change the path following the C<-L>. If it
  90. complains that it can't find I<EXTERN.h> and I<perl.h>, you need to
  91. change the path following the C<-I>.
  92. You may have to add extra libraries as well. Which ones?
  93. Perhaps those printed by
  94. perl -MConfig -e 'print $Config{libs}'
  95. Provided your perl binary was properly configured and installed the
  96. B<ExtUtils::Embed> module will determine all of this information for
  97. you:
  98. % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  99. If the B<ExtUtils::Embed> module isn't part of your Perl distribution,
  100. you can retrieve it from
  101. http://www.perl.com/perl/CPAN/modules/by-module/ExtUtils/. (If
  102. this documentation came from your Perl distribution, then you're
  103. running 5.004 or better and you already have it.)
  104. The B<ExtUtils::Embed> kit on CPAN also contains all source code for
  105. the examples in this document, tests, additional examples and other
  106. information you may find useful.
  107. =head2 Adding a Perl interpreter to your C program
  108. In a sense, perl (the C program) is a good example of embedding Perl
  109. (the language), so I'll demonstrate embedding with I<miniperlmain.c>,
  110. included in the source distribution. Here's a bastardized, nonportable
  111. version of I<miniperlmain.c> containing the essentials of embedding:
  112. #include <EXTERN.h> /* from the Perl distribution */
  113. #include <perl.h> /* from the Perl distribution */
  114. static PerlInterpreter *my_perl; /*** The Perl interpreter ***/
  115. int main(int argc, char **argv, char **env)
  116. {
  117. my_perl = perl_alloc();
  118. perl_construct(my_perl);
  119. perl_parse(my_perl, NULL, argc, argv, (char **)NULL);
  120. perl_run(my_perl);
  121. perl_destruct(my_perl);
  122. perl_free(my_perl);
  123. }
  124. Notice that we don't use the C<env> pointer. Normally handed to
  125. C<perl_parse> as its final argument, C<env> here is replaced by
  126. C<NULL>, which means that the current environment will be used.
  127. Now compile this program (I'll call it I<interp.c>) into an executable:
  128. % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  129. After a successful compilation, you'll be able to use I<interp> just
  130. like perl itself:
  131. % interp
  132. print "Pretty Good Perl \n";
  133. print "10890 - 9801 is ", 10890 - 9801;
  134. <CTRL-D>
  135. Pretty Good Perl
  136. 10890 - 9801 is 1089
  137. or
  138. % interp -e 'printf("%x", 3735928559)'
  139. deadbeef
  140. You can also read and execute Perl statements from a file while in the
  141. midst of your C program, by placing the filename in I<argv[1]> before
  142. calling I<perl_run>.
  143. =head2 Calling a Perl subroutine from your C program
  144. To call individual Perl subroutines, you can use any of the B<call_*>
  145. functions documented in L<perlcall>.
  146. In this example we'll use C<call_argv>.
  147. That's shown below, in a program I'll call I<showtime.c>.
  148. #include <EXTERN.h>
  149. #include <perl.h>
  150. static PerlInterpreter *my_perl;
  151. int main(int argc, char **argv, char **env)
  152. {
  153. char *args[] = { NULL };
  154. my_perl = perl_alloc();
  155. perl_construct(my_perl);
  156. perl_parse(my_perl, NULL, argc, argv, NULL);
  157. /*** skipping perl_run() ***/
  158. call_argv("showtime", G_DISCARD | G_NOARGS, args);
  159. perl_destruct(my_perl);
  160. perl_free(my_perl);
  161. }
  162. where I<showtime> is a Perl subroutine that takes no arguments (that's the
  163. I<G_NOARGS>) and for which I'll ignore the return value (that's the
  164. I<G_DISCARD>). Those flags, and others, are discussed in L<perlcall>.
  165. I'll define the I<showtime> subroutine in a file called I<showtime.pl>:
  166. print "I shan't be printed.";
  167. sub showtime {
  168. print time;
  169. }
  170. Simple enough. Now compile and run:
  171. % cc -o showtime showtime.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  172. % showtime showtime.pl
  173. 818284590
  174. yielding the number of seconds that elapsed between January 1, 1970
  175. (the beginning of the Unix epoch), and the moment I began writing this
  176. sentence.
  177. In this particular case we don't have to call I<perl_run>, but in
  178. general it's considered good practice to ensure proper initialization
  179. of library code, including execution of all object C<DESTROY> methods
  180. and package C<END {}> blocks.
  181. If you want to pass arguments to the Perl subroutine, you can add
  182. strings to the C<NULL>-terminated C<args> list passed to
  183. I<call_argv>. For other data types, or to examine return values,
  184. you'll need to manipulate the Perl stack. That's demonstrated in
  185. L<Fiddling with the Perl stack from your C program>.
  186. =head2 Evaluating a Perl statement from your C program
  187. Perl provides two API functions to evaluate pieces of Perl code.
  188. These are L<perlapi/eval_sv> and L<perlapi/eval_pv>.
  189. Arguably, these are the only routines you'll ever need to execute
  190. snippets of Perl code from within your C program. Your code can be as
  191. long as you wish; it can contain multiple statements; it can employ
  192. L<perlfunc/use>, L<perlfunc/require>, and L<perlfunc/do> to
  193. include external Perl files.
  194. I<eval_pv> lets us evaluate individual Perl strings, and then
  195. extract variables for coercion into C types. The following program,
  196. I<string.c>, executes three Perl strings, extracting an C<int> from
  197. the first, a C<float> from the second, and a C<char *> from the third.
  198. #include <EXTERN.h>
  199. #include <perl.h>
  200. static PerlInterpreter *my_perl;
  201. main (int argc, char **argv, char **env)
  202. {
  203. STRLEN n_a;
  204. char *embedding[] = { "", "-e", "0" };
  205. my_perl = perl_alloc();
  206. perl_construct( my_perl );
  207. perl_parse(my_perl, NULL, 3, embedding, NULL);
  208. perl_run(my_perl);
  209. /** Treat $a as an integer **/
  210. eval_pv("$a = 3; $a **= 2", TRUE);
  211. printf("a = %d\n", SvIV(get_sv("a", FALSE)));
  212. /** Treat $a as a float **/
  213. eval_pv("$a = 3.14; $a **= 2", TRUE);
  214. printf("a = %f\n", SvNV(get_sv("a", FALSE)));
  215. /** Treat $a as a string **/
  216. eval_pv("$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);", TRUE);
  217. printf("a = %s\n", SvPV(get_sv("a", FALSE), n_a));
  218. perl_destruct(my_perl);
  219. perl_free(my_perl);
  220. }
  221. 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>.
  222. If you compile and run I<string.c>, you'll see the results of using
  223. I<SvIV()> to create an C<int>, I<SvNV()> to create a C<float>, and
  224. I<SvPV()> to create a string:
  225. a = 9
  226. a = 9.859600
  227. a = Just Another Perl Hacker
  228. In the example above, we've created a global variable to temporarily
  229. store the computed value of our eval'd expression. It is also
  230. possible and in most cases a better strategy to fetch the return value
  231. from I<eval_pv()> instead. Example:
  232. ...
  233. STRLEN n_a;
  234. SV *val = eval_pv("reverse 'rekcaH lreP rehtonA tsuJ'", TRUE);
  235. printf("%s\n", SvPV(val,n_a));
  236. ...
  237. This way, we avoid namespace pollution by not creating global
  238. variables and we've simplified our code as well.
  239. =head2 Performing Perl pattern matches and substitutions from your C program
  240. The I<eval_sv()> function lets us evaluate strings of Perl code, so we can
  241. define some functions that use it to "specialize" in matches and
  242. substitutions: I<match()>, I<substitute()>, and I<matches()>.
  243. I32 match(SV *string, char *pattern);
  244. Given a string and a pattern (e.g., C<m/clasp/> or C</\b\w*\b/>, which
  245. in your C program might appear as "/\\b\\w*\\b/"), match()
  246. returns 1 if the string matches the pattern and 0 otherwise.
  247. int substitute(SV **string, char *pattern);
  248. Given a pointer to an C<SV> and an C<=~> operation (e.g.,
  249. C<s/bob/robert/g> or C<tr[A-Z][a-z]>), substitute() modifies the string
  250. within the C<AV> at according to the operation, returning the number of substitutions
  251. made.
  252. int matches(SV *string, char *pattern, AV **matches);
  253. Given an C<SV>, a pattern, and a pointer to an empty C<AV>,
  254. matches() evaluates C<$string =~ $pattern> in a list context, and
  255. fills in I<matches> with the array elements, returning the number of matches found.
  256. Here's a sample program, I<match.c>, that uses all three (long lines have
  257. been wrapped here):
  258. #include <EXTERN.h>
  259. #include <perl.h>
  260. /** my_eval_sv(code, error_check)
  261. ** kinda like eval_sv(),
  262. ** but we pop the return value off the stack
  263. **/
  264. SV* my_eval_sv(SV *sv, I32 croak_on_error)
  265. {
  266. dSP;
  267. SV* retval;
  268. STRLEN n_a;
  269. PUSHMARK(SP);
  270. eval_sv(sv, G_SCALAR);
  271. SPAGAIN;
  272. retval = POPs;
  273. PUTBACK;
  274. if (croak_on_error && SvTRUE(ERRSV))
  275. croak(SvPVx(ERRSV, n_a));
  276. return retval;
  277. }
  278. /** match(string, pattern)
  279. **
  280. ** Used for matches in a scalar context.
  281. **
  282. ** Returns 1 if the match was successful; 0 otherwise.
  283. **/
  284. I32 match(SV *string, char *pattern)
  285. {
  286. SV *command = NEWSV(1099, 0), *retval;
  287. STRLEN n_a;
  288. sv_setpvf(command, "my $string = '%s'; $string =~ %s",
  289. SvPV(string,n_a), pattern);
  290. retval = my_eval_sv(command, TRUE);
  291. SvREFCNT_dec(command);
  292. return SvIV(retval);
  293. }
  294. /** substitute(string, pattern)
  295. **
  296. ** Used for =~ operations that modify their left-hand side (s/// and tr///)
  297. **
  298. ** Returns the number of successful matches, and
  299. ** modifies the input string if there were any.
  300. **/
  301. I32 substitute(SV **string, char *pattern)
  302. {
  303. SV *command = NEWSV(1099, 0), *retval;
  304. STRLEN n_a;
  305. sv_setpvf(command, "$string = '%s'; ($string =~ %s)",
  306. SvPV(*string,n_a), pattern);
  307. retval = my_eval_sv(command, TRUE);
  308. SvREFCNT_dec(command);
  309. *string = get_sv("string", FALSE);
  310. return SvIV(retval);
  311. }
  312. /** matches(string, pattern, matches)
  313. **
  314. ** Used for matches in a list context.
  315. **
  316. ** Returns the number of matches,
  317. ** and fills in **matches with the matching substrings
  318. **/
  319. I32 matches(SV *string, char *pattern, AV **match_list)
  320. {
  321. SV *command = NEWSV(1099, 0);
  322. I32 num_matches;
  323. STRLEN n_a;
  324. sv_setpvf(command, "my $string = '%s'; @array = ($string =~ %s)",
  325. SvPV(string,n_a), pattern);
  326. my_eval_sv(command, TRUE);
  327. SvREFCNT_dec(command);
  328. *match_list = get_av("array", FALSE);
  329. num_matches = av_len(*match_list) + 1; /** assume $[ is 0 **/
  330. return num_matches;
  331. }
  332. main (int argc, char **argv, char **env)
  333. {
  334. PerlInterpreter *my_perl = perl_alloc();
  335. char *embedding[] = { "", "-e", "0" };
  336. AV *match_list;
  337. I32 num_matches, i;
  338. SV *text = NEWSV(1099,0);
  339. STRLEN n_a;
  340. perl_construct(my_perl);
  341. perl_parse(my_perl, NULL, 3, embedding, NULL);
  342. sv_setpv(text, "When he is at a convenience store and the bill comes to some amount like 76 cents, Maynard is aware that there is something he *should* do, something that will enable him to get back a quarter, but he has no idea *what*. He fumbles through his red squeezey changepurse and gives the boy three extra pennies with his dollar, hoping that he might luck into the correct amount. The boy gives him back two of his own pennies and then the big shiny quarter that is his prize. -RICHH");
  343. if (match(text, "m/quarter/")) /** Does text contain 'quarter'? **/
  344. printf("match: Text contains the word 'quarter'.\n\n");
  345. else
  346. printf("match: Text doesn't contain the word 'quarter'.\n\n");
  347. if (match(text, "m/eighth/")) /** Does text contain 'eighth'? **/
  348. printf("match: Text contains the word 'eighth'.\n\n");
  349. else
  350. printf("match: Text doesn't contain the word 'eighth'.\n\n");
  351. /** Match all occurrences of /wi../ **/
  352. num_matches = matches(text, "m/(wi..)/g", &match_list);
  353. printf("matches: m/(wi..)/g found %d matches...\n", num_matches);
  354. for (i = 0; i < num_matches; i++)
  355. printf("match: %s\n", SvPV(*av_fetch(match_list, i, FALSE),n_a));
  356. printf("\n");
  357. /** Remove all vowels from text **/
  358. num_matches = substitute(&text, "s/[aeiou]//gi");
  359. if (num_matches) {
  360. printf("substitute: s/[aeiou]//gi...%d substitutions made.\n",
  361. num_matches);
  362. printf("Now text is: %s\n\n", SvPV(text,n_a));
  363. }
  364. /** Attempt a substitution **/
  365. if (!substitute(&text, "s/Perl/C/")) {
  366. printf("substitute: s/Perl/C...No substitution made.\n\n");
  367. }
  368. SvREFCNT_dec(text);
  369. PL_perl_destruct_level = 1;
  370. perl_destruct(my_perl);
  371. perl_free(my_perl);
  372. }
  373. which produces the output (again, long lines have been wrapped here)
  374. match: Text contains the word 'quarter'.
  375. match: Text doesn't contain the word 'eighth'.
  376. matches: m/(wi..)/g found 2 matches...
  377. match: will
  378. match: with
  379. substitute: s/[aeiou]//gi...139 substitutions made.
  380. Now text is: Whn h s t cnvnnc str nd th bll cms t sm mnt lk 76 cnts,
  381. Mynrd s wr tht thr s smthng h *shld* d, smthng tht wll nbl hm t gt bck
  382. qrtr, bt h hs n d *wht*. H fmbls thrgh hs rd sqzy chngprs nd gvs th by
  383. thr xtr pnns wth hs dllr, hpng tht h mght lck nt th crrct mnt. Th by gvs
  384. hm bck tw f hs wn pnns nd thn th bg shny qrtr tht s hs prz. -RCHH
  385. substitute: s/Perl/C...No substitution made.
  386. =head2 Fiddling with the Perl stack from your C program
  387. When trying to explain stacks, most computer science textbooks mumble
  388. something about spring-loaded columns of cafeteria plates: the last
  389. thing you pushed on the stack is the first thing you pop off. That'll
  390. do for our purposes: your C program will push some arguments onto "the Perl
  391. stack", shut its eyes while some magic happens, and then pop the
  392. results--the return value of your Perl subroutine--off the stack.
  393. First you'll need to know how to convert between C types and Perl
  394. types, with newSViv() and sv_setnv() and newAV() and all their
  395. friends. They're described in L<perlguts> and L<perlapi>.
  396. Then you'll need to know how to manipulate the Perl stack. That's
  397. described in L<perlcall>.
  398. Once you've understood those, embedding Perl in C is easy.
  399. Because C has no builtin function for integer exponentiation, let's
  400. make Perl's ** operator available to it (this is less useful than it
  401. sounds, because Perl implements ** with C's I<pow()> function). First
  402. I'll create a stub exponentiation function in I<power.pl>:
  403. sub expo {
  404. my ($a, $b) = @_;
  405. return $a ** $b;
  406. }
  407. Now I'll create a C program, I<power.c>, with a function
  408. I<PerlPower()> that contains all the perlguts necessary to push the
  409. two arguments into I<expo()> and to pop the return value out. Take a
  410. deep breath...
  411. #include <EXTERN.h>
  412. #include <perl.h>
  413. static PerlInterpreter *my_perl;
  414. static void
  415. PerlPower(int a, int b)
  416. {
  417. dSP; /* initialize stack pointer */
  418. ENTER; /* everything created after here */
  419. SAVETMPS; /* ...is a temporary variable. */
  420. PUSHMARK(SP); /* remember the stack pointer */
  421. XPUSHs(sv_2mortal(newSViv(a))); /* push the base onto the stack */
  422. XPUSHs(sv_2mortal(newSViv(b))); /* push the exponent onto stack */
  423. PUTBACK; /* make local stack pointer global */
  424. call_pv("expo", G_SCALAR); /* call the function */
  425. SPAGAIN; /* refresh stack pointer */
  426. /* pop the return value from stack */
  427. printf ("%d to the %dth power is %d.\n", a, b, POPi);
  428. PUTBACK;
  429. FREETMPS; /* free that return value */
  430. LEAVE; /* ...and the XPUSHed "mortal" args.*/
  431. }
  432. int main (int argc, char **argv, char **env)
  433. {
  434. char *my_argv[] = { "", "power.pl" };
  435. my_perl = perl_alloc();
  436. perl_construct( my_perl );
  437. perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL);
  438. perl_run(my_perl);
  439. PerlPower(3, 4); /*** Compute 3 ** 4 ***/
  440. perl_destruct(my_perl);
  441. perl_free(my_perl);
  442. }
  443. Compile and run:
  444. % cc -o power power.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  445. % power
  446. 3 to the 4th power is 81.
  447. =head2 Maintaining a persistent interpreter
  448. When developing interactive and/or potentially long-running
  449. applications, it's a good idea to maintain a persistent interpreter
  450. rather than allocating and constructing a new interpreter multiple
  451. times. The major reason is speed: since Perl will only be loaded into
  452. memory once.
  453. However, you have to be more cautious with namespace and variable
  454. scoping when using a persistent interpreter. In previous examples
  455. we've been using global variables in the default package C<main>. We
  456. knew exactly what code would be run, and assumed we could avoid
  457. variable collisions and outrageous symbol table growth.
  458. Let's say your application is a server that will occasionally run Perl
  459. code from some arbitrary file. Your server has no way of knowing what
  460. code it's going to run. Very dangerous.
  461. If the file is pulled in by C<perl_parse()>, compiled into a newly
  462. constructed interpreter, and subsequently cleaned out with
  463. C<perl_destruct()> afterwards, you're shielded from most namespace
  464. troubles.
  465. One way to avoid namespace collisions in this scenario is to translate
  466. the filename into a guaranteed-unique package name, and then compile
  467. the code into that package using L<perlfunc/eval>. In the example
  468. below, each file will only be compiled once. Or, the application
  469. might choose to clean out the symbol table associated with the file
  470. after it's no longer needed. Using L<perlapi/call_argv>, We'll
  471. call the subroutine C<Embed::Persistent::eval_file> which lives in the
  472. file C<persistent.pl> and pass the filename and boolean cleanup/cache
  473. flag as arguments.
  474. Note that the process will continue to grow for each file that it
  475. uses. In addition, there might be C<AUTOLOAD>ed subroutines and other
  476. conditions that cause Perl's symbol table to grow. You might want to
  477. add some logic that keeps track of the process size, or restarts
  478. itself after a certain number of requests, to ensure that memory
  479. consumption is minimized. You'll also want to scope your variables
  480. with L<perlfunc/my> whenever possible.
  481. package Embed::Persistent;
  482. #persistent.pl
  483. use strict;
  484. our %Cache;
  485. use Symbol qw(delete_package);
  486. sub valid_package_name {
  487. my($string) = @_;
  488. $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;
  489. # second pass only for words starting with a digit
  490. $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg;
  491. # Dress it up as a real package name
  492. $string =~ s|/|::|g;
  493. return "Embed" . $string;
  494. }
  495. sub eval_file {
  496. my($filename, $delete) = @_;
  497. my $package = valid_package_name($filename);
  498. my $mtime = -M $filename;
  499. if(defined $Cache{$package}{mtime}
  500. &&
  501. $Cache{$package}{mtime} <= $mtime)
  502. {
  503. # we have compiled this subroutine already,
  504. # it has not been updated on disk, nothing left to do
  505. print STDERR "already compiled $package->handler\n";
  506. }
  507. else {
  508. local *FH;
  509. open FH, $filename or die "open '$filename' $!";
  510. local($/) = undef;
  511. my $sub = <FH>;
  512. close FH;
  513. #wrap the code into a subroutine inside our unique package
  514. my $eval = qq{package $package; sub handler { $sub; }};
  515. {
  516. # hide our variables within this block
  517. my($filename,$mtime,$package,$sub);
  518. eval $eval;
  519. }
  520. die $@ if $@;
  521. #cache it unless we're cleaning out each time
  522. $Cache{$package}{mtime} = $mtime unless $delete;
  523. }
  524. eval {$package->handler;};
  525. die $@ if $@;
  526. delete_package($package) if $delete;
  527. #take a look if you want
  528. #print Devel::Symdump->rnew($package)->as_string, $/;
  529. }
  530. 1;
  531. __END__
  532. /* persistent.c */
  533. #include <EXTERN.h>
  534. #include <perl.h>
  535. /* 1 = clean out filename's symbol table after each request, 0 = don't */
  536. #ifndef DO_CLEAN
  537. #define DO_CLEAN 0
  538. #endif
  539. static PerlInterpreter *perl = NULL;
  540. int
  541. main(int argc, char **argv, char **env)
  542. {
  543. char *embedding[] = { "", "persistent.pl" };
  544. char *args[] = { "", DO_CLEAN, NULL };
  545. char filename [1024];
  546. int exitstatus = 0;
  547. STRLEN n_a;
  548. if((perl = perl_alloc()) == NULL) {
  549. fprintf(stderr, "no memory!");
  550. exit(1);
  551. }
  552. perl_construct(perl);
  553. exitstatus = perl_parse(perl, NULL, 2, embedding, NULL);
  554. if(!exitstatus) {
  555. exitstatus = perl_run(perl);
  556. while(printf("Enter file name: ") && gets(filename)) {
  557. /* call the subroutine, passing it the filename as an argument */
  558. args[0] = filename;
  559. call_argv("Embed::Persistent::eval_file",
  560. G_DISCARD | G_EVAL, args);
  561. /* check $@ */
  562. if(SvTRUE(ERRSV))
  563. fprintf(stderr, "eval error: %s\n", SvPV(ERRSV,n_a));
  564. }
  565. }
  566. PL_perl_destruct_level = 0;
  567. perl_destruct(perl);
  568. perl_free(perl);
  569. exit(exitstatus);
  570. }
  571. Now compile:
  572. % cc -o persistent persistent.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  573. Here's a example script file:
  574. #test.pl
  575. my $string = "hello";
  576. foo($string);
  577. sub foo {
  578. print "foo says: @_\n";
  579. }
  580. Now run:
  581. % persistent
  582. Enter file name: test.pl
  583. foo says: hello
  584. Enter file name: test.pl
  585. already compiled Embed::test_2epl->handler
  586. foo says: hello
  587. Enter file name: ^C
  588. =head2 Maintaining multiple interpreter instances
  589. Some rare applications will need to create more than one interpreter
  590. during a session. Such an application might sporadically decide to
  591. release any resources associated with the interpreter.
  592. The program must take care to ensure that this takes place I<before>
  593. the next interpreter is constructed. By default, when perl is not
  594. built with any special options, the global variable
  595. C<PL_perl_destruct_level> is set to C<0>, since extra cleaning isn't
  596. usually needed when a program only ever creates a single interpreter
  597. in its entire lifetime.
  598. Setting C<PL_perl_destruct_level> to C<1> makes everything squeaky clean:
  599. PL_perl_destruct_level = 1;
  600. while(1) {
  601. ...
  602. /* reset global variables here with PL_perl_destruct_level = 1 */
  603. perl_construct(my_perl);
  604. ...
  605. /* clean and reset _everything_ during perl_destruct */
  606. perl_destruct(my_perl);
  607. perl_free(my_perl);
  608. ...
  609. /* let's go do it again! */
  610. }
  611. When I<perl_destruct()> is called, the interpreter's syntax parse tree
  612. and symbol tables are cleaned up, and global variables are reset.
  613. Now suppose we have more than one interpreter instance running at the
  614. same time. This is feasible, but only if you used the Configure option
  615. C<-Dusemultiplicity> or the options C<-Dusethreads -Duseithreads> when
  616. building Perl. By default, enabling one of these Configure options
  617. sets the per-interpreter global variable C<PL_perl_destruct_level> to
  618. C<1>, so that thorough cleaning is automatic.
  619. Using C<-Dusethreads -Duseithreads> rather than C<-Dusemultiplicity>
  620. is more appropriate if you intend to run multiple interpreters
  621. concurrently in different threads, because it enables support for
  622. linking in the thread libraries of your system with the interpreter.
  623. Let's give it a try:
  624. #include <EXTERN.h>
  625. #include <perl.h>
  626. /* we're going to embed two interpreters */
  627. /* we're going to embed two interpreters */
  628. #define SAY_HELLO "-e", "print qq(Hi, I'm $^X\n)"
  629. int main(int argc, char **argv, char **env)
  630. {
  631. PerlInterpreter
  632. *one_perl = perl_alloc(),
  633. *two_perl = perl_alloc();
  634. char *one_args[] = { "one_perl", SAY_HELLO };
  635. char *two_args[] = { "two_perl", SAY_HELLO };
  636. PERL_SET_CONTEXT(one_perl);
  637. perl_construct(one_perl);
  638. PERL_SET_CONTEXT(two_perl);
  639. perl_construct(two_perl);
  640. PERL_SET_CONTEXT(one_perl);
  641. perl_parse(one_perl, NULL, 3, one_args, (char **)NULL);
  642. PERL_SET_CONTEXT(two_perl);
  643. perl_parse(two_perl, NULL, 3, two_args, (char **)NULL);
  644. PERL_SET_CONTEXT(one_perl);
  645. perl_run(one_perl);
  646. PERL_SET_CONTEXT(two_perl);
  647. perl_run(two_perl);
  648. PERL_SET_CONTEXT(one_perl);
  649. perl_destruct(one_perl);
  650. PERL_SET_CONTEXT(two_perl);
  651. perl_destruct(two_perl);
  652. PERL_SET_CONTEXT(one_perl);
  653. perl_free(one_perl);
  654. PERL_SET_CONTEXT(two_perl);
  655. perl_free(two_perl);
  656. }
  657. Note the calls to PERL_SET_CONTEXT(). These are necessary to initialize
  658. the global state that tracks which interpreter is the "current" one on
  659. the particular process or thread that may be running it. It should
  660. always be used if you have more than one interpreter and are making
  661. perl API calls on both interpreters in an interleaved fashion.
  662. PERL_SET_CONTEXT(interp) should also be called whenever C<interp> is
  663. used by a thread that did not create it (using either perl_alloc(), or
  664. the more esoteric perl_clone()).
  665. Compile as usual:
  666. % cc -o multiplicity multiplicity.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  667. Run it, Run it:
  668. % multiplicity
  669. Hi, I'm one_perl
  670. Hi, I'm two_perl
  671. =head2 Using Perl modules, which themselves use C libraries, from your C program
  672. If you've played with the examples above and tried to embed a script
  673. that I<use()>s a Perl module (such as I<Socket>) which itself uses a C or C++ library,
  674. this probably happened:
  675. Can't load module Socket, dynamic loading not available in this perl.
  676. (You may need to build a new perl executable which either supports
  677. dynamic loading or has the Socket module statically linked into it.)
  678. What's wrong?
  679. Your interpreter doesn't know how to communicate with these extensions
  680. on its own. A little glue will help. Up until now you've been
  681. calling I<perl_parse()>, handing it NULL for the second argument:
  682. perl_parse(my_perl, NULL, argc, my_argv, NULL);
  683. That's where the glue code can be inserted to create the initial contact between
  684. Perl and linked C/C++ routines. Let's take a look some pieces of I<perlmain.c>
  685. to see how Perl does this:
  686. static void xs_init (pTHX);
  687. EXTERN_C void boot_DynaLoader (pTHX_ CV* cv);
  688. EXTERN_C void boot_Socket (pTHX_ CV* cv);
  689. EXTERN_C void
  690. xs_init(pTHX)
  691. {
  692. char *file = __FILE__;
  693. /* DynaLoader is a special case */
  694. newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
  695. newXS("Socket::bootstrap", boot_Socket, file);
  696. }
  697. Simply put: for each extension linked with your Perl executable
  698. (determined during its initial configuration on your
  699. computer or when adding a new extension),
  700. a Perl subroutine is created to incorporate the extension's
  701. routines. Normally, that subroutine is named
  702. I<Module::bootstrap()> and is invoked when you say I<use Module>. In
  703. turn, this hooks into an XSUB, I<boot_Module>, which creates a Perl
  704. counterpart for each of the extension's XSUBs. Don't worry about this
  705. part; leave that to the I<xsubpp> and extension authors. If your
  706. extension is dynamically loaded, DynaLoader creates I<Module::bootstrap()>
  707. for you on the fly. In fact, if you have a working DynaLoader then there
  708. is rarely any need to link in any other extensions statically.
  709. Once you have this code, slap it into the second argument of I<perl_parse()>:
  710. perl_parse(my_perl, xs_init, argc, my_argv, NULL);
  711. Then compile:
  712. % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  713. % interp
  714. use Socket;
  715. use SomeDynamicallyLoadedModule;
  716. print "Now I can use extensions!\n"'
  717. B<ExtUtils::Embed> can also automate writing the I<xs_init> glue code.
  718. % perl -MExtUtils::Embed -e xsinit -- -o perlxsi.c
  719. % cc -c perlxsi.c `perl -MExtUtils::Embed -e ccopts`
  720. % cc -c interp.c `perl -MExtUtils::Embed -e ccopts`
  721. % cc -o interp perlxsi.o interp.o `perl -MExtUtils::Embed -e ldopts`
  722. Consult L<perlxs>, L<perlguts>, and L<perlapi> for more details.
  723. =head1 Embedding Perl under Win32
  724. In general, all of the source code shown here should work unmodified under
  725. Windows.
  726. However, there are some caveats about the command-line examples shown.
  727. For starters, backticks won't work under the Win32 native command shell.
  728. The ExtUtils::Embed kit on CPAN ships with a script called
  729. B<genmake>, which generates a simple makefile to build a program from
  730. a single C source file. It can be used like this:
  731. C:\ExtUtils-Embed\eg> perl genmake interp.c
  732. C:\ExtUtils-Embed\eg> nmake
  733. C:\ExtUtils-Embed\eg> interp -e "print qq{I'm embedded in Win32!\n}"
  734. You may wish to use a more robust environment such as the Microsoft
  735. Developer Studio. In this case, run this to generate perlxsi.c:
  736. perl -MExtUtils::Embed -e xsinit
  737. Create a new project and Insert -> Files into Project: perlxsi.c,
  738. perl.lib, and your own source files, e.g. interp.c. Typically you'll
  739. find perl.lib in B<C:\perl\lib\CORE>, if not, you should see the
  740. B<CORE> directory relative to C<perl -V:archlib>. The studio will
  741. also need this path so it knows where to find Perl include files.
  742. This path can be added via the Tools -> Options -> Directories menu.
  743. Finally, select Build -> Build interp.exe and you're ready to go.
  744. =head1 MORAL
  745. You can sometimes I<write faster code> in C, but
  746. you can always I<write code faster> in Perl. Because you can use
  747. each from the other, combine them as you wish.
  748. =head1 AUTHOR
  749. Jon Orwant <F<[email protected]>> and Doug MacEachern
  750. <F<[email protected]>>, with small contributions from Tim Bunce, Tom
  751. Christiansen, Guy Decoux, Hallvard Furuseth, Dov Grobgeld, and Ilya
  752. Zakharevich.
  753. Doug MacEachern has an article on embedding in Volume 1, Issue 4 of
  754. The Perl Journal (http://tpj.com). Doug is also the developer of the
  755. most widely-used Perl embedding: the mod_perl system
  756. (perl.apache.org), which embeds Perl in the Apache web server.
  757. Oracle, Binary Evolution, ActiveState, and Ben Sugars's nsapi_perl
  758. have used this model for Oracle, Netscape and Internet Information
  759. Server Perl plugins.
  760. July 22, 1998
  761. =head1 COPYRIGHT
  762. Copyright (C) 1995, 1996, 1997, 1998 Doug MacEachern and Jon Orwant. All
  763. Rights Reserved.
  764. Permission is granted to make and distribute verbatim copies of this
  765. documentation provided the copyright notice and this permission notice are
  766. preserved on all copies.
  767. Permission is granted to copy and distribute modified versions of this
  768. documentation under the conditions for verbatim copying, provided also
  769. that they are marked clearly as modified versions, that the authors'
  770. names and title are unchanged (though subtitles and additional
  771. authors' names may be added), and that the entire resulting derived
  772. work is distributed under the terms of a permission notice identical
  773. to this one.
  774. Permission is granted to copy and distribute translations of this
  775. documentation into another language, under the above conditions for
  776. modified versions.