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