home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 2 / AACD 2.iso / AACD / Programming / perlman / man / perlembed.txt < prev    next >
Encoding:
Text File  |  1999-09-09  |  21.3 KB  |  581 lines

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