Debian Codegraph @

upstream/opensuse-tumbleweed/man1/perlembed.1

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