source: trunk/essentials/dev-lang/perl/pod/perlembed.pod@ 3310

Last change on this file since 3310 was 3181, checked in by bird, 19 years ago

perl 5.8.8

File size: 36.1 KB
Line 
1=head1 NAME
2
3perlembed - how to embed perl in your C program
4
5=head1 DESCRIPTION
6
7=head2 PREAMBLE
8
9Do you want to:
10
11=over 5
12
13=item B<Use C from Perl?>
14
15Read L<perlxstut>, L<perlxs>, L<h2xs>, L<perlguts>, and L<perlapi>.
16
17=item B<Use a Unix program from Perl?>
18
19Read about back-quotes and about C<system> and C<exec> in L<perlfunc>.
20
21=item B<Use Perl from Perl?>
22
23Read about L<perlfunc/do> and L<perlfunc/eval> and L<perlfunc/require>
24and L<perlfunc/use>.
25
26=item B<Use C from C?>
27
28Rethink your design.
29
30=item B<Use Perl from C?>
31
32Read on...
33
34=back
35
36=head2 ROADMAP
37
38=over 5
39
40=item *
41
42Compiling your C program
43
44=item *
45
46Adding a Perl interpreter to your C program
47
48=item *
49
50Calling a Perl subroutine from your C program
51
52=item *
53
54Evaluating a Perl statement from your C program
55
56=item *
57
58Performing Perl pattern matches and substitutions from your C program
59
60=item *
61
62Fiddling with the Perl stack from your C program
63
64=item *
65
66Maintaining a persistent interpreter
67
68=item *
69
70Maintaining multiple interpreter instances
71
72=item *
73
74Using Perl modules, which themselves use C libraries, from your C program
75
76=item *
77
78Embedding Perl under Win32
79
80=back
81
82=head2 Compiling your C program
83
84If you have trouble compiling the scripts in this documentation,
85you're not alone. The cardinal rule: COMPILE THE PROGRAMS IN EXACTLY
86THE SAME WAY THAT YOUR PERL WAS COMPILED. (Sorry for yelling.)
87
88Also, every C program that uses Perl must link in the I<perl library>.
89What's that, you ask? Perl is itself written in C; the perl library
90is the collection of compiled C programs that were used to create your
91perl executable (I</usr/bin/perl> or equivalent). (Corollary: you
92can't use Perl from your C program unless Perl has been compiled on
93your machine, or installed properly--that's why you shouldn't blithely
94copy Perl executables from machine to machine without also copying the
95I<lib> directory.)
96
97When you use Perl from C, your C program will--usually--allocate,
98"run", and deallocate a I<PerlInterpreter> object, which is defined by
99the perl library.
100
101If your copy of Perl is recent enough to contain this documentation
102(version 5.002 or later), then the perl library (and I<EXTERN.h> and
103I<perl.h>, which you'll also need) will reside in a directory
104that looks like this:
105
106 /usr/local/lib/perl5/your_architecture_here/CORE
107
108or perhaps just
109
110 /usr/local/lib/perl5/CORE
111
112or maybe something like
113
114 /usr/opt/perl5/CORE
115
116Execute this statement for a hint about where to find CORE:
117
118 perl -MConfig -e 'print $Config{archlib}'
119
120Here's how you'd compile the example in the next section,
121L<Adding a Perl interpreter to your C program>, on my Linux box:
122
123 % gcc -O2 -Dbool=char -DHAS_BOOL -I/usr/local/include
124 -I/usr/local/lib/perl5/i586-linux/5.003/CORE
125 -L/usr/local/lib/perl5/i586-linux/5.003/CORE
126 -o interp interp.c -lperl -lm
127
128(That's all one line.) On my DEC Alpha running old 5.003_05, the
129incantation is a bit different:
130
131 % cc -O2 -Olimit 2900 -DSTANDARD_C -I/usr/local/include
132 -I/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE
133 -L/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE -L/usr/local/lib
134 -D__LANGUAGE_C__ -D_NO_PROTO -o interp interp.c -lperl -lm
135
136How can you figure out what to add? Assuming your Perl is post-5.001,
137execute a C<perl -V> command and pay special attention to the "cc" and
138"ccflags" information.
139
140You'll have to choose the appropriate compiler (I<cc>, I<gcc>, et al.) for
141your machine: C<perl -MConfig -e 'print $Config{cc}'> will tell you what
142to use.
143
144You'll also have to choose the appropriate library directory
145(I</usr/local/lib/...>) for your machine. If your compiler complains
146that certain functions are undefined, or that it can't locate
147I<-lperl>, then you need to change the path following the C<-L>. If it
148complains that it can't find I<EXTERN.h> and I<perl.h>, you need to
149change the path following the C<-I>.
150
151You may have to add extra libraries as well. Which ones?
152Perhaps those printed by
153
154 perl -MConfig -e 'print $Config{libs}'
155
156Provided your perl binary was properly configured and installed the
157B<ExtUtils::Embed> module will determine all of this information for
158you:
159
160 % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
161
162If the B<ExtUtils::Embed> module isn't part of your Perl distribution,
163you can retrieve it from
164http://www.perl.com/perl/CPAN/modules/by-module/ExtUtils/
165(If this documentation came from your Perl distribution, then you're
166running 5.004 or better and you already have it.)
167
168The B<ExtUtils::Embed> kit on CPAN also contains all source code for
169the examples in this document, tests, additional examples and other
170information you may find useful.
171
172=head2 Adding a Perl interpreter to your C program
173
174In a sense, perl (the C program) is a good example of embedding Perl
175(the language), so I'll demonstrate embedding with I<miniperlmain.c>,
176included in the source distribution. Here's a bastardized, nonportable
177version of I<miniperlmain.c> containing the essentials of embedding:
178
179 #include <EXTERN.h> /* from the Perl distribution */
180 #include <perl.h> /* from the Perl distribution */
181
182 static PerlInterpreter *my_perl; /*** The Perl interpreter ***/
183
184 int main(int argc, char **argv, char **env)
185 {
186 PERL_SYS_INIT3(&argc,&argv,&env);
187 my_perl = perl_alloc();
188 perl_construct(my_perl);
189 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
190 perl_parse(my_perl, NULL, argc, argv, (char **)NULL);
191 perl_run(my_perl);
192 perl_destruct(my_perl);
193 perl_free(my_perl);
194 PERL_SYS_TERM();
195 }
196
197Notice that we don't use the C<env> pointer. Normally handed to
198C<perl_parse> as its final argument, C<env> here is replaced by
199C<NULL>, which means that the current environment will be used. The macros
200PERL_SYS_INIT3() and PERL_SYS_TERM() provide system-specific tune up
201of the C runtime environment necessary to run Perl interpreters; since
202PERL_SYS_INIT3() may change C<env>, it may be more appropriate to provide
203C<env> as an argument to perl_parse().
204
205Now compile this program (I'll call it I<interp.c>) into an executable:
206
207 % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
208
209After a successful compilation, you'll be able to use I<interp> just
210like perl itself:
211
212 % interp
213 print "Pretty Good Perl \n";
214 print "10890 - 9801 is ", 10890 - 9801;
215 <CTRL-D>
216 Pretty Good Perl
217 10890 - 9801 is 1089
218
219or
220
221 % interp -e 'printf("%x", 3735928559)'
222 deadbeef
223
224You can also read and execute Perl statements from a file while in the
225midst of your C program, by placing the filename in I<argv[1]> before
226calling I<perl_run>.
227
228=head2 Calling a Perl subroutine from your C program
229
230To call individual Perl subroutines, you can use any of the B<call_*>
231functions documented in L<perlcall>.
232In this example we'll use C<call_argv>.
233
234That's shown below, in a program I'll call I<showtime.c>.
235
236 #include <EXTERN.h>
237 #include <perl.h>
238
239 static PerlInterpreter *my_perl;
240
241 int main(int argc, char **argv, char **env)
242 {
243 char *args[] = { NULL };
244 PERL_SYS_INIT3(&argc,&argv,&env);
245 my_perl = perl_alloc();
246 perl_construct(my_perl);
247
248 perl_parse(my_perl, NULL, argc, argv, NULL);
249 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
250
251 /*** skipping perl_run() ***/
252
253 call_argv("showtime", G_DISCARD | G_NOARGS, args);
254
255 perl_destruct(my_perl);
256 perl_free(my_perl);
257 PERL_SYS_TERM();
258 }
259
260where I<showtime> is a Perl subroutine that takes no arguments (that's the
261I<G_NOARGS>) and for which I'll ignore the return value (that's the
262I<G_DISCARD>). Those flags, and others, are discussed in L<perlcall>.
263
264I'll define the I<showtime> subroutine in a file called I<showtime.pl>:
265
266 print "I shan't be printed.";
267
268 sub showtime {
269 print time;
270 }
271
272Simple enough. Now compile and run:
273
274 % cc -o showtime showtime.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
275
276 % showtime showtime.pl
277 818284590
278
279yielding the number of seconds that elapsed between January 1, 1970
280(the beginning of the Unix epoch), and the moment I began writing this
281sentence.
282
283In this particular case we don't have to call I<perl_run>, as we set
284the PL_exit_flag PERL_EXIT_DESTRUCT_END which executes END blocks in
285perl_destruct.
286
287If you want to pass arguments to the Perl subroutine, you can add
288strings to the C<NULL>-terminated C<args> list passed to
289I<call_argv>. For other data types, or to examine return values,
290you'll need to manipulate the Perl stack. That's demonstrated in
291L<Fiddling with the Perl stack from your C program>.
292
293=head2 Evaluating a Perl statement from your C program
294
295Perl provides two API functions to evaluate pieces of Perl code.
296These are L<perlapi/eval_sv> and L<perlapi/eval_pv>.
297
298Arguably, these are the only routines you'll ever need to execute
299snippets of Perl code from within your C program. Your code can be as
300long as you wish; it can contain multiple statements; it can employ
301L<perlfunc/use>, L<perlfunc/require>, and L<perlfunc/do> to
302include external Perl files.
303
304I<eval_pv> lets us evaluate individual Perl strings, and then
305extract variables for coercion into C types. The following program,
306I<string.c>, executes three Perl strings, extracting an C<int> from
307the first, a C<float> from the second, and a C<char *> from the third.
308
309 #include <EXTERN.h>
310 #include <perl.h>
311
312 static PerlInterpreter *my_perl;
313
314 main (int argc, char **argv, char **env)
315 {
316 STRLEN n_a;
317 char *embedding[] = { "", "-e", "0" };
318
319 PERL_SYS_INIT3(&argc,&argv,&env);
320 my_perl = perl_alloc();
321 perl_construct( my_perl );
322
323 perl_parse(my_perl, NULL, 3, embedding, NULL);
324 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
325 perl_run(my_perl);
326
327 /** Treat $a as an integer **/
328 eval_pv("$a = 3; $a **= 2", TRUE);
329 printf("a = %d\n", SvIV(get_sv("a", FALSE)));
330
331 /** Treat $a as a float **/
332 eval_pv("$a = 3.14; $a **= 2", TRUE);
333 printf("a = %f\n", SvNV(get_sv("a", FALSE)));
334
335 /** Treat $a as a string **/
336 eval_pv("$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);", TRUE);
337 printf("a = %s\n", SvPV(get_sv("a", FALSE), n_a));
338
339 perl_destruct(my_perl);
340 perl_free(my_perl);
341 PERL_SYS_TERM();
342 }
343
344All of those strange functions with I<sv> in their names help convert Perl scalars to C types. They're described in L<perlguts> and L<perlapi>.
345
346If you compile and run I<string.c>, you'll see the results of using
347I<SvIV()> to create an C<int>, I<SvNV()> to create a C<float>, and
348I<SvPV()> to create a string:
349
350 a = 9
351 a = 9.859600
352 a = Just Another Perl Hacker
353
354In the example above, we've created a global variable to temporarily
355store the computed value of our eval'd expression. It is also
356possible and in most cases a better strategy to fetch the return value
357from I<eval_pv()> instead. Example:
358
359 ...
360 STRLEN n_a;
361 SV *val = eval_pv("reverse 'rekcaH lreP rehtonA tsuJ'", TRUE);
362 printf("%s\n", SvPV(val,n_a));
363 ...
364
365This way, we avoid namespace pollution by not creating global
366variables and we've simplified our code as well.
367
368=head2 Performing Perl pattern matches and substitutions from your C program
369
370The I<eval_sv()> function lets us evaluate strings of Perl code, so we can
371define some functions that use it to "specialize" in matches and
372substitutions: I<match()>, I<substitute()>, and I<matches()>.
373
374 I32 match(SV *string, char *pattern);
375
376Given a string and a pattern (e.g., C<m/clasp/> or C</\b\w*\b/>, which
377in your C program might appear as "/\\b\\w*\\b/"), match()
378returns 1 if the string matches the pattern and 0 otherwise.
379
380 int substitute(SV **string, char *pattern);
381
382Given a pointer to an C<SV> and an C<=~> operation (e.g.,
383C<s/bob/robert/g> or C<tr[A-Z][a-z]>), substitute() modifies the string
384within the C<SV> as according to the operation, returning the number of substitutions
385made.
386
387 int matches(SV *string, char *pattern, AV **matches);
388
389Given an C<SV>, a pattern, and a pointer to an empty C<AV>,
390matches() evaluates C<$string =~ $pattern> in a list context, and
391fills in I<matches> with the array elements, returning the number of matches found.
392
393Here's a sample program, I<match.c>, that uses all three (long lines have
394been wrapped here):
395
396 #include <EXTERN.h>
397 #include <perl.h>
398
399 static PerlInterpreter *my_perl;
400
401 /** my_eval_sv(code, error_check)
402 ** kinda like eval_sv(),
403 ** but we pop the return value off the stack
404 **/
405 SV* my_eval_sv(SV *sv, I32 croak_on_error)
406 {
407 dSP;
408 SV* retval;
409 STRLEN n_a;
410
411 PUSHMARK(SP);
412 eval_sv(sv, G_SCALAR);
413
414 SPAGAIN;
415 retval = POPs;
416 PUTBACK;
417
418 if (croak_on_error && SvTRUE(ERRSV))
419 croak(SvPVx(ERRSV, n_a));