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