This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Use PERL=../miniperl
[perl5.git] / pod / perlembed.pod
CommitLineData
a0d0e21e
LW
1=head1 NAME
2
cb1a09d0 3perlembed - how to embed perl in your C program
a0d0e21e
LW
4
5=head1 DESCRIPTION
6
cb1a09d0
AD
7=head2 PREAMBLE
8
9Do you want to:
10
11=over 5
12
13=item B<Use C from Perl?>
14
15Read L<perlcall> and L<perlxs>.
16
17=item B<Use a UNIX program from Perl?>
18
19Read about backquotes and L<perlfunc/system> and L<perlfunc/exec>.
20
21=item B<Use Perl from Perl?>
22
23Read about L<perlfunc/do> and L<perlfunc/eval> and L<perlmod/use>
24and L<perlmod/require>.
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
38L<Compiling your C program>
39
40There's one example in each of the five sections:
41
42L<Adding a Perl interpreter to your C program>
43
44L<Calling a Perl subroutine from your C program>
45
46L<Evaluating a Perl statement from your C program>
47
48L<Performing Perl pattern matches and substitutions from your C program>
49
50L<Fiddling with the Perl stack from your C program>
51
52This documentation is UNIX specific.
53
54=head2 Compiling your C program
55
56Every C program that uses Perl must link in the I<perl library>.
57
58What's that, you ask? Perl is itself written in C; the perl library
59is the collection of compiled C programs that were used to create your
60perl executable (I</usr/bin/perl> or equivalent). (Corollary: you
61can't use Perl from your C program unless Perl has been compiled on
62your machine, or installed properly--that's why you shouldn't blithely
63copy Perl executables from machine to machine without also copying the
64I<lib> directory.)
65
66Your C program will--usually--allocate, "run", and deallocate a
67I<PerlInterpreter> object, which is defined in the perl library.
68
69If your copy of Perl is recent enough to contain this documentation
70(5.002 or later), then the perl library (and I<EXTERN.h> and
71I<perl.h>, which you'll also need) will
72reside in a directory resembling this:
73
74 /usr/local/lib/perl5/your_architecture_here/CORE
75
76or perhaps just
77
78 /usr/local/lib/perl5/CORE
79
80or maybe something like
81
82 /usr/opt/perl5/CORE
83
84Execute this statement for a hint about where to find CORE:
85
86 perl -e 'use Config; print $Config{archlib}'
87
88Here's how you might compile the example in the next section,
89L<Adding a Perl interpreter to your C program>,
90on a DEC Alpha running the OSF operating system:
91
92 % cc -o interp interp.c -L/usr/local/lib/perl5/alpha-dec_osf/CORE
93 -I/usr/local/lib/perl5/alpha-dec_osf/CORE -lperl -lm
94
95You'll have to choose the appropriate compiler (I<cc>, I<gcc>, et al.) and
96library directory (I</usr/local/lib/...>) for your machine. If your
97compiler complains that certain functions are undefined, or that it
98can't locate I<-lperl>, then you need to change the path following the
99-L. If it complains that it can't find I<EXTERN.h> or I<perl.h>, you need
100to change the path following the -I.
101
102You may have to add extra libraries as well. Which ones?
103Perhaps those printed by
104
105 perl -e 'use Config; print $Config{libs}'
106
107=head2 Adding a Perl interpreter to your C program
108
109In a sense, perl (the C program) is a good example of embedding Perl
110(the language), so I'll demonstrate embedding with I<miniperlmain.c>,
111from the source distribution. Here's a bastardized, non-portable version of
112I<miniperlmain.c> containing the essentials of embedding:
113
114 #include <stdio.h>
115 #include <EXTERN.h> /* from the Perl distribution */
116 #include <perl.h> /* from the Perl distribution */
117
118 static PerlInterpreter *my_perl; /*** The Perl interpreter ***/
119
120 int main(int argc, char **argv, char **env)
121 {
122 my_perl = perl_alloc();
123 perl_construct(my_perl);
124 perl_parse(my_perl, NULL, argc, argv, env);
125 perl_run(my_perl);
126 perl_destruct(my_perl);
127 perl_free(my_perl);
128 }
129
130Now compile this program (I'll call it I<interp.c>) into an executable:
131
132 % cc -o interp interp.c -L/usr/local/lib/perl5/alpha-dec_osf/CORE
133 -I/usr/local/lib/perl5/alpha-dec_osf/CORE -lperl -lm
134
135After a successful compilation, you'll be able to use I<interp> just
136like perl itself:
137
138 % interp
139 print "Pretty Good Perl \n";
140 print "10890 - 9801 is ", 10890 - 9801;
141 <CTRL-D>
142 Pretty Good Perl
143 10890 - 9801 is 1089
144
145or
146
147 % interp -e 'printf("%x", 3735928559)'
148 deadbeef
149
150You can also read and execute Perl statements from a file while in the
151midst of your C program, by placing the filename in I<argv[1]> before
152calling I<perl_run()>.
153
154=head2 Calling a Perl subroutine from your C program
155
156To call individual Perl subroutines, you'll need to remove the call to
157I<perl_run()> and replace it with a call to I<perl_call_argv()>.
158
159That's shown below, in a program I'll call I<showtime.c>.
160
161 #include <stdio.h>
162 #include <EXTERN.h>
163 #include <perl.h>
164
165 static PerlInterpreter *my_perl;
166
167 int main(int argc, char **argv, char **env)
168 {
169 my_perl = perl_alloc();
170 perl_construct(my_perl);
171
172 perl_parse(my_perl, NULL, argc, argv, env);
173
174 /*** This replaces perl_run() ***/
175 perl_call_argv("showtime", G_DISCARD | G_NOARGS, argv);
176 perl_destruct(my_perl);
177 perl_free(my_perl);
178 }
179
180where I<showtime> is a Perl subroutine that takes no arguments (that's the
181I<G_NOARGS>) and for which I'll ignore the return value (that's the
182I<G_DISCARD>). Those flags, and others, are discussed in L<perlcall>.
183
184I'll define the I<showtime> subroutine in a file called I<showtime.pl>:
185
186 print "I shan't be printed.";
187
188 sub showtime {
189 print time;
190 }
191
192Simple enough. Now compile and run:
193
194 % cc -o showtime showtime.c -L/usr/local/lib/perl5/alpha-dec_osf/CORE
195 -I/usr/local/lib/perl5/alpha-dec_osf/CORE -lperl -lm
196
197 % showtime showtime.pl
198 818284590
199
200yielding the number of seconds that elapsed between January 1, 1970
201(the beginning of the UNIX epoch), and the moment I began writing this
202sentence.
203
204If you want to pass some arguments to the Perl subroutine, or
205you want to access the return value, you'll need to manipulate the
206Perl stack, demonstrated in the last section of this document:
207L<Fiddling with the Perl stack from your C program>
208
209=head2 Evaluating a Perl statement from your C program
210
211NOTE: This section, and the next, employ some very brittle techniques
212for evaluting strings of Perl code. Perl 5.002 contains some nifty
213features that enable A Better Way (such as with L<perlguts/perl_eval_sv>).
214Look for updates to this document soon.
215
216One way to evaluate a Perl string is to define a function (we'll call
217ours I<perl_eval()>) that wraps around Perl's L<perlfunc/eval>.
218
219Arguably, this is the only routine you'll ever need to execute
220snippets of Perl code from within your C program. Your string can be
221as long as you wish; it can contain multiple statements; it can
222use L<perlmod/require> or L<perlfunc/do> to include external Perl
223files.
224
225Our I<perl_eval()> lets us evaluate individual Perl strings, and then
226extract variables for coercion into C types. The following program,
227I<string.c>, executes three Perl strings, extracting an C<int> from
228the first, a C<float> from the second, and a C<char *> from the third.
229
230 #include <stdio.h>
231 #include <EXTERN.h>
232 #include <perl.h>
233
234 static PerlInterpreter *my_perl;
235
236 int perl_eval(char *string)
237 {
238 char *argv[2];
239 argv[0] = string;
240 argv[1] = NULL;
241 perl_call_argv("_eval_", 0, argv);
242 }
243
244 main (int argc, char **argv, char **env)
245 {
246 char *embedding[] = { "", "-e", "sub _eval_ { eval $_[0] }" };
247 STRLEN length;
248
249 my_perl = perl_alloc();
250 perl_construct( my_perl );
251
252 perl_parse(my_perl, NULL, 3, embedding, env);
253
254 /** Treat $a as an integer **/
255 perl_eval("$a = 3; $a **= 2");
256 printf("a = %d\n", SvIV(perl_get_sv("a", FALSE)));
257
258 /** Treat $a as a float **/
259 perl_eval("$a = 3.14; $a **= 2");
260 printf("a = %f\n", SvNV(perl_get_sv("a", FALSE)));
261
262 /** Treat $a as a string **/
263 perl_eval("$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a); ");
264 printf("a = %s\n", SvPV(perl_get_sv("a", FALSE), length));
265
266 perl_destruct(my_perl);
267 perl_free(my_perl);
268 }
269
270All of those strange functions with I<sv> in their names help convert Perl scalars to C types. They're described in L<perlguts>.
271
272If you compile and run I<string.c>, you'll see the results of using
273I<SvIV()> to create an C<int>, I<SvNV()> to create a C<float>, and
274I<SvPV()> to create a string:
275
276 a = 9
277 a = 9.859600
278 a = Just Another Perl Hacker
279
280
281=head2 Performing Perl pattern matches and substitutions from your C program
282
283Our I<perl_eval()> lets us evaluate strings of Perl code, so we can
284define some functions that use it to "specialize" in matches and
285substitutions: I<match()>, I<substitute()>, and I<matches()>.
286
287 char match(char *string, char *pattern);
288
289Given a string and a pattern (e.g. "m/clasp/" or "/\b\w*\b/", which in
290your program might be represented as C<"/\\b\\w*\\b/">),
291returns 1 if the string matches the pattern and 0 otherwise.
292
293
294 int substitute(char *string[], char *pattern);
295
296Given a pointer to a string and an "=~" operation (e.g. "s/bob/robert/g" or
297"tr[A-Z][a-z]"), modifies the string according to the operation,
298returning the number of substitutions made.
299
300 int matches(char *string, char *pattern, char **matches[]);
301
302Given a string, a pattern, and a pointer to an empty array of strings,
303evaluates C<$string =~ $pattern> in an array context, and fills in
304I<matches> with the array elements (allocating memory as it does so),
305returning the number of matches found.
306
307Here's a sample program, I<match.c>, that uses all three:
308
309 #include <stdio.h>
310 #include <EXTERN.h>
311 #include <perl.h>
312
313 static PerlInterpreter *my_perl;
314
315 int eval(char *string)
316 {
317 char *argv[2];
318 argv[0] = string;
319 argv[1] = NULL;
320 perl_call_argv("_eval_", 0, argv);
321 }
322
323 /** match(string, pattern)
324 **
325 ** Used for matches in a scalar context.
326 **
327 ** Returns 1 if the match was successful; 0 otherwise.
328 **/
329 char match(char *string, char *pattern)
330 {
331 char *command;
332 command = malloc(sizeof(char) * strlen(string) + strlen(pattern) + 37);
333 sprintf(command, "$string = '%s'; $return = $string =~ %s",
334 string, pattern);
335 perl_eval(command);
336 free(command);
337 return SvIV(perl_get_sv("return", FALSE));
338 }
339
340 /** substitute(string, pattern)
341 **
342 ** Used for =~ operations that modify their left-hand side (s/// and tr///)
343 **
344 ** Returns the number of successful matches, and
345 ** modifies the input string if there were any.
346 **/
347 int substitute(char *string[], char *pattern)
348 {
349 char *command;
350 STRLEN length;
351 command = malloc(sizeof(char) * strlen(*string) + strlen(pattern) + 35);
352 sprintf(command, "$string = '%s'; $ret = ($string =~ %s)",
353 *string, pattern);
354 perl_eval(command);
355 free(command);
356 *string = SvPV(perl_get_sv("string", FALSE), length);
357 return SvIV(perl_get_sv("ret", FALSE));
358 }
359
360 /** matches(string, pattern, matches)
361 **
362 ** Used for matches in an array context.
363 **
364 ** Returns the number of matches,
365 ** and fills in **matches with the matching substrings (allocates memory!)
366 **/
367 int matches(char *string, char *pattern, char **matches[])
368 {
369 char *command;
370 SV *current_match;
371 AV *array;
372 I32 num_matches;
373 STRLEN length;
374 int i;
375
376 command = malloc(sizeof(char) * strlen(string) + strlen(pattern) + 38);
377 sprintf(command, "$string = '%s'; @array = ($string =~ %s)",
378 string, pattern);
379 perl_eval(command);
380 free(command);
381 array = perl_get_av("array", FALSE);
382 num_matches = av_len(array) + 1; /** assume $[ is 0 **/
383 *matches = (char **) malloc(sizeof(char *) * num_matches);
384 for (i = 0; i <= num_matches; i++) {
385 current_match = av_shift(array);
386 (*matches)[i] = SvPV(current_match, length);
387 }
388 return num_matches;
389 }
390
391 main (int argc, char **argv, char **env)
392 {
393 char *embedding[] = { "", "-e", "sub _eval_ { eval $_[0] }" };
394 char *text, **matches;
395 int num_matches, i;
396 int j;
397
398 my_perl = perl_alloc();
399 perl_construct( my_perl );
400
401 perl_parse(my_perl, NULL, 3, embedding, env);
402
403 text = (char *) malloc(sizeof(char) * 486); /** A long string follows! **/
404 sprintf(text, "%s", "When he is at a convenience store and the bill comes to some amount like 76 cents, Maynard is aware that there is something he *should* do, something that will enable him to get back a quarter, but he has no idea *what*. He fumbles through his red squeezey changepurse and gives the boy three extra pennies with his dollar, hoping that he might luck into the correct amount. The boy gives him back two of his own pennies and then the big shiny quarter that is his prize. -RICHH");
405
406 if (perl_match(text, "m/quarter/")) /** Does text contain 'quarter'? **/
407 printf("perl_match: Text contains the word 'quarter'.\n\n");
408 else
409 printf("perl_match: Text doesn't contain the word 'quarter'.\n\n");
410
411 if (perl_match(text, "m/eighth/")) /** Does text contain 'eighth'? **/
412 printf("perl_match: Text contains the word 'eighth'.\n\n");
413 else
414 printf("perl_match: Text doesn't contain the word 'eighth'.\n\n");
415
416 /** Match all occurrences of /wi../ **/
417 num_matches = perl_matches(text, "m/(wi..)/g", &matches);
418
419 printf("perl_matches: m/(wi..)/g found %d matches...\n", num_matches);
420 for (i = 0; i < num_matches; i++)
421 printf("match: %s\n", matches[i]);
422 printf("\n");
423 for (i = 0; i < num_matches; i++) {
424 free(matches[i]);
425 }
426 free(matches);
427
428 /** Remove all vowels from text **/
429 num_matches = perl_substitute(&text, "s/[aeiou]//gi");
430 if (num_matches) {
431 printf("perl_substitute: s/[aeiou]//gi...%d substitutions made.\n",
432 num_matches);
433 printf("Now text is: %s\n\n", text);
434 }
435
436 /** Attempt a substitution
437 if (!perl_substitute(&text, "s/Perl/C/")) {
438 printf("perl_substitute: s/Perl/C...No substitution made.\n\n");
439 }
440
441 free(text);
442
443 perl_destruct(my_perl);
444 perl_free(my_perl);
445 }
446
447which produces the output
448
449 perl_match: Text contains the word 'quarter'.
450
451 perl_match: Text doesn't contain the word 'eighth'.
452
453 perl_matches: m/(wi..)/g found 2 matches...
454 match: will
455 match: with
456
457 perl_substitute: s/[aeiou]//gi...139 substitutions made.
458 Now text is: Whn h s t cnvnnc str nd th bll cms t sm mnt lk 76 cnts, Mynrd s wr tht thr s smthng h *shld* d, smthng tht wll nbl hm t gt bck qrtr, bt h hs n d *wht*. H fmbls thrgh hs rd sqzy chngprs nd gvs th by thr xtr pnns wth hs dllr, hpng tht h mght lck nt th crrct mnt. Th by gvs hm bck tw f hs wn pnns nd thn th bg shny qrtr tht s hs prz. -RCHH
459
460 perl_substitute: s/Perl/C...No substitution made.
461
462=head2 Fiddling with the Perl stack from your C program
463
464When trying to explain stacks, most computer science textbooks mumble
465something about spring-loaded columns of cafeteria plates: the last
466thing you pushed on the stack is the first thing you pop off. That'll
467do for our purposes: your C program will push some arguments onto "the Perl
468stack", shut its eyes while some magic happens, and then pop the
469results--the return value of your Perl subroutine--off the stack.
470
471First you'll need to know how to convert between C types and Perl
472types, with newSViv() and sv_setnv() and newAV() and all their
473friends. They're described in L<perlguts>.
474
475Then you'll need to know how to manipulate the Perl stack. That's
476described in L<perlcall>.
477
478Once you've understood those, embedding Perl in C is easy.
479
480Since C has no built-in function for integer exponentiation, let's
481make Perl's ** operator available to it (this is less useful than it
482sounds, since Perl implements ** with C's I<pow()> function). First
483I'll create a stub exponentiation function in I<power.pl>:
484
485 sub expo {
486 my ($a, $b) = @_;
487 return $a ** $b;
488 }
489
490Now I'll create a C program, I<power.c>, with a function
491I<PerlPower()> that contains all the perlguts necessary to push the
492two arguments into I<expo()> and to pop the return value out. Take a
493deep breath...
494
495 #include <stdio.h>
496 #include <EXTERN.h>
497 #include <perl.h>
498
499 static PerlInterpreter *my_perl;
500
501 static void
502 PerlPower(int a, int b)
503 {
504 dSP; /* initialize stack pointer */
505 ENTER; /* everything created after here */
506 SAVETMPS; /* ...is a temporary variable. */
507 PUSHMARK(sp); /* remember the stack pointer */
508 XPUSHs(sv_2mortal(newSViv(a))); /* push the base onto the stack */
509 XPUSHs(sv_2mortal(newSViv(b))); /* push the exponent onto stack */
510 PUTBACK; /* make local stack pointer global */
511 perl_call_pv("expo", G_SCALAR); /* call the function */
512 SPAGAIN; /* refresh stack pointer */
513 /* pop the return value from stack */
514 printf ("%d to the %dth power is %d.\n", a, b, POPi);
515 PUTBACK;
516 FREETMPS; /* free that return value */
517 LEAVE; /* ...and the XPUSHed "mortal" args.*/
518 }
519
520 int main (int argc, char **argv, char **env)
521 {
522 char *my_argv[2];
523
524 my_perl = perl_alloc();
525 perl_construct( my_perl );
526
527 my_argv[1] = (char *) malloc(10);
528 sprintf(my_argv[1], "power.pl");
529
530 perl_parse(my_perl, NULL, argc, my_argv, env);
531
532 PerlPower(3, 4); /*** Compute 3 ** 4 ***/
533
534 perl_destruct(my_perl);
535 perl_free(my_perl);
536 }
537
538
539
540Compile and run:
541
542 % cc -o power power.c -L/usr/local/lib/perl5/alpha-dec_osf/CORE
543 -I/usr/local/lib/perl5/alpha-dec_osf/CORE -lperl -lm
544
545 % power
546 3 to the 4th power is 81.
547
548=head1 MORAL
549
550You can sometimes I<write faster code> in C, but
551you can always I<write code faster> in Perl. Since you can use
552each from the other, combine them as you wish.
553
554
555=head1 AUTHOR
556
557Jon Orwant F<E<lt>orwant@media.mit.eduE<gt>>, with contributions from
558Tim Bunce, Tom Christiansen, Dov Grobgeld, and Ilya Zakharevich.
559
560December 18, 1995
561
562Some of this material is excerpted from my book: I<Perl 5 Interactive>,
563Waite Group Press, 1996 (ISBN 1-57169-064-6) and appears
564courtesy of Waite Group Press.
565