home *** CD-ROM | disk | FTP | other *** search
/ BURKS 2 / BURKS_AUG97.ISO / SLAKWARE / D13 / PERL2.TGZ / perl2.tar / usr / lib / perl5 / pod / perlembed.pod < prev    next >
Text File  |  1996-06-28  |  19KB  |  566 lines

  1. =head1 NAME
  2.  
  3. perlembed - how to embed perl in your C program
  4.  
  5. =head1 DESCRIPTION
  6.  
  7. =head2 PREAMBLE
  8.  
  9. Do you want to:
  10.  
  11. =over 5
  12.  
  13. =item B<Use C from Perl?>  
  14.  
  15. Read L<perlcall> and L<perlxs>.
  16.  
  17. =item B<Use a UNIX program from Perl?>  
  18.  
  19. Read about backquotes and L<perlfunc/system> and L<perlfunc/exec>.
  20.  
  21. =item B<Use Perl from Perl?>  
  22.  
  23. Read about L<perlfunc/do> and L<perlfunc/eval> and L<perlmod/use> 
  24. and L<perlmod/require>.
  25.  
  26. =item B<Use C from C?>  
  27.  
  28. Rethink your design.
  29.  
  30. =item B<Use Perl from C?>  
  31.  
  32. Read on...
  33.  
  34. =back
  35.  
  36. =head2 ROADMAP
  37.  
  38. L<Compiling your C program>
  39.  
  40. There's one example in each of the five sections:
  41.  
  42. L<Adding a Perl interpreter to your C program>
  43.  
  44. L<Calling a Perl subroutine from your C program>
  45.  
  46. L<Evaluating a Perl statement from your C program>
  47.  
  48. L<Performing Perl pattern matches and substitutions from your C program>
  49.  
  50. L<Fiddling with the Perl stack from your C program>
  51.  
  52. This documentation is UNIX specific.
  53.  
  54. =head2 Compiling your C program
  55.  
  56. Every C program that uses Perl must link in the I<perl library>.  
  57.  
  58. What's that, you ask?  Perl is itself written in C; the perl library
  59. is the collection of compiled C programs that were used to create your
  60. perl executable (I</usr/bin/perl> or equivalent).  (Corollary: you
  61. can't use Perl from your C program unless Perl has been compiled on
  62. your machine, or installed properly--that's why you shouldn't blithely
  63. copy Perl executables from machine to machine without also copying the
  64. I<lib> directory.)
  65.  
  66. Your C program will--usually--allocate, "run", and deallocate a
  67. I<PerlInterpreter> object, which is defined in the perl library.  
  68.  
  69. If 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
  71. I<perl.h>, which you'll also need) will
  72. reside in a directory resembling this:
  73.  
  74.     /usr/local/lib/perl5/your_architecture_here/CORE
  75.  
  76. or perhaps just
  77.  
  78.     /usr/local/lib/perl5/CORE
  79.  
  80. or maybe something like
  81.  
  82.     /usr/opt/perl5/CORE
  83.  
  84. Execute this statement for a hint about where to find CORE:
  85.  
  86.     perl -e 'use Config; print $Config{archlib}'
  87.  
  88. Here's how you might compile the example in the next section,
  89. L<Adding a Perl interpreter to your C program>,
  90. on 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.  
  95. You'll have to choose the appropriate compiler (I<cc>, I<gcc>, et al.)  and
  96. library directory (I</usr/local/lib/...>)  for your machine.  If your
  97. compiler complains that certain functions are undefined, or that it
  98. can'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
  100. to change the path following the -I.  
  101.  
  102. You may have to add extra libraries as well.  Which ones?
  103. Perhaps those printed by 
  104.  
  105.    perl -e 'use Config; print $Config{libs}'
  106.  
  107. =head2 Adding a Perl interpreter to your C program
  108.  
  109. In 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>,
  111. from the source distribution.  Here's a bastardized, non-portable version of
  112. I<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.  
  130. Now 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.  
  135. After a successful compilation, you'll be able to use I<interp> just
  136. like 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.  
  145. or
  146.  
  147.     % interp -e 'printf("%x", 3735928559)'
  148.     deadbeef
  149.  
  150. You can also read and execute Perl statements from a file while in the
  151. midst of your C program, by placing the filename in I<argv[1]> before
  152. calling I<perl_run()>.  
  153.  
  154. =head2 Calling a Perl subroutine from your C program
  155.  
  156. To call individual Perl subroutines, you'll need to remove the call to
  157. I<perl_run()> and replace it with a call to I<perl_call_argv()>.
  158.  
  159. That'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.  
  180. where I<showtime> is a Perl subroutine that takes no arguments (that's the
  181. I<G_NOARGS>) and for which I'll ignore the return value (that's the 
  182. I<G_DISCARD>).  Those flags, and others, are discussed in L<perlcall>.
  183.  
  184. I'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.  
  192. Simple 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.  
  200. yielding the number of seconds that elapsed between January 1, 1970
  201. (the beginning of the UNIX epoch), and the moment I began writing this
  202. sentence.
  203.  
  204. If you want to pass some arguments to the Perl subroutine, or
  205. you want to access the return value, you'll need to manipulate the
  206. Perl stack, demonstrated in the last section of this document: 
  207. L<Fiddling with the Perl stack from your C program>
  208.  
  209. =head2 Evaluating a Perl statement from your C program
  210.  
  211. NOTE: This section, and the next, employ some very brittle techniques
  212. for evaluting strings of Perl code.  Perl 5.002 contains some nifty
  213. features that enable A Better Way (such as with L<perlguts/perl_eval_sv>).
  214. Look for updates to this document soon.
  215.  
  216. One way to evaluate a Perl string is to define a function (we'll call 
  217. ours I<perl_eval()>) that wraps around Perl's L<perlfunc/eval>.
  218.  
  219. Arguably, this is the only routine you'll ever need to execute
  220. snippets of Perl code from within your C program.  Your string can be
  221. as long as you wish; it can contain multiple statements; it can
  222. use L<perlmod/require> or L<perlfunc/do> to include external Perl
  223. files.  
  224.  
  225. Our I<perl_eval()> lets us evaluate individual Perl strings, and then 
  226. extract variables for coercion into C types.  The following program, 
  227. I<string.c>, executes three Perl strings, extracting an C<int> from
  228. the 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_