Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / perl-5.8.0 / man / man1 / perlembed.1
CommitLineData
86530b38
AT
1.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
2.\"
3.\" Standard preamble:
4.\" ========================================================================
5.de Sh \" Subsection heading
6.br
7.if t .Sp
8.ne 5
9.PP
10\fB\\$1\fR
11.PP
12..
13.de Sp \" Vertical space (when we can't use .PP)
14.if t .sp .5v
15.if n .sp
16..
17.de Vb \" Begin verbatim text
18.ft CW
19.nf
20.ne \\$1
21..
22.de Ve \" End verbatim text
23.ft R
24.fi
25..
26.\" Set up some character translations and predefined strings. \*(-- will
27.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28.\" double quote, and \*(R" will give a right double quote. | will give a
29.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
30.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
31.\" expand to `' in nroff, nothing in troff, for use with C<>.
32.tr \(*W-|\(bv\*(Tr
33.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34.ie n \{\
35. ds -- \(*W-
36. ds PI pi
37. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
39. ds L" ""
40. ds R" ""
41. ds C` ""
42. ds C' ""
43'br\}
44.el\{\
45. ds -- \|\(em\|
46. ds PI \(*p
47. ds L" ``
48. ds R" ''
49'br\}
50.\"
51.\" If the F register is turned on, we'll generate index entries on stderr for
52.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53.\" entries marked with X<> in POD. Of course, you'll have to process the
54.\" output yourself in some meaningful fashion.
55.if \nF \{\
56. de IX
57. tm Index:\\$1\t\\n%\t"\\$2"
58..
59. nr % 0
60. rr F
61.\}
62.\"
63.\" For nroff, turn off justification. Always turn off hyphenation; it makes
64.\" way too many mistakes in technical documents.
65.hy 0
66.if n .na
67.\"
68.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69.\" Fear. Run. Save yourself. No user-serviceable parts.
70. \" fudge factors for nroff and troff
71.if n \{\
72. ds #H 0
73. ds #V .8m
74. ds #F .3m
75. ds #[ \f1
76. ds #] \fP
77.\}
78.if t \{\
79. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80. ds #V .6m
81. ds #F 0
82. ds #[ \&
83. ds #] \&
84.\}
85. \" simple accents for nroff and troff
86.if n \{\
87. ds ' \&
88. ds ` \&
89. ds ^ \&
90. ds , \&
91. ds ~ ~
92. ds /
93.\}
94.if t \{\
95. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
101.\}
102. \" troff and (daisy-wheel) nroff accents
103.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110.ds ae a\h'-(\w'a'u*4/10)'e
111.ds Ae A\h'-(\w'A'u*4/10)'E
112. \" corrections for vroff
113.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115. \" for low resolution devices (crt and lpr)
116.if \n(.H>23 .if \n(.V>19 \
117\{\
118. ds : e
119. ds 8 ss
120. ds o a
121. ds d- d\h'-1'\(ga
122. ds D- D\h'-1'\(hy
123. ds th \o'bp'
124. ds Th \o'LP'
125. ds ae ae
126. ds Ae AE
127.\}
128.rm #[ #] #H #V #F C
129.\" ========================================================================
130.\"
131.IX Title "PERLEMBED 1"
132.TH PERLEMBED 1 "2002-06-08" "perl v5.8.0" "Perl Programmers Reference Guide"
133.SH "NAME"
134perlembed \- how to embed perl in your C program
135.SH "DESCRIPTION"
136.IX Header "DESCRIPTION"
137.Sh "\s-1PREAMBLE\s0"
138.IX Subsection "PREAMBLE"
139Do you want to:
140.IP "\fBUse C from Perl?\fR" 5
141.IX Item "Use C from Perl?"
142Read perlxstut, perlxs, h2xs, perlguts, and perlapi.
143.IP "\fBUse a Unix program from Perl?\fR" 5
144.IX Item "Use a Unix program from Perl?"
145Read about back-quotes and about \f(CW\*(C`system\*(C'\fR and \f(CW\*(C`exec\*(C'\fR in perlfunc.
146.IP "\fBUse Perl from Perl?\fR" 5
147.IX Item "Use Perl from Perl?"
148Read about \*(L"do\*(R" in perlfunc and \*(L"eval\*(R" in perlfunc and \*(L"require\*(R" in perlfunc
149and \*(L"use\*(R" in perlfunc.
150.IP "\fBUse C from C?\fR" 5
151.IX Item "Use C from C?"
152Rethink your design.
153.IP "\fBUse Perl from C?\fR" 5
154.IX Item "Use Perl from C?"
155Read on...
156.Sh "\s-1ROADMAP\s0"
157.IX Subsection "ROADMAP"
158.IP "\(bu" 5
159Compiling your C program
160.IP "\(bu" 5
161Adding a Perl interpreter to your C program
162.IP "\(bu" 5
163Calling a Perl subroutine from your C program
164.IP "\(bu" 5
165Evaluating a Perl statement from your C program
166.IP "\(bu" 5
167Performing Perl pattern matches and substitutions from your C program
168.IP "\(bu" 5
169Fiddling with the Perl stack from your C program
170.IP "\(bu" 5
171Maintaining a persistent interpreter
172.IP "\(bu" 5
173Maintaining multiple interpreter instances
174.IP "\(bu" 5
175Using Perl modules, which themselves use C libraries, from your C program
176.IP "\(bu" 5
177Embedding Perl under Win32
178.Sh "Compiling your C program"
179.IX Subsection "Compiling your C program"
180If you have trouble compiling the scripts in this documentation,
181you're not alone. The cardinal rule: \s-1COMPILE\s0 \s-1THE\s0 \s-1PROGRAMS\s0 \s-1IN\s0 \s-1EXACTLY\s0
182\&\s-1THE\s0 \s-1SAME\s0 \s-1WAY\s0 \s-1THAT\s0 \s-1YOUR\s0 \s-1PERL\s0 \s-1WAS\s0 \s-1COMPILED\s0. (Sorry for yelling.)
183.PP
184Also, every C program that uses Perl must link in the \fIperl library\fR.
185What's that, you ask? Perl is itself written in C; the perl library
186is the collection of compiled C programs that were used to create your
187perl executable (\fI/usr/bin/perl\fR or equivalent). (Corollary: you
188can't use Perl from your C program unless Perl has been compiled on
189your machine, or installed properly\*(--that's why you shouldn't blithely
190copy Perl executables from machine to machine without also copying the
191\&\fIlib\fR directory.)
192.PP
193When you use Perl from C, your C program will\*(--usually\-\-allocate,
194\&\*(L"run\*(R", and deallocate a \fIPerlInterpreter\fR object, which is defined by
195the perl library.
196.PP
197If your copy of Perl is recent enough to contain this documentation
198(version 5.002 or later), then the perl library (and \fI\s-1EXTERN\s0.h\fR and
199\&\fIperl.h\fR, which you'll also need) will reside in a directory
200that looks like this:
201.PP
202.Vb 1
203\& /usr/local/lib/perl5/your_architecture_here/CORE
204.Ve
205.PP
206or perhaps just
207.PP
208.Vb 1
209\& /usr/local/lib/perl5/CORE
210.Ve
211.PP
212or maybe something like
213.PP
214.Vb 1
215\& /usr/opt/perl5/CORE
216.Ve
217.PP
218Execute this statement for a hint about where to find \s-1CORE:\s0
219.PP
220.Vb 1
221\& perl -MConfig -e 'print $Config{archlib}'
222.Ve
223.PP
224Here's how you'd compile the example in the next section,
225\&\*(L"Adding a Perl interpreter to your C program\*(R", on my Linux box:
226.PP
227.Vb 4
228\& % gcc -O2 -Dbool=char -DHAS_BOOL -I/usr/local/include
229\& -I/usr/local/lib/perl5/i586-linux/5.003/CORE
230\& -L/usr/local/lib/perl5/i586-linux/5.003/CORE
231\& -o interp interp.c -lperl -lm
232.Ve
233.PP
234(That's all one line.) On my \s-1DEC\s0 Alpha running old 5.003_05, the
235incantation is a bit different:
236.PP
237.Vb 4
238\& % cc -O2 -Olimit 2900 -DSTANDARD_C -I/usr/local/include
239\& -I/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE
240\& -L/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE -L/usr/local/lib
241\& -D__LANGUAGE_C__ -D_NO_PROTO -o interp interp.c -lperl -lm
242.Ve
243.PP
244How can you figure out what to add? Assuming your Perl is post\-5.001,
245execute a \f(CW\*(C`perl \-V\*(C'\fR command and pay special attention to the \*(L"cc\*(R" and
246\&\*(L"ccflags\*(R" information.
247.PP
248You'll have to choose the appropriate compiler (\fIcc\fR, \fIgcc\fR, et al.) for
249your machine: \f(CW\*(C`perl \-MConfig \-e 'print $Config{cc}'\*(C'\fR will tell you what
250to use.
251.PP
252You'll also have to choose the appropriate library directory
253(\fI/usr/local/lib/...\fR) for your machine. If your compiler complains
254that certain functions are undefined, or that it can't locate
255\&\fI\-lperl\fR, then you need to change the path following the \f(CW\*(C`\-L\*(C'\fR. If it
256complains that it can't find \fI\s-1EXTERN\s0.h\fR and \fIperl.h\fR, you need to
257change the path following the \f(CW\*(C`\-I\*(C'\fR.
258.PP
259You may have to add extra libraries as well. Which ones?
260Perhaps those printed by
261.PP
262.Vb 1
263\& perl -MConfig -e 'print $Config{libs}'
264.Ve
265.PP
266Provided your perl binary was properly configured and installed the
267\&\fBExtUtils::Embed\fR module will determine all of this information for
268you:
269.PP
270.Vb 1
271\& % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
272.Ve
273.PP
274If the \fBExtUtils::Embed\fR module isn't part of your Perl distribution,
275you can retrieve it from
276http://www.perl.com/perl/CPAN/modules/by\-module/ExtUtils/
277(If this documentation came from your Perl distribution, then you're
278running 5.004 or better and you already have it.)
279.PP
280The \fBExtUtils::Embed\fR kit on \s-1CPAN\s0 also contains all source code for
281the examples in this document, tests, additional examples and other
282information you may find useful.
283.Sh "Adding a Perl interpreter to your C program"
284.IX Subsection "Adding a Perl interpreter to your C program"
285In a sense, perl (the C program) is a good example of embedding Perl
286(the language), so I'll demonstrate embedding with \fIminiperlmain.c\fR,
287included in the source distribution. Here's a bastardized, nonportable
288version of \fIminiperlmain.c\fR containing the essentials of embedding:
289.PP
290.Vb 2
291\& #include <EXTERN.h> /* from the Perl distribution */
292\& #include <perl.h> /* from the Perl distribution */
293.Ve
294.PP
295.Vb 1
296\& static PerlInterpreter *my_perl; /*** The Perl interpreter ***/
297.Ve
298.PP
299.Vb 10
300\& int main(int argc, char **argv, char **env)
301\& {
302\& my_perl = perl_alloc();
303\& perl_construct(my_perl);
304\& PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
305\& perl_parse(my_perl, NULL, argc, argv, (char **)NULL);
306\& perl_run(my_perl);
307\& perl_destruct(my_perl);
308\& perl_free(my_perl);
309\& }
310.Ve
311.PP
312Notice that we don't use the \f(CW\*(C`env\*(C'\fR pointer. Normally handed to
313\&\f(CW\*(C`perl_parse\*(C'\fR as its final argument, \f(CW\*(C`env\*(C'\fR here is replaced by
314\&\f(CW\*(C`NULL\*(C'\fR, which means that the current environment will be used.
315.PP
316Now compile this program (I'll call it \fIinterp.c\fR) into an executable:
317.PP
318.Vb 1
319\& % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
320.Ve
321.PP
322After a successful compilation, you'll be able to use \fIinterp\fR just
323like perl itself:
324.PP
325.Vb 6
326\& % interp
327\& print "Pretty Good Perl \en";
328\& print "10890 - 9801 is ", 10890 - 9801;
329\& <CTRL-D>
330\& Pretty Good Perl
331\& 10890 - 9801 is 1089
332.Ve
333.PP
334or
335.PP
336.Vb 2
337\& % interp -e 'printf("%x", 3735928559)'
338\& deadbeef
339.Ve
340.PP
341You can also read and execute Perl statements from a file while in the
342midst of your C program, by placing the filename in \fIargv[1]\fR before
343calling \fIperl_run\fR.
344.Sh "Calling a Perl subroutine from your C program"
345.IX Subsection "Calling a Perl subroutine from your C program"
346To call individual Perl subroutines, you can use any of the \fBcall_*\fR
347functions documented in perlcall.
348In this example we'll use \f(CW\*(C`call_argv\*(C'\fR.
349.PP
350That's shown below, in a program I'll call \fIshowtime.c\fR.
351.PP
352.Vb 2
353\& #include <EXTERN.h>
354\& #include <perl.h>
355.Ve
356.PP
357.Vb 1
358\& static PerlInterpreter *my_perl;
359.Ve
360.PP
361.Vb 5
362\& int main(int argc, char **argv, char **env)
363\& {
364\& char *args[] = { NULL };
365\& my_perl = perl_alloc();
366\& perl_construct(my_perl);
367.Ve
368.PP
369.Vb 2
370\& perl_parse(my_perl, NULL, argc, argv, NULL);
371\& PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
372.Ve
373.PP
374.Vb 1
375\& /*** skipping perl_run() ***/
376.Ve
377.PP
378.Vb 1
379\& call_argv("showtime", G_DISCARD | G_NOARGS, args);
380.Ve
381.PP
382.Vb 3
383\& perl_destruct(my_perl);
384\& perl_free(my_perl);
385\& }
386.Ve
387.PP
388where \fIshowtime\fR is a Perl subroutine that takes no arguments (that's the
389\&\fIG_NOARGS\fR) and for which I'll ignore the return value (that's the
390\&\fIG_DISCARD\fR). Those flags, and others, are discussed in perlcall.
391.PP
392I'll define the \fIshowtime\fR subroutine in a file called \fIshowtime.pl\fR:
393.PP
394.Vb 1
395\& print "I shan't be printed.";
396.Ve
397.PP
398.Vb 3
399\& sub showtime {
400\& print time;
401\& }
402.Ve
403.PP
404Simple enough. Now compile and run:
405.PP
406.Vb 1
407\& % cc -o showtime showtime.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
408.Ve
409.PP
410.Vb 2
411\& % showtime showtime.pl
412\& 818284590
413.Ve
414.PP
415yielding the number of seconds that elapsed between January 1, 1970
416(the beginning of the Unix epoch), and the moment I began writing this
417sentence.
418.PP
419In this particular case we don't have to call \fIperl_run\fR, as we set
420the PL_exit_flag \s-1PERL_EXIT_DESTRUCT_END\s0 which executes \s-1END\s0 blocks in
421perl_destruct.
422.PP
423If you want to pass arguments to the Perl subroutine, you can add
424strings to the \f(CW\*(C`NULL\*(C'\fR\-terminated \f(CW\*(C`args\*(C'\fR list passed to
425\&\fIcall_argv\fR. For other data types, or to examine return values,
426you'll need to manipulate the Perl stack. That's demonstrated in
427\&\*(L"Fiddling with the Perl stack from your C program\*(R".
428.Sh "Evaluating a Perl statement from your C program"
429.IX Subsection "Evaluating a Perl statement from your C program"
430Perl provides two \s-1API\s0 functions to evaluate pieces of Perl code.
431These are \*(L"eval_sv\*(R" in perlapi and \*(L"eval_pv\*(R" in perlapi.
432.PP
433Arguably, these are the only routines you'll ever need to execute
434snippets of Perl code from within your C program. Your code can be as
435long as you wish; it can contain multiple statements; it can employ
436\&\*(L"use\*(R" in perlfunc, \*(L"require\*(R" in perlfunc, and \*(L"do\*(R" in perlfunc to
437include external Perl files.
438.PP
439\&\fIeval_pv\fR lets us evaluate individual Perl strings, and then
440extract variables for coercion into C types. The following program,
441\&\fIstring.c\fR, executes three Perl strings, extracting an \f(CW\*(C`int\*(C'\fR from
442the first, a \f(CW\*(C`float\*(C'\fR from the second, and a \f(CW\*(C`char *\*(C'\fR from the third.
443.PP
444.Vb 2
445\& #include <EXTERN.h>
446\& #include <perl.h>
447.Ve
448.PP
449.Vb 1
450\& static PerlInterpreter *my_perl;
451.Ve
452.PP
453.Vb 4
454\& main (int argc, char **argv, char **env)
455\& {
456\& STRLEN n_a;
457\& char *embedding[] = { "", "-e", "0" };
458.Ve
459.PP
460.Vb 2
461\& my_perl = perl_alloc();
462\& perl_construct( my_perl );
463.Ve
464.PP
465.Vb 3
466\& perl_parse(my_perl, NULL, 3, embedding, NULL);
467\& PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
468\& perl_run(my_perl);
469.Ve
470.PP
471.Vb 3
472\& /** Treat $a as an integer **/
473\& eval_pv("$a = 3; $a **= 2", TRUE);
474\& printf("a = %d\en", SvIV(get_sv("a", FALSE)));
475.Ve
476.PP
477.Vb 3
478\& /** Treat $a as a float **/
479\& eval_pv("$a = 3.14; $a **= 2", TRUE);
480\& printf("a = %f\en", SvNV(get_sv("a", FALSE)));
481.Ve
482.PP
483.Vb 3
484\& /** Treat $a as a string **/
485\& eval_pv("$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);", TRUE);
486\& printf("a = %s\en", SvPV(get_sv("a", FALSE), n_a));
487.Ve
488.PP
489.Vb 3
490\& perl_destruct(my_perl);
491\& perl_free(my_perl);
492\& }
493.Ve
494.PP
495All of those strange functions with \fIsv\fR in their names help convert Perl scalars to C types. They're described in perlguts and perlapi.
496.PP
497If you compile and run \fIstring.c\fR, you'll see the results of using
498\&\fI\fISvIV()\fI\fR to create an \f(CW\*(C`int\*(C'\fR, \fI\fISvNV()\fI\fR to create a \f(CW\*(C`float\*(C'\fR, and
499\&\fI\fISvPV()\fI\fR to create a string:
500.PP
501.Vb 3
502\& a = 9
503\& a = 9.859600
504\& a = Just Another Perl Hacker
505.Ve
506.PP
507In the example above, we've created a global variable to temporarily
508store the computed value of our eval'd expression. It is also
509possible and in most cases a better strategy to fetch the return value
510from \fI\fIeval_pv()\fI\fR instead. Example:
511.PP
512.Vb 5
513\& ...
514\& STRLEN n_a;
515\& SV *val = eval_pv("reverse 'rekcaH lreP rehtonA tsuJ'", TRUE);
516\& printf("%s\en", SvPV(val,n_a));
517\& ...
518.Ve
519.PP
520This way, we avoid namespace pollution by not creating global
521variables and we've simplified our code as well.
522.Sh "Performing Perl pattern matches and substitutions from your C program"
523.IX Subsection "Performing Perl pattern matches and substitutions from your C program"
524The \fI\fIeval_sv()\fI\fR function lets us evaluate strings of Perl code, so we can
525define some functions that use it to \*(L"specialize\*(R" in matches and
526substitutions: \fI\fImatch()\fI\fR, \fI\fIsubstitute()\fI\fR, and \fI\fImatches()\fI\fR.
527.PP
528.Vb 1
529\& I32 match(SV *string, char *pattern);
530.Ve
531.PP
532Given a string and a pattern (e.g., \f(CW\*(C`m/clasp/\*(C'\fR or \f(CW\*(C`/\eb\ew*\eb/\*(C'\fR, which
533in your C program might appear as \*(L"/\e\eb\e\ew*\e\eb/\*(R"), \fImatch()\fR
534returns 1 if the string matches the pattern and 0 otherwise.
535.PP
536.Vb 1
537\& int substitute(SV **string, char *pattern);
538.Ve
539.PP
540Given a pointer to an \f(CW\*(C`SV\*(C'\fR and an \f(CW\*(C`=~\*(C'\fR operation (e.g.,
541\&\f(CW\*(C`s/bob/robert/g\*(C'\fR or \f(CW\*(C`tr[A\-Z][a\-z]\*(C'\fR), \fIsubstitute()\fR modifies the string
542within the \f(CW\*(C`AV\*(C'\fR at according to the operation, returning the number of substitutions
543made.
544.PP
545.Vb 1
546\& int matches(SV *string, char *pattern, AV **matches);
547.Ve
548.PP
549Given an \f(CW\*(C`SV\*(C'\fR, a pattern, and a pointer to an empty \f(CW\*(C`AV\*(C'\fR,
550\&\fImatches()\fR evaluates \f(CW\*(C`$string =~ $pattern\*(C'\fR in a list context, and
551fills in \fImatches\fR with the array elements, returning the number of matches found.
552.PP
553Here's a sample program, \fImatch.c\fR, that uses all three (long lines have
554been wrapped here):
555.PP
556.Vb 2
557\& #include <EXTERN.h>
558\& #include <perl.h>
559.Ve
560.PP
561.Vb 9
562\& /** my_eval_sv(code, error_check)
563\& ** kinda like eval_sv(),
564\& ** but we pop the return value off the stack
565\& **/
566\& SV* my_eval_sv(SV *sv, I32 croak_on_error)
567\& {
568\& dSP;
569\& SV* retval;
570\& STRLEN n_a;
571.Ve
572.PP
573.Vb 2
574\& PUSHMARK(SP);
575\& eval_sv(sv, G_SCALAR);
576.Ve
577.PP
578.Vb 3
579\& SPAGAIN;
580\& retval = POPs;
581\& PUTBACK;
582.Ve
583.PP
584.Vb 2
585\& if (croak_on_error && SvTRUE(ERRSV))
586\& croak(SvPVx(ERRSV, n_a));
587.Ve
588.PP
589.Vb 2
590\& return retval;
591\& }
592.Ve
593.PP
594.Vb 6
595\& /** match(string, pattern)
596\& **
597\& ** Used for matches in a scalar context.
598\& **
599\& ** Returns 1 if the match was successful; 0 otherwise.
600\& **/
601.Ve
602.PP
603.Vb 4
604\& I32 match(SV *string, char *pattern)
605\& {
606\& SV *command = NEWSV(1099, 0), *retval;
607\& STRLEN n_a;
608.Ve
609.PP
610.Vb 2
611\& sv_setpvf(command, "my $string = '%s'; $string =~ %s",
612\& SvPV(string,n_a), pattern);
613.Ve
614.PP
615.Vb 2
616\& retval = my_eval_sv(command, TRUE);
617\& SvREFCNT_dec(command);
618.Ve
619.PP
620.Vb 2
621\& return SvIV(retval);
622\& }
623.Ve
624.PP
625.Vb 7
626\& /** substitute(string, pattern)
627\& **
628\& ** Used for =~ operations that modify their left-hand side (s/// and tr///)
629\& **
630\& ** Returns the number of successful matches, and
631\& ** modifies the input string if there were any.
632\& **/
633.Ve
634.PP
635.Vb 4
636\& I32 substitute(SV **string, char *pattern)
637\& {
638\& SV *command = NEWSV(1099, 0), *retval;
639\& STRLEN n_a;
640.Ve
641.PP
642.Vb 2
643\& sv_setpvf(command, "$string = '%s'; ($string =~ %s)",
644\& SvPV(*string,n_a), pattern);
645.Ve
646.PP
647.Vb 2
648\& retval = my_eval_sv(command, TRUE);
649\& SvREFCNT_dec(command);
650.Ve
651.PP
652.Vb 3
653\& *string = get_sv("string", FALSE);
654\& return SvIV(retval);
655\& }
656.Ve
657.PP
658.Vb 7
659\& /** matches(string, pattern, matches)
660\& **
661\& ** Used for matches in a list context.
662\& **
663\& ** Returns the number of matches,
664\& ** and fills in **matches with the matching substrings
665\& **/
666.Ve
667.PP
668.Vb 5
669\& I32 matches(SV *string, char *pattern, AV **match_list)
670\& {
671\& SV *command = NEWSV(1099, 0);
672\& I32 num_matches;
673\& STRLEN n_a;
674.Ve
675.PP
676.Vb 2
677\& sv_setpvf(command, "my $string = '%s'; @array = ($string =~ %s)",
678\& SvPV(string,n_a), pattern);
679.Ve
680.PP
681.Vb 2
682\& my_eval_sv(command, TRUE);
683\& SvREFCNT_dec(command);
684.Ve
685.PP
686.Vb 2
687\& *match_list = get_av("array", FALSE);
688\& num_matches = av_len(*match_list) + 1; /** assume $[ is 0 **/
689.Ve
690.PP
691.Vb 2
692\& return num_matches;
693\& }
694.Ve
695.PP
696.Vb 8
697\& main (int argc, char **argv, char **env)
698\& {
699\& PerlInterpreter *my_perl = perl_alloc();
700\& char *embedding[] = { "", "-e", "0" };
701\& AV *match_list;
702\& I32 num_matches, i;
703\& SV *text = NEWSV(1099,0);
704\& STRLEN n_a;
705.Ve
706.PP
707.Vb 3
708\& perl_construct(my_perl);
709\& perl_parse(my_perl, NULL, 3, embedding, NULL);
710\& PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
711.Ve
712.PP
713.Vb 1
714\& 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");
715.Ve
716.PP
717.Vb 4
718\& if (match(text, "m/quarter/")) /** Does text contain 'quarter'? **/
719\& printf("match: Text contains the word 'quarter'.\en\en");
720\& else
721\& printf("match: Text doesn't contain the word 'quarter'.\en\en");
722.Ve
723.PP
724.Vb 4
725\& if (match(text, "m/eighth/")) /** Does text contain 'eighth'? **/
726\& printf("match: Text contains the word 'eighth'.\en\en");
727\& else
728\& printf("match: Text doesn't contain the word 'eighth'.\en\en");
729.Ve
730.PP
731.Vb 3
732\& /** Match all occurrences of /wi../ **/
733\& num_matches = matches(text, "m/(wi..)/g", &match_list);
734\& printf("matches: m/(wi..)/g found %d matches...\en", num_matches);
735.Ve
736.PP
737.Vb 3
738\& for (i = 0; i < num_matches; i++)
739\& printf("match: %s\en", SvPV(*av_fetch(match_list, i, FALSE),n_a));
740\& printf("\en");
741.Ve
742.PP
743.Vb 7
744\& /** Remove all vowels from text **/
745\& num_matches = substitute(&text, "s/[aeiou]//gi");
746\& if (num_matches) {
747\& printf("substitute: s/[aeiou]//gi...%d substitutions made.\en",
748\& num_matches);
749\& printf("Now text is: %s\en\en", SvPV(text,n_a));
750\& }
751.Ve
752.PP
753.Vb 4
754\& /** Attempt a substitution **/
755\& if (!substitute(&text, "s/Perl/C/")) {
756\& printf("substitute: s/Perl/C...No substitution made.\en\en");
757\& }
758.Ve
759.PP
760.Vb 5
761\& SvREFCNT_dec(text);
762\& PL_perl_destruct_level = 1;
763\& perl_destruct(my_perl);
764\& perl_free(my_perl);
765\& }
766.Ve
767.PP
768which produces the output (again, long lines have been wrapped here)
769.PP
770.Vb 1
771\& match: Text contains the word 'quarter'.
772.Ve
773.PP
774.Vb 1
775\& match: Text doesn't contain the word 'eighth'.
776.Ve
777.PP
778.Vb 3
779\& matches: m/(wi..)/g found 2 matches...
780\& match: will
781\& match: with
782.Ve
783.PP
784.Vb 6
785\& substitute: s/[aeiou]//gi...139 substitutions made.
786\& Now text is: Whn h s t cnvnnc str nd th bll cms t sm mnt lk 76 cnts,
787\& Mynrd s wr tht thr s smthng h *shld* d, smthng tht wll nbl hm t gt bck
788\& qrtr, bt h hs n d *wht*. H fmbls thrgh hs rd sqzy chngprs nd gvs th by
789\& thr xtr pnns wth hs dllr, hpng tht h mght lck nt th crrct mnt. Th by gvs
790\& hm bck tw f hs wn pnns nd thn th bg shny qrtr tht s hs prz. -RCHH
791.Ve
792.PP
793.Vb 1
794\& substitute: s/Perl/C...No substitution made.
795.Ve
796.Sh "Fiddling with the Perl stack from your C program"
797.IX Subsection "Fiddling with the Perl stack from your C program"
798When trying to explain stacks, most computer science textbooks mumble
799something about spring-loaded columns of cafeteria plates: the last
800thing you pushed on the stack is the first thing you pop off. That'll
801do for our purposes: your C program will push some arguments onto \*(L"the Perl
802stack\*(R", shut its eyes while some magic happens, and then pop the
803results\*(--the return value of your Perl subroutine\*(--off the stack.
804.PP
805First you'll need to know how to convert between C types and Perl
806types, with \fInewSViv()\fR and \fIsv_setnv()\fR and \fInewAV()\fR and all their
807friends. They're described in perlguts and perlapi.
808.PP
809Then you'll need to know how to manipulate the Perl stack. That's
810described in perlcall.
811.PP
812Once you've understood those, embedding Perl in C is easy.
813.PP
814Because C has no builtin function for integer exponentiation, let's
815make Perl's ** operator available to it (this is less useful than it
816sounds, because Perl implements ** with C's \fI\fIpow()\fI\fR function). First
817I'll create a stub exponentiation function in \fIpower.pl\fR:
818.PP
819.Vb 4
820\& sub expo {
821\& my ($a, $b) = @_;
822\& return $a ** $b;
823\& }
824.Ve
825.PP
826Now I'll create a C program, \fIpower.c\fR, with a function
827\&\fI\fIPerlPower()\fI\fR that contains all the perlguts necessary to push the
828two arguments into \fI\fIexpo()\fI\fR and to pop the return value out. Take a
829deep breath...
830.PP
831.Vb 2
832\& #include <EXTERN.h>
833\& #include <perl.h>
834.Ve
835.PP
836.Vb 1
837\& static PerlInterpreter *my_perl;
838.Ve
839.PP
840.Vb 18
841\& static void
842\& PerlPower(int a, int b)
843\& {
844\& dSP; /* initialize stack pointer */
845\& ENTER; /* everything created after here */
846\& SAVETMPS; /* ...is a temporary variable. */
847\& PUSHMARK(SP); /* remember the stack pointer */
848\& XPUSHs(sv_2mortal(newSViv(a))); /* push the base onto the stack */
849\& XPUSHs(sv_2mortal(newSViv(b))); /* push the exponent onto stack */
850\& PUTBACK; /* make local stack pointer global */
851\& call_pv("expo", G_SCALAR); /* call the function */
852\& SPAGAIN; /* refresh stack pointer */
853\& /* pop the return value from stack */
854\& printf ("%d to the %dth power is %d.\en", a, b, POPi);
855\& PUTBACK;
856\& FREETMPS; /* free that return value */
857\& LEAVE; /* ...and the XPUSHed "mortal" args.*/
858\& }
859.Ve
860.PP
861.Vb 3
862\& int main (int argc, char **argv, char **env)
863\& {
864\& char *my_argv[] = { "", "power.pl" };
865.Ve
866.PP
867.Vb 2
868\& my_perl = perl_alloc();
869\& perl_construct( my_perl );
870.Ve
871.PP
872.Vb 3
873\& perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL);
874\& PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
875\& perl_run(my_perl);
876.Ve
877.PP
878.Vb 1
879\& PerlPower(3, 4); /*** Compute 3 ** 4 ***/
880.Ve
881.PP
882.Vb 3
883\& perl_destruct(my_perl);
884\& perl_free(my_perl);
885\& }
886.Ve
887.PP
888Compile and run:
889.PP
890.Vb 1
891\& % cc -o power power.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
892.Ve
893.PP
894.Vb 2
895\& % power
896\& 3 to the 4th power is 81.
897.Ve
898.Sh "Maintaining a persistent interpreter"
899.IX Subsection "Maintaining a persistent interpreter"
900When developing interactive and/or potentially long-running
901applications, it's a good idea to maintain a persistent interpreter
902rather than allocating and constructing a new interpreter multiple
903times. The major reason is speed: since Perl will only be loaded into
904memory once.
905.PP
906However, you have to be more cautious with namespace and variable
907scoping when using a persistent interpreter. In previous examples
908we've been using global variables in the default package \f(CW\*(C`main\*(C'\fR. We
909knew exactly what code would be run, and assumed we could avoid
910variable collisions and outrageous symbol table growth.
911.PP
912Let's say your application is a server that will occasionally run Perl
913code from some arbitrary file. Your server has no way of knowing what
914code it's going to run. Very dangerous.
915.PP
916If the file is pulled in by \f(CW\*(C`perl_parse()\*(C'\fR, compiled into a newly
917constructed interpreter, and subsequently cleaned out with
918\&\f(CW\*(C`perl_destruct()\*(C'\fR afterwards, you're shielded from most namespace
919troubles.
920.PP
921One way to avoid namespace collisions in this scenario is to translate
922the filename into a guaranteed-unique package name, and then compile
923the code into that package using \*(L"eval\*(R" in perlfunc. In the example
924below, each file will only be compiled once. Or, the application
925might choose to clean out the symbol table associated with the file
926after it's no longer needed. Using \*(L"call_argv\*(R" in perlapi, We'll
927call the subroutine \f(CW\*(C`Embed::Persistent::eval_file\*(C'\fR which lives in the
928file \f(CW\*(C`persistent.pl\*(C'\fR and pass the filename and boolean cleanup/cache
929flag as arguments.
930.PP
931Note that the process will continue to grow for each file that it
932uses. In addition, there might be \f(CW\*(C`AUTOLOAD\*(C'\fRed subroutines and other
933conditions that cause Perl's symbol table to grow. You might want to
934add some logic that keeps track of the process size, or restarts
935itself after a certain number of requests, to ensure that memory
936consumption is minimized. You'll also want to scope your variables
937with \*(L"my\*(R" in perlfunc whenever possible.
938.PP
939.Vb 2
940\& package Embed::Persistent;
941\& #persistent.pl
942.Ve
943.PP
944.Vb 3
945\& use strict;
946\& our %Cache;
947\& use Symbol qw(delete_package);
948.Ve
949.PP
950.Vb 5
951\& sub valid_package_name {
952\& my($string) = @_;
953\& $string =~ s/([^A-Za-z0-9\e/])/sprintf("_%2x",unpack("C",$1))/eg;
954\& # second pass only for words starting with a digit
955\& $string =~ s|/(\ed)|sprintf("/_%2x",unpack("C",$1))|eg;
956.Ve
957.PP
958.Vb 4
959\& # Dress it up as a real package name
960\& $string =~ s|/|::|g;
961\& return "Embed" . $string;
962\& }
963.Ve
964.PP
965.Vb 18
966\& sub eval_file {
967\& my($filename, $delete) = @_;
968\& my $package = valid_package_name($filename);
969\& my $mtime = -M $filename;
970\& if(defined $Cache{$package}{mtime}
971\& &&
972\& $Cache{$package}{mtime} <= $mtime)
973\& {
974\& # we have compiled this subroutine already,
975\& # it has not been updated on disk, nothing left to do
976\& print STDERR "already compiled $package->handler\en";
977\& }
978\& else {
979\& local *FH;
980\& open FH, $filename or die "open '$filename' $!";
981\& local($/) = undef;
982\& my $sub = <FH>;
983\& close FH;
984.Ve
985.PP
986.Vb 8
987\& #wrap the code into a subroutine inside our unique package
988\& my $eval = qq{package $package; sub handler { $sub; }};
989\& {
990\& # hide our variables within this block
991\& my($filename,$mtime,$package,$sub);
992\& eval $eval;
993\& }
994\& die $@ if $@;
995.Ve
996.PP
997.Vb 3
998\& #cache it unless we're cleaning out each time
999\& $Cache{$package}{mtime} = $mtime unless $delete;
1000\& }
1001.Ve
1002.PP
1003.Vb 2
1004\& eval {$package->handler;};
1005\& die $@ if $@;
1006.Ve
1007.PP
1008.Vb 1
1009\& delete_package($package) if $delete;
1010.Ve
1011.PP
1012.Vb 3
1013\& #take a look if you want
1014\& #print Devel::Symdump->rnew($package)->as_string, $/;
1015\& }
1016.Ve
1017.PP
1018.Vb 1
1019\& 1;
1020.Ve
1021.PP
1022.Vb 1
1023\& __END__
1024.Ve
1025.PP
1026.Vb 3
1027\& /* persistent.c */
1028\& #include <EXTERN.h>
1029\& #include <perl.h>
1030.Ve
1031.PP
1032.Vb 4
1033\& /* 1 = clean out filename's symbol table after each request, 0 = don't */
1034\& #ifndef DO_CLEAN
1035\& #define DO_CLEAN 0
1036\& #endif
1037.Ve
1038.PP
1039.Vb 1
1040\& static PerlInterpreter *perl = NULL;
1041.Ve
1042.PP
1043.Vb 8
1044\& int
1045\& main(int argc, char **argv, char **env)
1046\& {
1047\& char *embedding[] = { "", "persistent.pl" };
1048\& char *args[] = { "", DO_CLEAN, NULL };
1049\& char filename [1024];
1050\& int exitstatus = 0;
1051\& STRLEN n_a;
1052.Ve
1053.PP
1054.Vb 5
1055\& if((perl = perl_alloc()) == NULL) {
1056\& fprintf(stderr, "no memory!");
1057\& exit(1);
1058\& }
1059\& perl_construct(perl);
1060.Ve
1061.PP
1062.Vb 4
1063\& exitstatus = perl_parse(perl, NULL, 2, embedding, NULL);
1064\& PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1065\& if(!exitstatus) {
1066\& exitstatus = perl_run(perl);
1067.Ve
1068.PP
1069.Vb 1
1070\& while(printf("Enter file name: ") && gets(filename)) {
1071.Ve
1072.PP
1073.Vb 4
1074\& /* call the subroutine, passing it the filename as an argument */
1075\& args[0] = filename;
1076\& call_argv("Embed::Persistent::eval_file",
1077\& G_DISCARD | G_EVAL, args);
1078.Ve
1079.PP
1080.Vb 5
1081\& /* check $@ */
1082\& if(SvTRUE(ERRSV))
1083\& fprintf(stderr, "eval error: %s\en", SvPV(ERRSV,n_a));
1084\& }
1085\& }
1086.Ve
1087.PP
1088.Vb 5
1089\& PL_perl_destruct_level = 0;
1090\& perl_destruct(perl);
1091\& perl_free(perl);
1092\& exit(exitstatus);
1093\& }
1094.Ve
1095.PP
1096Now compile:
1097.PP
1098.Vb 1
1099\& % cc -o persistent persistent.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
1100.Ve
1101.PP
1102Here's an example script file:
1103.PP
1104.Vb 3
1105\& #test.pl
1106\& my $string = "hello";
1107\& foo($string);
1108.Ve
1109.PP
1110.Vb 3
1111\& sub foo {
1112\& print "foo says: @_\en";
1113\& }
1114.Ve
1115.PP
1116Now run:
1117.PP
1118.Vb 7
1119\& % persistent
1120\& Enter file name: test.pl
1121\& foo says: hello
1122\& Enter file name: test.pl
1123\& already compiled Embed::test_2epl->handler
1124\& foo says: hello
1125\& Enter file name: ^C
1126.Ve
1127.Sh "Execution of \s-1END\s0 blocks"
1128.IX Subsection "Execution of END blocks"
1129Traditionally \s-1END\s0 blocks have been executed at the end of the perl_run.
1130This causes problems for applications that never call perl_run. Since
1131perl 5.7.2 you can specify \f(CW\*(C`PL_exit_flags |= PERL_EXIT_DESTRUCT_END\*(C'\fR
1132to get the new behaviour. This also enables the running of \s-1END\s0 blocks if
1133the perl_prase fails and \f(CW\*(C`perl_destruct\*(C'\fR will return the exit value.
1134.Sh "Maintaining multiple interpreter instances"
1135.IX Subsection "Maintaining multiple interpreter instances"
1136Some rare applications will need to create more than one interpreter
1137during a session. Such an application might sporadically decide to
1138release any resources associated with the interpreter.
1139.PP
1140The program must take care to ensure that this takes place \fIbefore\fR
1141the next interpreter is constructed. By default, when perl is not
1142built with any special options, the global variable
1143\&\f(CW\*(C`PL_perl_destruct_level\*(C'\fR is set to \f(CW0\fR, since extra cleaning isn't
1144usually needed when a program only ever creates a single interpreter
1145in its entire lifetime.
1146.PP
1147Setting \f(CW\*(C`PL_perl_destruct_level\*(C'\fR to \f(CW1\fR makes everything squeaky clean:
1148.PP
1149.Vb 1
1150\& PL_perl_destruct_level = 1;
1151.Ve
1152.PP
1153.Vb 11
1154\& while(1) {
1155\& ...
1156\& /* reset global variables here with PL_perl_destruct_level = 1 */
1157\& perl_construct(my_perl);
1158\& ...
1159\& /* clean and reset _everything_ during perl_destruct */
1160\& perl_destruct(my_perl);
1161\& perl_free(my_perl);
1162\& ...
1163\& /* let's go do it again! */
1164\& }
1165.Ve
1166.PP
1167When \fI\fIperl_destruct()\fI\fR is called, the interpreter's syntax parse tree
1168and symbol tables are cleaned up, and global variables are reset.
1169.PP
1170Now suppose we have more than one interpreter instance running at the
1171same time. This is feasible, but only if you used the Configure option
1172\&\f(CW\*(C`\-Dusemultiplicity\*(C'\fR or the options \f(CW\*(C`\-Dusethreads \-Duseithreads\*(C'\fR when
1173building Perl. By default, enabling one of these Configure options
1174sets the per-interpreter global variable \f(CW\*(C`PL_perl_destruct_level\*(C'\fR to
1175\&\f(CW1\fR, so that thorough cleaning is automatic.
1176.PP
1177Using \f(CW\*(C`\-Dusethreads \-Duseithreads\*(C'\fR rather than \f(CW\*(C`\-Dusemultiplicity\*(C'\fR
1178is more appropriate if you intend to run multiple interpreters
1179concurrently in different threads, because it enables support for
1180linking in the thread libraries of your system with the interpreter.
1181.PP
1182Let's give it a try:
1183.PP
1184.Vb 2
1185\& #include <EXTERN.h>
1186\& #include <perl.h>
1187.Ve
1188.PP
1189.Vb 2
1190\& /* we're going to embed two interpreters */
1191\& /* we're going to embed two interpreters */
1192.Ve
1193.PP
1194.Vb 1
1195\& #define SAY_HELLO "-e", "print qq(Hi, I'm $^X\en)"
1196.Ve
1197.PP
1198.Vb 7
1199\& int main(int argc, char **argv, char **env)
1200\& {
1201\& PerlInterpreter
1202\& *one_perl = perl_alloc(),
1203\& *two_perl = perl_alloc();
1204\& char *one_args[] = { "one_perl", SAY_HELLO };
1205\& char *two_args[] = { "two_perl", SAY_HELLO };
1206.Ve
1207.PP
1208.Vb 4
1209\& PERL_SET_CONTEXT(one_perl);
1210\& perl_construct(one_perl);
1211\& PERL_SET_CONTEXT(two_perl);
1212\& perl_construct(two_perl);
1213.Ve
1214.PP
1215.Vb 4
1216\& PERL_SET_CONTEXT(one_perl);
1217\& perl_parse(one_perl, NULL, 3, one_args, (char **)NULL);
1218\& PERL_SET_CONTEXT(two_perl);
1219\& perl_parse(two_perl, NULL, 3, two_args, (char **)NULL);
1220.Ve
1221.PP
1222.Vb 4
1223\& PERL_SET_CONTEXT(one_perl);
1224\& perl_run(one_perl);
1225\& PERL_SET_CONTEXT(two_perl);
1226\& perl_run(two_perl);
1227.Ve
1228.PP
1229.Vb 4
1230\& PERL_SET_CONTEXT(one_perl);
1231\& perl_destruct(one_perl);
1232\& PERL_SET_CONTEXT(two_perl);
1233\& perl_destruct(two_perl);
1234.Ve
1235.PP
1236.Vb 5
1237\& PERL_SET_CONTEXT(one_perl);
1238\& perl_free(one_perl);
1239\& PERL_SET_CONTEXT(two_perl);
1240\& perl_free(two_perl);
1241\& }
1242.Ve
1243.PP
1244Note the calls to \s-1\fIPERL_SET_CONTEXT\s0()\fR. These are necessary to initialize
1245the global state that tracks which interpreter is the \*(L"current\*(R" one on
1246the particular process or thread that may be running it. It should
1247always be used if you have more than one interpreter and are making
1248perl \s-1API\s0 calls on both interpreters in an interleaved fashion.
1249.PP
1250\&\s-1PERL_SET_CONTEXT\s0(interp) should also be called whenever \f(CW\*(C`interp\*(C'\fR is
1251used by a thread that did not create it (using either \fIperl_alloc()\fR, or
1252the more esoteric \fIperl_clone()\fR).
1253.PP
1254Compile as usual:
1255.PP
1256.Vb 1
1257\& % cc -o multiplicity multiplicity.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
1258.Ve
1259.PP
1260Run it, Run it:
1261.PP
1262.Vb 3
1263\& % multiplicity
1264\& Hi, I'm one_perl
1265\& Hi, I'm two_perl
1266.Ve
1267.Sh "Using Perl modules, which themselves use C libraries, from your C program"
1268.IX Subsection "Using Perl modules, which themselves use C libraries, from your C program"
1269If you've played with the examples above and tried to embed a script
1270that \fI\fIuse()\fI\fRs a Perl module (such as \fISocket\fR) which itself uses a C or \*(C+ library,
1271this probably happened:
1272.PP
1273.Vb 3
1274\& Can't load module Socket, dynamic loading not available in this perl.
1275\& (You may need to build a new perl executable which either supports
1276\& dynamic loading or has the Socket module statically linked into it.)
1277.Ve
1278.PP
1279What's wrong?
1280.PP
1281Your interpreter doesn't know how to communicate with these extensions
1282on its own. A little glue will help. Up until now you've been
1283calling \fI\fIperl_parse()\fI\fR, handing it \s-1NULL\s0 for the second argument:
1284.PP
1285.Vb 1
1286\& perl_parse(my_perl, NULL, argc, my_argv, NULL);
1287.Ve
1288.PP
1289That's where the glue code can be inserted to create the initial contact between
1290Perl and linked C/\*(C+ routines. Let's take a look some pieces of \fIperlmain.c\fR
1291to see how Perl does this:
1292.PP
1293.Vb 1
1294\& static void xs_init (pTHX);
1295.Ve
1296.PP
1297.Vb 2
1298\& EXTERN_C void boot_DynaLoader (pTHX_ CV* cv);
1299\& EXTERN_C void boot_Socket (pTHX_ CV* cv);
1300.Ve
1301.PP
1302.Vb 8
1303\& EXTERN_C void
1304\& xs_init(pTHX)
1305\& {
1306\& char *file = __FILE__;
1307\& /* DynaLoader is a special case */
1308\& newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
1309\& newXS("Socket::bootstrap", boot_Socket, file);
1310\& }
1311.Ve
1312.PP
1313Simply put: for each extension linked with your Perl executable
1314(determined during its initial configuration on your
1315computer or when adding a new extension),
1316a Perl subroutine is created to incorporate the extension's
1317routines. Normally, that subroutine is named
1318\&\fI\fIModule::bootstrap()\fI\fR and is invoked when you say \fIuse Module\fR. In
1319turn, this hooks into an \s-1XSUB\s0, \fIboot_Module\fR, which creates a Perl
1320counterpart for each of the extension's XSUBs. Don't worry about this
1321part; leave that to the \fIxsubpp\fR and extension authors. If your
1322extension is dynamically loaded, DynaLoader creates \fI\fIModule::bootstrap()\fI\fR
1323for you on the fly. In fact, if you have a working DynaLoader then there
1324is rarely any need to link in any other extensions statically.
1325.PP
1326Once you have this code, slap it into the second argument of \fI\fIperl_parse()\fI\fR:
1327.PP
1328.Vb 1
1329\& perl_parse(my_perl, xs_init, argc, my_argv, NULL);
1330.Ve
1331.PP
1332Then compile:
1333.PP
1334.Vb 1
1335\& % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
1336.Ve
1337.PP
1338.Vb 3
1339\& % interp
1340\& use Socket;
1341\& use SomeDynamicallyLoadedModule;
1342.Ve
1343.PP
1344.Vb 1
1345\& print "Now I can use extensions!\en"'
1346.Ve
1347.PP
1348\&\fBExtUtils::Embed\fR can also automate writing the \fIxs_init\fR glue code.
1349.PP
1350.Vb 4
1351\& % perl -MExtUtils::Embed -e xsinit -- -o perlxsi.c
1352\& % cc -c perlxsi.c `perl -MExtUtils::Embed -e ccopts`
1353\& % cc -c interp.c `perl -MExtUtils::Embed -e ccopts`
1354\& % cc -o interp perlxsi.o interp.o `perl -MExtUtils::Embed -e ldopts`
1355.Ve
1356.PP
1357Consult perlxs, perlguts, and perlapi for more details.
1358.SH "Embedding Perl under Win32"
1359.IX Header "Embedding Perl under Win32"
1360In general, all of the source code shown here should work unmodified under
1361Windows.
1362.PP
1363However, there are some caveats about the command-line examples shown.
1364For starters, backticks won't work under the Win32 native command shell.
1365The ExtUtils::Embed kit on \s-1CPAN\s0 ships with a script called
1366\&\fBgenmake\fR, which generates a simple makefile to build a program from
1367a single C source file. It can be used like this:
1368.PP
1369.Vb 3
1370\& C:\eExtUtils-Embed\eeg> perl genmake interp.c
1371\& C:\eExtUtils-Embed\eeg> nmake
1372\& C:\eExtUtils-Embed\eeg> interp -e "print qq{I'm embedded in Win32!\en}"
1373.Ve
1374.PP
1375You may wish to use a more robust environment such as the Microsoft
1376Developer Studio. In this case, run this to generate perlxsi.c:
1377.PP
1378.Vb 1
1379\& perl -MExtUtils::Embed -e xsinit
1380.Ve
1381.PP
1382Create a new project and Insert \-> Files into Project: perlxsi.c,
1383perl.lib, and your own source files, e.g. interp.c. Typically you'll
1384find perl.lib in \fBC:\eperl\elib\eCORE\fR, if not, you should see the
1385\&\fB\s-1CORE\s0\fR directory relative to \f(CW\*(C`perl \-V:archlib\*(C'\fR. The studio will
1386also need this path so it knows where to find Perl include files.
1387This path can be added via the Tools \-> Options \-> Directories menu.
1388Finally, select Build \-> Build interp.exe and you're ready to go.
1389.SH "MORAL"
1390.IX Header "MORAL"
1391You can sometimes \fIwrite faster code\fR in C, but
1392you can always \fIwrite code faster\fR in Perl. Because you can use
1393each from the other, combine them as you wish.
1394.SH "AUTHOR"
1395.IX Header "AUTHOR"
1396Jon Orwant <\fIorwant@tpj.com\fR> and Doug MacEachern
1397<\fIdougm@osf.org\fR>, with small contributions from Tim Bunce, Tom
1398Christiansen, Guy Decoux, Hallvard Furuseth, Dov Grobgeld, and Ilya
1399Zakharevich.
1400.PP
1401Doug MacEachern has an article on embedding in Volume 1, Issue 4 of
1402The Perl Journal ( http://www.tpj.com/ ). Doug is also the developer of the
1403most widely-used Perl embedding: the mod_perl system
1404(perl.apache.org), which embeds Perl in the Apache web server.
1405Oracle, Binary Evolution, ActiveState, and Ben Sugars's nsapi_perl
1406have used this model for Oracle, Netscape and Internet Information
1407Server Perl plugins.
1408.PP
1409July 22, 1998
1410.SH "COPYRIGHT"
1411.IX Header "COPYRIGHT"
1412Copyright (C) 1995, 1996, 1997, 1998 Doug MacEachern and Jon Orwant. All
1413Rights Reserved.
1414.PP
1415Permission is granted to make and distribute verbatim copies of this
1416documentation provided the copyright notice and this permission notice are
1417preserved on all copies.
1418.PP
1419Permission is granted to copy and distribute modified versions of this
1420documentation under the conditions for verbatim copying, provided also
1421that they are marked clearly as modified versions, that the authors'
1422names and title are unchanged (though subtitles and additional
1423authors' names may be added), and that the entire resulting derived
1424work is distributed under the terms of a permission notice identical
1425to this one.
1426.PP
1427Permission is granted to copy and distribute translations of this
1428documentation into another language, under the above conditions for
1429modified versions.