home *** CD-ROM | disk | FTP | other *** search
/ Chip 2000 May / Chip_2000-05_cd1.bin / zkuste / Perl / ActivePerl-5.6.0.613.msi / 䆊䌷䈹䈙䏵-䞅䞆䞀㡆䞃䄦䠥 / _c744c7c2da69b1ef10679b36fe23752a < prev    next >
Text File  |  2000-03-23  |  45KB  |  975 lines

  1. <HTML>
  2. <HEAD>
  3. <TITLE>perlembed - how to embed perl in your C program</TITLE>
  4. <LINK REL="stylesheet" HREF="../../Active.css" TYPE="text/css">
  5. <LINK REV="made" HREF="mailto:">
  6. </HEAD>
  7.  
  8. <BODY>
  9. <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
  10. <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
  11. <STRONG><P CLASS=block> perlembed - how to embed perl in your C program</P></STRONG>
  12. </TD></TR>
  13. </TABLE>
  14.  
  15. <A NAME="__index__"></A>
  16. <!-- INDEX BEGIN -->
  17.  
  18. <UL>
  19.  
  20.     <LI><A HREF="#name">NAME</A></LI>
  21.     <LI><A HREF="#description">DESCRIPTION</A></LI>
  22.     <UL>
  23.  
  24.         <LI><A HREF="#preamble">PREAMBLE</A></LI>
  25.         <LI><A HREF="#roadmap">ROADMAP</A></LI>
  26.         <LI><A HREF="#compiling your c program">Compiling your C program</A></LI>
  27.         <LI><A HREF="#adding a perl interpreter to your c program">Adding a Perl interpreter to your C program</A></LI>
  28.         <LI><A HREF="#calling a perl subroutine from your c program">Calling a Perl subroutine from your C program</A></LI>
  29.         <LI><A HREF="#evaluating a perl statement from your c program">Evaluating a Perl statement from your C program</A></LI>
  30.         <LI><A HREF="#performing perl pattern matches and substitutions from your c program">Performing Perl pattern matches and substitutions from your C program</A></LI>
  31.         <LI><A HREF="#fiddling with the perl stack from your c program">Fiddling with the Perl stack from your C program</A></LI>
  32.         <LI><A HREF="#maintaining a persistent interpreter">Maintaining a persistent interpreter</A></LI>
  33.         <LI><A HREF="#maintaining multiple interpreter instances">Maintaining multiple interpreter instances</A></LI>
  34.         <LI><A HREF="#using perl modules, which themselves use c libraries, from your c program">Using Perl modules, which themselves use C libraries, from your C program</A></LI>
  35.     </UL>
  36.  
  37.     <LI><A HREF="#embedding perl under win32">Embedding Perl under Win32</A></LI>
  38.     <LI><A HREF="#moral">MORAL</A></LI>
  39.     <LI><A HREF="#author">AUTHOR</A></LI>
  40.     <LI><A HREF="#copyright">COPYRIGHT</A></LI>
  41. </UL>
  42. <!-- INDEX END -->
  43.  
  44. <HR>
  45. <P>
  46. <H1><A NAME="name">NAME</A></H1>
  47. <P>perlembed - how to embed perl in your C program</P>
  48. <P>
  49. <HR>
  50. <H1><A NAME="description">DESCRIPTION</A></H1>
  51. <P>
  52. <H2><A NAME="preamble">PREAMBLE</A></H2>
  53. <P>Do you want to:</P>
  54. <DL>
  55. <DT><STRONG><A NAME="item_Use_C_from_Perl%3F"><STRONG>Use C from Perl?</STRONG></A></STRONG><BR>
  56. <DD>
  57. Read <A HREF="../../lib/Pod/perlxstut.html">the perlxstut manpage</A>, <A HREF="../../lib/Pod/perlxs.html">the perlxs manpage</A>, <EM>h2xs</EM>, <A HREF="../../lib/Pod/perlguts.html">the perlguts manpage</A>, and <A HREF="../../lib/Pod/perlapi.html">the perlapi manpage</A>.
  58. <P></P>
  59. <DT><STRONG><A NAME="item_Use_a_Unix_program_from_Perl%3F"><STRONG>Use a Unix program from Perl?</STRONG></A></STRONG><BR>
  60. <DD>
  61. Read about back-quotes and about <A HREF="../../lib/Pod/perlfunc.html#item_system"><CODE>system</CODE></A> and <A HREF="../../lib/Pod/perlfunc.html#item_exec"><CODE>exec</CODE></A> in <A HREF="../../lib/Pod/perlfunc.html">the perlfunc manpage</A>.
  62. <P></P>
  63. <DT><STRONG><A NAME="item_Use_Perl_from_Perl%3F"><STRONG>Use Perl from Perl?</STRONG></A></STRONG><BR>
  64. <DD>
  65. Read about <A HREF="../../lib/Pod/perlfunc.html#do">do in the perlfunc manpage</A> and <A HREF="../../lib/Pod/perlfunc.html#eval">eval in the perlfunc manpage</A> and <A HREF="../../lib/Pod/perlfunc.html#require">require in the perlfunc manpage</A> 
  66. and <A HREF="../../lib/Pod/perlfunc.html#use">use in the perlfunc manpage</A>.
  67. <P></P>
  68. <DT><STRONG><A NAME="item_Use_C_from_C%3F"><STRONG>Use C from C?</STRONG></A></STRONG><BR>
  69. <DD>
  70. Rethink your design.
  71. <P></P>
  72. <DT><STRONG><A NAME="item_Use_Perl_from_C%3F"><STRONG>Use Perl from C?</STRONG></A></STRONG><BR>
  73. <DD>
  74. Read on...
  75. <P></P></DL>
  76. <P>
  77. <H2><A NAME="roadmap">ROADMAP</A></H2>
  78. <P><A HREF="#compiling your c program">Compiling your C program</A></P>
  79. <P><A HREF="#adding a perl interpreter to your c program">Adding a Perl interpreter to your C program</A></P>
  80. <P><A HREF="#calling a perl subroutine from your c program">Calling a Perl subroutine from your C program</A></P>
  81. <P><A HREF="#evaluating a perl statement from your c program">Evaluating a Perl statement from your C program</A></P>
  82. <P><A HREF="#performing perl pattern matches and substitutions from your c program">Performing Perl pattern matches and substitutions from your C program</A></P>
  83. <P><A HREF="#fiddling with the perl stack from your c program">Fiddling with the Perl stack from your C program</A></P>
  84. <P><A HREF="#maintaining a persistent interpreter">Maintaining a persistent interpreter</A></P>
  85. <P><A HREF="#maintaining multiple interpreter instances">Maintaining multiple interpreter instances</A></P>
  86. <P><A HREF="#using perl modules, which themselves use c libraries, from your c program">Using Perl modules, which themselves use C libraries, from your C program</A></P>
  87. <P><A HREF="#embedding perl under win32">Embedding Perl under Win32</A></P>
  88. <P>
  89. <H2><A NAME="compiling your c program">Compiling your C program</A></H2>
  90. <P>If you have trouble compiling the scripts in this documentation,
  91. you're not alone.  The cardinal rule: COMPILE THE PROGRAMS IN EXACTLY
  92. THE SAME WAY THAT YOUR PERL WAS COMPILED.  (Sorry for yelling.)</P>
  93. <P>Also, every C program that uses Perl must link in the <EM>perl library</EM>.
  94. What's that, you ask?  Perl is itself written in C; the perl library
  95. is the collection of compiled C programs that were used to create your
  96. perl executable (<EM>/usr/bin/perl</EM> or equivalent).  (Corollary: you
  97. can't use Perl from your C program unless Perl has been compiled on
  98. your machine, or installed properly--that's why you shouldn't blithely
  99. copy Perl executables from machine to machine without also copying the
  100. <EM>lib</EM> directory.)</P>
  101. <P>When you use Perl from C, your C program will--usually--allocate,
  102. ``run'', and deallocate a <EM>PerlInterpreter</EM> object, which is defined by
  103. the perl library.</P>
  104. <P>If your copy of Perl is recent enough to contain this documentation
  105. (version 5.002 or later), then the perl library (and <EM>EXTERN.h</EM> and
  106. <EM>perl.h</EM>, which you'll also need) will reside in a directory
  107. that looks like this:</P>
  108. <PRE>
  109.     /usr/local/lib/perl5/your_architecture_here/CORE</PRE>
  110. <P>or perhaps just</P>
  111. <PRE>
  112.     /usr/local/lib/perl5/CORE</PRE>
  113. <P>or maybe something like</P>
  114. <PRE>
  115.     /usr/opt/perl5/CORE</PRE>
  116. <P>Execute this statement for a hint about where to find CORE:</P>
  117. <PRE>
  118.     perl -MConfig -e 'print $Config{archlib}'</PRE>
  119. <P>Here's how you'd compile the example in the next section,
  120. <A HREF="#adding a perl interpreter to your c program">Adding a Perl interpreter to your C program</A>, on my Linux box:</P>
  121. <PRE>
  122.     % gcc -O2 -Dbool=char -DHAS_BOOL -I/usr/local/include
  123.     -I/usr/local/lib/perl5/i586-linux/5.003/CORE
  124.     -L/usr/local/lib/perl5/i586-linux/5.003/CORE
  125.     -o interp interp.c -lperl -lm</PRE>
  126. <P>(That's all one line.)  On my DEC Alpha running old 5.003_05, the 
  127. incantation is a bit different:</P>
  128. <PRE>
  129.     % cc -O2 -Olimit 2900 -DSTANDARD_C -I/usr/local/include
  130.     -I/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE
  131.     -L/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE -L/usr/local/lib
  132.     -D__LANGUAGE_C__ -D_NO_PROTO -o interp interp.c -lperl -lm</PRE>
  133. <P>How can you figure out what to add?  Assuming your Perl is post-5.001,
  134. execute a <CODE>perl -V</CODE> command and pay special attention to the ``cc'' and
  135. ``ccflags'' information.</P>
  136. <P>You'll have to choose the appropriate compiler (<EM>cc</EM>, <EM>gcc</EM>, et al.) for
  137. your machine: <CODE>perl -MConfig -e 'print $Config{cc}'</CODE> will tell you what
  138. to use.</P>
  139. <P>You'll also have to choose the appropriate library directory
  140. (<EM>/usr/local/lib/...</EM>) for your machine.  If your compiler complains
  141. that certain functions are undefined, or that it can't locate
  142. <EM>-lperl</EM>, then you need to change the path following the <CODE>-L</CODE>.  If it
  143. complains that it can't find <EM>EXTERN.h</EM> and <EM>perl.h</EM>, you need to
  144. change the path following the <CODE>-I</CODE>.</P>
  145. <P>You may have to add extra libraries as well.  Which ones?
  146. Perhaps those printed by</P>
  147. <PRE>
  148.    perl -MConfig -e 'print $Config{libs}'</PRE>
  149. <P>Provided your perl binary was properly configured and installed the
  150. <STRONG>ExtUtils::Embed</STRONG> module will determine all of this information for
  151. you:</P>
  152. <PRE>
  153.    % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`</PRE>
  154. <P>If the <STRONG>ExtUtils::Embed</STRONG> module isn't part of your Perl distribution,
  155. you can retrieve it from
  156. <A HREF="http://www.perl.com/perl/CPAN/modules/by-module/ExtUtils/.">http://www.perl.com/perl/CPAN/modules/by-module/ExtUtils/.</A>  (If
  157. this documentation came from your Perl distribution, then you're
  158. running 5.004 or better and you already have it.)</P>
  159. <P>The <STRONG>ExtUtils::Embed</STRONG> kit on CPAN also contains all source code for
  160. the examples in this document, tests, additional examples and other
  161. information you may find useful.</P>
  162. <P>
  163. <H2><A NAME="adding a perl interpreter to your c program">Adding a Perl interpreter to your C program</A></H2>
  164. <P>In a sense, perl (the C program) is a good example of embedding Perl
  165. (the language), so I'll demonstrate embedding with <EM>miniperlmain.c</EM>,
  166. included in the source distribution.  Here's a bastardized, nonportable
  167. version of <EM>miniperlmain.c</EM> containing the essentials of embedding:</P>
  168. <PRE>
  169.     #include <EXTERN.h>               /* from the Perl distribution     */
  170.     #include <perl.h>                 /* from the Perl distribution     */</PRE>
  171. <PRE>
  172.     static PerlInterpreter *my_perl;  /***    The Perl interpreter    ***/</PRE>
  173. <PRE>
  174.     int main(int argc, char **argv, char **env)
  175.     {
  176.         my_perl = perl_alloc();
  177.         perl_construct(my_perl);
  178.         perl_parse(my_perl, NULL, argc, argv, (char **)NULL);
  179.         perl_run(my_perl);
  180.         perl_destruct(my_perl);
  181.         perl_free(my_perl);
  182.     }</PRE>
  183. <P>Notice that we don't use the <CODE>env</CODE> pointer.  Normally handed to
  184. <CODE>perl_parse</CODE> as its final argument, <CODE>env</CODE> here is replaced by
  185. <CODE>NULL</CODE>, which means that the current environment will be used.</P>
  186. <P>Now compile this program (I'll call it <EM>interp.c</EM>) into an executable:</P>
  187. <PRE>
  188.     % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`</PRE>
  189. <P>After a successful compilation, you'll be able to use <EM>interp</EM> just
  190. like perl itself:</P>
  191. <PRE>
  192.     % interp
  193.     print "Pretty Good Perl \n";
  194.     print "10890 - 9801 is ", 10890 - 9801;
  195.     <CTRL-D>
  196.     Pretty Good Perl
  197.     10890 - 9801 is 1089</PRE>
  198. <P>or</P>
  199. <PRE>
  200.     % interp -e 'printf("%x", 3735928559)'
  201.     deadbeef</PRE>
  202. <P>You can also read and execute Perl statements from a file while in the
  203. midst of your C program, by placing the filename in <EM>argv[1]</EM> before
  204. calling <EM>perl_run</EM>.</P>
  205. <P>
  206. <H2><A NAME="calling a perl subroutine from your c program">Calling a Perl subroutine from your C program</A></H2>
  207. <P>To call individual Perl subroutines, you can use any of the <STRONG>call_*</STRONG>
  208. functions documented in <A HREF="../../lib/Pod/perlcall.html">the perlcall manpage</A>.
  209. In this example we'll use <CODE>call_argv</CODE>.</P>
  210. <P>That's shown below, in a program I'll call <EM>showtime.c</EM>.</P>
  211. <PRE>
  212.     #include <EXTERN.h>
  213.     #include <perl.h></PRE>
  214. <PRE>
  215.     static PerlInterpreter *my_perl;</PRE>
  216. <PRE>
  217.     int main(int argc, char **argv, char **env)
  218.     {
  219.         char *args[] = { NULL };
  220.         my_perl = perl_alloc();
  221.         perl_construct(my_perl);</PRE>
  222. <PRE>
  223.         perl_parse(my_perl, NULL, argc, argv, NULL);</PRE>
  224. <PRE>
  225.         /*** skipping perl_run() ***/</PRE>
  226. <PRE>
  227.         call_argv("showtime", G_DISCARD | G_NOARGS, args);</PRE>
  228. <PRE>
  229.         perl_destruct(my_perl);
  230.         perl_free(my_perl);
  231.     }</PRE>
  232. <P>where <EM>showtime</EM> is a Perl subroutine that takes no arguments (that's the
  233. <EM>G_NOARGS</EM>) and for which I'll ignore the return value (that's the
  234. <EM>G_DISCARD</EM>).  Those flags, and others, are discussed in <A HREF="../../lib/Pod/perlcall.html">the perlcall manpage</A>.</P>
  235. <P>I'll define the <EM>showtime</EM> subroutine in a file called <EM>showtime.pl</EM>:</P>
  236. <PRE>
  237.     print "I shan't be printed.";</PRE>
  238. <PRE>
  239.     sub showtime {
  240.         print time;
  241.     }</PRE>
  242. <P>Simple enough.  Now compile and run:</P>
  243. <PRE>
  244.     % cc -o showtime showtime.c `perl -MExtUtils::Embed -e ccopts -e ldopts`</PRE>
  245. <PRE>
  246.     % showtime showtime.pl
  247.     818284590</PRE>
  248. <P>yielding the number of seconds that elapsed between January 1, 1970
  249. (the beginning of the Unix epoch), and the moment I began writing this
  250. sentence.</P>
  251. <P>In this particular case we don't have to call <EM>perl_run</EM>, but in
  252. general it's considered good practice to ensure proper initialization
  253. of library code, including execution of all object <CODE>DESTROY</CODE> methods
  254. and package <CODE>END {}</CODE> blocks.</P>
  255. <P>If you want to pass arguments to the Perl subroutine, you can add
  256. strings to the <CODE>NULL</CODE>-terminated <CODE>args</CODE> list passed to
  257. <EM>call_argv</EM>.  For other data types, or to examine return values,
  258. you'll need to manipulate the Perl stack.  That's demonstrated in the
  259. last section of this document: <A HREF="#fiddling with the perl stack from your c program">Fiddling with the Perl stack from your C program</A>.</P>
  260. <P>
  261. <H2><A NAME="evaluating a perl statement from your c program">Evaluating a Perl statement from your C program</A></H2>
  262. <P>Perl provides two API functions to evaluate pieces of Perl code.
  263. These are <A HREF="../../lib/Pod/perlapi.html#eval_sv">eval_sv in the perlapi manpage</A> and <A HREF="../../lib/Pod/perlapi.html#eval_pv">eval_pv in the perlapi manpage</A>.</P>
  264. <P>Arguably, these are the only routines you'll ever need to execute
  265. snippets of Perl code from within your C program.  Your code can be as
  266. long as you wish; it can contain multiple statements; it can employ
  267. <A HREF="../../lib/Pod/perlfunc.html#use">use in the perlfunc manpage</A>, <A HREF="../../lib/Pod/perlfunc.html#require">require in the perlfunc manpage</A>, and <A HREF="../../lib/Pod/perlfunc.html#do">do in the perlfunc manpage</A> to
  268. include external Perl files.</P>
  269. <P><EM>eval_pv</EM> lets us evaluate individual Perl strings, and then
  270. extract variables for coercion into C types.  The following program,
  271. <EM>string.c</EM>, executes three Perl strings, extracting an <A HREF="../../lib/Pod/perlfunc.html#item_int"><CODE>int</CODE></A> from
  272. the first, a <CODE>float</CODE> from the second, and a <CODE>char *</CODE> from the third.</P>
  273. <PRE>
  274.    #include <EXTERN.h>
  275.    #include <perl.h></PRE>
  276. <PRE>
  277.    static PerlInterpreter *my_perl;</PRE>
  278. <PRE>
  279.    main (int argc, char **argv, char **env)
  280.    {
  281.        STRLEN n_a;
  282.        char *embedding[] = { "", "-e", "0" };</PRE>
  283. <PRE>
  284.        my_perl = perl_alloc();
  285.        perl_construct( my_perl );</PRE>
  286. <PRE>
  287.        perl_parse(my_perl, NULL, 3, embedding, NULL);
  288.        perl_run(my_perl);</PRE>
  289. <PRE>
  290.        /** Treat $a as an integer **/
  291.        eval_pv("$a = 3; $a **= 2", TRUE);
  292.        printf("a = %d\n", SvIV(get_sv("a", FALSE)));</PRE>
  293. <PRE>
  294.        /** Treat $a as a float **/
  295.        eval_pv("$a = 3.14; $a **= 2", TRUE);
  296.        printf("a = %f\n", SvNV(get_sv("a", FALSE)));</PRE>
  297. <PRE>
  298.        /** Treat $a as a string **/
  299.        eval_pv("$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);", TRUE);
  300.        printf("a = %s\n", SvPV(get_sv("a", FALSE), n_a));</PRE>
  301. <PRE>
  302.        perl_destruct(my_perl);
  303.        perl_free(my_perl);
  304.    }</PRE>
  305. <P>All of those strange functions with <EM>sv</EM> in their names help convert Perl scalars to C types.  They're described in <A HREF="../../lib/Pod/perlguts.html">the perlguts manpage</A> and <A HREF="../../lib/Pod/perlapi.html">the perlapi manpage</A>.</P>
  306. <P>If you compile and run <EM>string.c</EM>, you'll see the results of using
  307. <EM>SvIV()</EM> to create an <A HREF="../../lib/Pod/perlfunc.html#item_int"><CODE>int</CODE></A>, <EM>SvNV()</EM> to create a <CODE>float</CODE>, and
  308. <EM>SvPV()</EM> to create a string:</P>
  309. <PRE>
  310.    a = 9
  311.    a = 9.859600
  312.    a = Just Another Perl Hacker</PRE>
  313. <P>In the example above, we've created a global variable to temporarily
  314. store the computed value of our eval'd expression.  It is also
  315. possible and in most cases a better strategy to fetch the return value
  316. from <EM>eval_pv()</EM> instead.  Example:</P>
  317. <PRE>
  318.    ...
  319.    STRLEN n_a;
  320.    SV *val = eval_pv("reverse 'rekcaH lreP rehtonA tsuJ'", TRUE);
  321.    printf("%s\n", SvPV(val,n_a));
  322.    ...</PRE>
  323. <P>This way, we avoid namespace pollution by not creating global
  324. variables and we've simplified our code as well.</P>
  325. <P>
  326. <H2><A NAME="performing perl pattern matches and substitutions from your c program">Performing Perl pattern matches and substitutions from your C program</A></H2>
  327. <P>The <EM>eval_sv()</EM> function lets us evaluate strings of Perl code, so we can
  328. define some functions that use it to ``specialize'' in matches and
  329. substitutions: <EM>match()</EM>, <EM>substitute()</EM>, and <EM>matches()</EM>.</P>
  330. <PRE>
  331.    I32 match(SV *string, char *pattern);</PRE>
  332. <P>Given a string and a pattern (e.g., <CODE>m/clasp/</CODE> or <CODE>/\b\w*\b/</CODE>, which
  333. in your C program might appear as ``/\\b\\w*\\b/''), <CODE>match()</CODE>
  334. returns 1 if the string matches the pattern and 0 otherwise.</P>
  335. <PRE>
  336.    int substitute(SV **string, char *pattern);</PRE>
  337. <P>Given a pointer to an <A HREF="../../lib/Pod/perlguts.html#item_SV"><CODE>SV</CODE></A> and an <CODE>=~</CODE> operation (e.g.,
  338. <CODE>s/bob/robert/g</CODE> or <CODE>tr[A-Z][a-z]</CODE>), <CODE>substitute()</CODE> modifies the string
  339. within the <A HREF="../../lib/Pod/perlguts.html#item_AV"><CODE>AV</CODE></A> at according to the operation, returning the number of substitutions
  340. made.</P>
  341. <PRE>
  342.    int matches(SV *string, char *pattern, AV **matches);</PRE>
  343. <P>Given an <A HREF="../../lib/Pod/perlguts.html#item_SV"><CODE>SV</CODE></A>, a pattern, and a pointer to an empty <A HREF="../../lib/Pod/perlguts.html#item_AV"><CODE>AV</CODE></A>,
  344. <CODE>matches()</CODE> evaluates <CODE>$string =~ $pattern</CODE> in an array context, and
  345. fills in <EM>matches</EM> with the array elements, returning the number of matches found.</P>
  346. <P>Here's a sample program, <EM>match.c</EM>, that uses all three (long lines have
  347. been wrapped here):</P>
  348. <PRE>
  349.  #include <EXTERN.h>
  350.  #include <perl.h></PRE>
  351. <PRE>
  352.  /** my_eval_sv(code, error_check)
  353.  ** kinda like eval_sv(), 
  354.  ** but we pop the return value off the stack 
  355.  **/
  356.  SV* my_eval_sv(SV *sv, I32 croak_on_error)
  357.  {
  358.      dSP;
  359.      SV* retval;
  360.      STRLEN n_a;</PRE>
  361. <PRE>
  362.      PUSHMARK(SP);
  363.      eval_sv(sv, G_SCALAR);</PRE>
  364. <PRE>
  365.      SPAGAIN;
  366.      retval = POPs;
  367.      PUTBACK;</PRE>
  368. <PRE>
  369.      if (croak_on_error && SvTRUE(ERRSV))
  370.         croak(SvPVx(ERRSV, n_a));</PRE>
  371. <PRE>
  372.      return retval;
  373.  }</PRE>
  374. <PRE>
  375.  /** match(string, pattern)
  376.  **
  377.  ** Used for matches in a scalar context.
  378.  **
  379.  ** Returns 1 if the match was successful; 0 otherwise.
  380.  **/</PRE>
  381. <PRE>
  382.  I32 match(SV *string, char *pattern)
  383.  {
  384.      SV *command = NEWSV(1099, 0), *retval;
  385.      STRLEN n_a;</PRE>
  386. <PRE>
  387.      sv_setpvf(command, "my $string = '%s'; $string =~ %s",
  388.               SvPV(string,n_a), pattern);</PRE>
  389. <PRE>
  390.      retval = my_eval_sv(command, TRUE);
  391.      SvREFCNT_dec(command);</PRE>
  392. <PRE>
  393.      return SvIV(retval);
  394.  }</PRE>
  395. <PRE>
  396.  /** substitute(string, pattern)
  397.  **
  398.  ** Used for =~ operations that modify their left-hand side (s/// and tr///)
  399.  **
  400.  ** Returns the number of successful matches, and
  401.  ** modifies the input string if there were any.
  402.  **/</PRE>
  403. <PRE>
  404.  I32 substitute(SV **string, char *pattern)
  405.  {
  406.      SV *command = NEWSV(1099, 0), *retval;
  407.      STRLEN n_a;</PRE>
  408. <PRE>
  409.      sv_setpvf(command, "$string = '%s'; ($string =~ %s)",
  410.               SvPV(*string,n_a), pattern);</PRE>
  411. <PRE>
  412.      retval = my_eval_sv(command, TRUE);
  413.      SvREFCNT_dec(command);</PRE>
  414. <PRE>
  415.      *string = get_sv("string", FALSE);
  416.      return SvIV(retval);
  417.  }</PRE>
  418. <PRE>
  419.  /** matches(string, pattern, matches)
  420.  **
  421.  ** Used for matches in an array context.
  422.  **
  423.  ** Returns the number of matches,
  424.  ** and fills in **matches with the matching substrings
  425.  **/</PRE>
  426. <PRE>
  427.  I32 matches(SV *string, char *pattern, AV **match_list)
  428.  {
  429.      SV *command = NEWSV(1099, 0);
  430.      I32 num_matches;
  431.      STRLEN n_a;</PRE>
  432. <PRE>
  433.      sv_setpvf(command, "my $string = '%s'; @array = ($string =~ %s)",
  434.               SvPV(string,n_a), pattern);</PRE>
  435. <PRE>
  436.      my_eval_sv(command, TRUE);
  437.      SvREFCNT_dec(command);</PRE>
  438. <PRE>
  439.      *match_list = get_av("array", FALSE);
  440.      num_matches = av_len(*match_list) + 1; /** assume $[ is 0 **/</PRE>
  441. <PRE>
  442.      return num_matches;
  443.  }</PRE>
  444. <PRE>
  445.  main (int argc, char **argv, char **env)
  446.  {
  447.      PerlInterpreter *my_perl = perl_alloc();
  448.      char *embedding[] = { "", "-e", "0" };
  449.      AV *match_list;
  450.      I32 num_matches, i;
  451.      SV *text = NEWSV(1099,0);
  452.      STRLEN n_a;</PRE>
  453. <PRE>
  454.      perl_construct(my_perl);
  455.      perl_parse(my_perl, NULL, 3, embedding, NULL);</PRE>
  456. <PRE>
  457.      sv_setpv(text, "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");</PRE>
  458. <PRE>
  459.      if (match(text, "m/quarter/")) /** Does text contain 'quarter'? **/
  460.         printf("match: Text contains the word 'quarter'.\n\n");
  461.      else
  462.         printf("match: Text doesn't contain the word 'quarter'.\n\n");</PRE>
  463. <PRE>
  464.      if (match(text, "m/eighth/")) /** Does text contain 'eighth'? **/
  465.         printf("match: Text contains the word 'eighth'.\n\n");
  466.      else
  467.         printf("match: Text doesn't contain the word 'eighth'.\n\n");</PRE>
  468. <PRE>
  469.      /** Match all occurrences of /wi../ **/
  470.      num_matches = matches(text, "m/(wi..)/g", &match_list);
  471.      printf("matches: m/(wi..)/g found %d matches...\n", num_matches);</PRE>
  472. <PRE>
  473.      for (i = 0; i < num_matches; i++)
  474.         printf("match: %s\n", SvPV(*av_fetch(match_list, i, FALSE),n_a));
  475.      printf("\n");</PRE>
  476. <PRE>
  477.      /** Remove all vowels from text **/
  478.      num_matches = substitute(&text, "s/[aeiou]//gi");
  479.      if (num_matches) {
  480.         printf("substitute: s/[aeiou]//gi...%d substitutions made.\n",
  481.                num_matches);
  482.         printf("Now text is: %s\n\n", SvPV(text,n_a));
  483.      }</PRE>
  484. <PRE>
  485.      /** Attempt a substitution **/
  486.      if (!substitute(&text, "s/Perl/C/")) {
  487.         printf("substitute: s/Perl/C...No substitution made.\n\n");
  488.      }</PRE>
  489. <PRE>
  490.      SvREFCNT_dec(text);
  491.      PL_perl_destruct_level = 1;
  492.      perl_destruct(my_perl);
  493.      perl_free(my_perl);
  494.  }</PRE>
  495. <P>which produces the output (again, long lines have been wrapped here)</P>
  496. <PRE>
  497.    match: Text contains the word 'quarter'.</PRE>
  498. <PRE>
  499.    match: Text doesn't contain the word 'eighth'.</PRE>
  500. <PRE>
  501.    matches: m/(wi..)/g found 2 matches...
  502.    match: will
  503.    match: with</PRE>
  504. <PRE>
  505.    substitute: s/[aeiou]//gi...139 substitutions made.
  506.    Now text is: Whn h s t  cnvnnc str nd th bll cms t sm mnt lk 76 cnts,
  507.    Mynrd s wr tht thr s smthng h *shld* d, smthng tht wll nbl hm t gt bck
  508.    qrtr, bt h hs n d *wht*.  H fmbls thrgh hs rd sqzy chngprs nd gvs th by
  509.    thr xtr pnns wth hs dllr, hpng tht h mght lck nt th crrct mnt.  Th by gvs
  510.    hm bck tw f hs wn pnns nd thn th bg shny qrtr tht s hs prz. -RCHH</PRE>
  511. <PRE>
  512.    substitute: s/Perl/C...No substitution made.</PRE>
  513. <P>
  514. <H2><A NAME="fiddling with the perl stack from your c program">Fiddling with the Perl stack from your C program</A></H2>
  515. <P>When trying to explain stacks, most computer science textbooks mumble
  516. something about spring-loaded columns of cafeteria plates: the last
  517. thing you pushed on the stack is the first thing you pop off.  That'll
  518. do for our purposes: your C program will push some arguments onto ``the Perl
  519. stack'', shut its eyes while some magic happens, and then pop the
  520. results--the return value of your Perl subroutine--off the stack.</P>
  521. <P>First you'll need to know how to convert between C types and Perl
  522. types, with <CODE>newSViv()</CODE> and <CODE>sv_setnv()</CODE> and <CODE>newAV()</CODE> and all their
  523. friends.  They're described in <A HREF="../../lib/Pod/perlguts.html">the perlguts manpage</A> and <A HREF="../../lib/Pod/perlapi.html">the perlapi manpage</A>.</P>
  524. <P>Then you'll need to know how to manipulate the Perl stack.  That's
  525. described in <A HREF="../../lib/Pod/perlcall.html">the perlcall manpage</A>.</P>
  526. <P>Once you've understood those, embedding Perl in C is easy.</P>
  527. <P>Because C has no builtin function for integer exponentiation, let's
  528. make Perl's ** operator available to it (this is less useful than it
  529. sounds, because Perl implements ** with C's <EM>pow()</EM> function).  First
  530. I'll create a stub exponentiation function in <EM>power.pl</EM>:</P>
  531. <PRE>
  532.     sub expo {
  533.         my ($a, $b) = @_;
  534.         return $a ** $b;
  535.     }</PRE>
  536. <P>Now I'll create a C program, <EM>power.c</EM>, with a function
  537. <EM>PerlPower()</EM> that contains all the perlguts necessary to push the
  538. two arguments into <EM>expo()</EM> and to pop the return value out.  Take a
  539. deep breath...</P>
  540. <PRE>
  541.     #include <EXTERN.h>
  542.     #include <perl.h></PRE>
  543. <PRE>
  544.     static PerlInterpreter *my_perl;</PRE>
  545. <PRE>
  546.     static void
  547.     PerlPower(int a, int b)
  548.     {
  549.       dSP;                            /* initialize stack pointer      */
  550.       ENTER;                          /* everything created after here */
  551.       SAVETMPS;                       /* ...is a temporary variable.   */
  552.       PUSHMARK(SP);                   /* remember the stack pointer    */
  553.       XPUSHs(sv_2mortal(newSViv(a))); /* push the base onto the stack  */
  554.       XPUSHs(sv_2mortal(newSViv(b))); /* push the exponent onto stack  */
  555.       PUTBACK;                      /* make local stack pointer global */
  556.       call_pv("expo", G_SCALAR);      /* call the function             */
  557.       SPAGAIN;                        /* refresh stack pointer         */
  558.                                     /* pop the return value from stack */
  559.       printf ("%d to the %dth power is %d.\n", a, b, POPi);
  560.       PUTBACK;
  561.       FREETMPS;                       /* free that return value        */
  562.       LEAVE;                       /* ...and the XPUSHed "mortal" args.*/
  563.     }</PRE>
  564. <PRE>
  565.     int main (int argc, char **argv, char **env)
  566.     {
  567.       char *my_argv[] = { "", "power.pl" };</PRE>
  568. <PRE>
  569.       my_perl = perl_alloc();
  570.       perl_construct( my_perl );</PRE>
  571. <PRE>
  572.       perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL);
  573.       perl_run(my_perl);</PRE>
  574. <PRE>
  575.       PerlPower(3, 4);                      /*** Compute 3 ** 4 ***/</PRE>
  576. <PRE>
  577.       perl_destruct(my_perl);
  578.       perl_free(my_perl);
  579.     }</PRE>
  580. <P>Compile and run:</P>
  581. <PRE>
  582.     % cc -o power power.c `perl -MExtUtils::Embed -e ccopts -e ldopts`</PRE>
  583. <PRE>
  584.     % power
  585.     3 to the 4th power is 81.</PRE>
  586. <P>
  587. <H2><A NAME="maintaining a persistent interpreter">Maintaining a persistent interpreter</A></H2>
  588. <P>When developing interactive and/or potentially long-running
  589. applications, it's a good idea to maintain a persistent interpreter
  590. rather than allocating and constructing a new interpreter multiple
  591. times.  The major reason is speed: since Perl will only be loaded into
  592. memory once.</P>
  593. <P>However, you have to be more cautious with namespace and variable
  594. scoping when using a persistent interpreter.  In previous examples
  595. we've been using global variables in the default package <CODE>main</CODE>.  We
  596. knew exactly what code would be run, and assumed we could avoid
  597. variable collisions and outrageous symbol table growth.</P>
  598. <P>Let's say your application is a server that will occasionally run Perl
  599. code from some arbitrary file.  Your server has no way of knowing what
  600. code it's going to run.  Very dangerous.</P>
  601. <P>If the file is pulled in by <CODE>perl_parse()</CODE>, compiled into a newly
  602. constructed interpreter, and subsequently cleaned out with
  603. <CODE>perl_destruct()</CODE> afterwards, you're shielded from most namespace
  604. troubles.</P>
  605. <P>One way to avoid namespace collisions in this scenario is to translate
  606. the filename into a guaranteed-unique package name, and then compile
  607. the code into that package using <A HREF="../../lib/Pod/perlfunc.html#eval">eval in the perlfunc manpage</A>.  In the example
  608. below, each file will only be compiled once.  Or, the application
  609. might choose to clean out the symbol table associated with the file
  610. after it's no longer needed.  Using <A HREF="../../lib/Pod/perlapi.html#call_argv">call_argv in the perlapi manpage</A>, We'll
  611. call the subroutine <CODE>Embed::Persistent::eval_file</CODE> which lives in the
  612. file <CODE>persistent.pl</CODE> and pass the filename and boolean cleanup/cache
  613. flag as arguments.</P>
  614. <P>Note that the process will continue to grow for each file that it
  615. uses.  In addition, there might be <CODE>AUTOLOAD</CODE>ed subroutines and other
  616. conditions that cause Perl's symbol table to grow.  You might want to
  617. add some logic that keeps track of the process size, or restarts
  618. itself after a certain number of requests, to ensure that memory
  619. consumption is minimized.  You'll also want to scope your variables
  620. with <A HREF="../../lib/Pod/perlfunc.html#my">my in the perlfunc manpage</A> whenever possible.</P>
  621. <PRE>
  622.  package Embed::Persistent;
  623.  #persistent.pl</PRE>
  624. <PRE>
  625.  use strict;
  626.  our %Cache;
  627.  use Symbol qw(delete_package);</PRE>
  628. <PRE>
  629.  sub valid_package_name {
  630.      my($string) = @_;
  631.      $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;
  632.      # second pass only for words starting with a digit
  633.      $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg;</PRE>
  634. <PRE>
  635.      # Dress it up as a real package name
  636.      $string =~ s|/|::|g;
  637.      return "Embed" . $string;
  638.  }</PRE>
  639. <PRE>
  640.  sub eval_file {
  641.      my($filename, $delete) = @_;
  642.      my $package = valid_package_name($filename);
  643.      my $mtime = -M $filename;
  644.      if(defined $Cache{$package}{mtime}
  645.         &&
  646.         $Cache{$package}{mtime} <= $mtime)
  647.      {
  648.         # we have compiled this subroutine already,
  649.         # it has not been updated on disk, nothing left to do
  650.         print STDERR "already compiled $package->handler\n";
  651.      }
  652.      else {
  653.         local *FH;
  654.         open FH, $filename or die "open '$filename' $!";
  655.         local($/) = undef;
  656.         my $sub = <FH>;
  657.         close FH;</PRE>
  658. <PRE>
  659.         #wrap the code into a subroutine inside our unique package
  660.         my $eval = qq{package $package; sub handler { $sub; }};
  661.         {
  662.             # hide our variables within this block
  663.             my($filename,$mtime,$package,$sub);
  664.             eval $eval;
  665.         }
  666.         die $@ if $@;</PRE>
  667. <PRE>
  668.         #cache it unless we're cleaning out each time
  669.         $Cache{$package}{mtime} = $mtime unless $delete;
  670.      }</PRE>
  671. <PRE>
  672.      eval {$package->handler;};
  673.      die $@ if $@;</PRE>
  674. <PRE>
  675.      delete_package($package) if $delete;</PRE>
  676. <PRE>
  677.      #take a look if you want
  678.      #print Devel::Symdump->rnew($package)->as_string, $/;
  679.  }</PRE>
  680. <PRE>
  681.  1;</PRE>
  682. <PRE>
  683.  __END__</PRE>
  684. <PRE>
  685.  /* persistent.c */
  686.  #include <EXTERN.h>
  687.  #include <perl.h></PRE>
  688. <PRE>
  689.  /* 1 = clean out filename's symbol table after each request, 0 = don't */
  690.  #ifndef DO_CLEAN
  691.  #define DO_CLEAN 0
  692.  #endif</PRE>
  693. <PRE>
  694.  static PerlInterpreter *perl = NULL;</PRE>
  695. <PRE>
  696.  int
  697.  main(int argc, char **argv, char **env)
  698.  {
  699.      char *embedding[] = { "", "persistent.pl" };
  700.      char *args[] = { "", DO_CLEAN, NULL };
  701.      char filename [1024];
  702.      int exitstatus = 0;
  703.      STRLEN n_a;</PRE>
  704. <PRE>
  705.      if((perl = perl_alloc()) == NULL) {
  706.         fprintf(stderr, "no memory!");
  707.         exit(1);
  708.      }
  709.      perl_construct(perl);</PRE>
  710. <PRE>
  711.      exitstatus = perl_parse(perl, NULL, 2, embedding, NULL);</PRE>
  712. <PRE>
  713.      if(!exitstatus) {
  714.         exitstatus = perl_run(perl);</PRE>
  715. <PRE>
  716.         while(printf("Enter file name: ") && gets(filename)) {</PRE>
  717. <PRE>
  718.             /* call the subroutine, passing it the filename as an argument */
  719.             args[0] = filename;
  720.             call_argv("Embed::Persistent::eval_file",
  721.                            G_DISCARD | G_EVAL, args);</PRE>
  722. <PRE>
  723.             /* check $@ */
  724.             if(SvTRUE(ERRSV))
  725.                 fprintf(stderr, "eval error: %s\n", SvPV(ERRSV,n_a));
  726.         }
  727.      }</PRE>
  728. <PRE>
  729.      PL_perl_destruct_level = 0;
  730.      perl_destruct(perl);
  731.      perl_free(perl);
  732.      exit(exitstatus);
  733.  }</PRE>
  734. <P>Now compile:</P>
  735. <PRE>
  736.  % cc -o persistent persistent.c `perl -MExtUtils::Embed -e ccopts -e ldopts`</PRE>
  737. <P>Here's a example script file:</P>
  738. <PRE>
  739.  #test.pl
  740.  my $string = "hello";
  741.  foo($string);</PRE>
  742. <PRE>
  743.  sub foo {
  744.      print "foo says: @_\n";
  745.  }</PRE>
  746. <P>Now run:</P>
  747. <PRE>
  748.  % persistent
  749.  Enter file name: test.pl
  750.  foo says: hello
  751.  Enter file name: test.pl
  752.  already compiled Embed::test_2epl->handler
  753.  foo says: hello
  754.  Enter file name: ^C</PRE>
  755. <P>
  756. <H2><A NAME="maintaining multiple interpreter instances">Maintaining multiple interpreter instances</A></H2>
  757. <P>Some rare applications will need to create more than one interpreter
  758. during a session.  Such an application might sporadically decide to
  759. release any resources associated with the interpreter.</P>
  760. <P>The program must take care to ensure that this takes place <EM>before</EM>
  761. the next interpreter is constructed.  By default, the global variable
  762. <CODE>PL_perl_destruct_level</CODE> is set to <CODE>0</CODE>, since extra cleaning isn't
  763. needed when a program has only one interpreter.</P>
  764. <P>Setting <CODE>PL_perl_destruct_level</CODE> to <CODE>1</CODE> makes everything squeaky clean:</P>
  765. <PRE>
  766.  PL_perl_destruct_level = 1;</PRE>
  767. <PRE>
  768.  while(1) {
  769.      ...
  770.      /* reset global variables here with PL_perl_destruct_level = 1 */
  771.      perl_construct(my_perl);
  772.      ...
  773.      /* clean and reset _everything_ during perl_destruct */
  774.      perl_destruct(my_perl);
  775.      perl_free(my_perl);
  776.      ...
  777.      /* let's go do it again! */
  778.  }</PRE>
  779. <P>When <EM>perl_destruct()</EM> is called, the interpreter's syntax parse tree
  780. and symbol tables are cleaned up, and global variables are reset.</P>
  781. <P>Now suppose we have more than one interpreter instance running at the
  782. same time.  This is feasible, but only if you used the
  783. <CODE>-DMULTIPLICITY</CODE> flag when building Perl.  By default, that sets
  784. <CODE>PL_perl_destruct_level</CODE> to <CODE>1</CODE>.</P>
  785. <P>Let's give it a try:</P>
  786. <PRE>
  787.  #include <EXTERN.h>
  788.  #include <perl.h></PRE>
  789. <PRE>
  790.  /* we're going to embed two interpreters */
  791.  /* we're going to embed two interpreters */</PRE>
  792. <PRE>
  793.  #define SAY_HELLO "-e", "print qq(Hi, I'm $^X\n)"</PRE>
  794. <PRE>
  795.  int main(int argc, char **argv, char **env)
  796.  {
  797.      PerlInterpreter
  798.          *one_perl = perl_alloc(),
  799.          *two_perl = perl_alloc();
  800.      char *one_args[] = { "one_perl", SAY_HELLO };
  801.      char *two_args[] = { "two_perl", SAY_HELLO };</PRE>
  802. <PRE>
  803.      perl_construct(one_perl);
  804.      perl_construct(two_perl);</PRE>
  805. <PRE>
  806.      perl_parse(one_perl, NULL, 3, one_args, (char **)NULL);
  807.      perl_parse(two_perl, NULL, 3, two_args, (char **)NULL);</PRE>
  808. <PRE>
  809.      perl_run(one_perl);
  810.      perl_run(two_perl);</PRE>
  811. <PRE>
  812.      perl_destruct(one_perl);
  813.      perl_destruct(two_perl);</PRE>
  814. <PRE>
  815.      perl_free(one_perl);
  816.      perl_free(two_perl);
  817.  }</PRE>
  818. <P>Compile as usual:</P>
  819. <PRE>
  820.  % cc -o multiplicity multiplicity.c `perl -MExtUtils::Embed -e ccopts -e ldopts`</PRE>
  821. <P>Run it, Run it:</P>
  822. <PRE>
  823.  % multiplicity
  824.  Hi, I'm one_perl
  825.  Hi, I'm two_perl</PRE>
  826. <P>
  827. <H2><A NAME="using perl modules, which themselves use c libraries, from your c program">Using Perl modules, which themselves use C libraries, from your C program</A></H2>
  828. <P>If you've played with the examples above and tried to embed a script
  829. that <EM>use()</EM>s a Perl module (such as <EM>Socket</EM>) which itself uses a C or C++ library,
  830. this probably happened:</P>
  831. <PRE>
  832.  Can't load module Socket, dynamic loading not available in this perl.
  833.   (You may need to build a new perl executable which either supports
  834.   dynamic loading or has the Socket module statically linked into it.)</PRE>
  835. <P>What's wrong?</P>
  836. <P>Your interpreter doesn't know how to communicate with these extensions
  837. on its own.  A little glue will help.  Up until now you've been
  838. calling <EM>perl_parse()</EM>, handing it NULL for the second argument:</P>
  839. <PRE>
  840.  perl_parse(my_perl, NULL, argc, my_argv, NULL);</PRE>
  841. <P>That's where the glue code can be inserted to create the initial contact between
  842. Perl and linked C/C++ routines.  Let's take a look some pieces of <EM>perlmain.c</EM>
  843. to see how Perl does this:</P>
  844. <PRE>
  845.  #ifdef __cplusplus
  846.  #  define EXTERN_C extern "C"
  847.  #else
  848.  #  define EXTERN_C extern
  849.  #endif</PRE>
  850. <PRE>
  851.  static void xs_init (void);</PRE>
  852. <PRE>
  853.  EXTERN_C void boot_DynaLoader (CV* cv);
  854.  EXTERN_C void boot_Socket (CV* cv);</PRE>
  855. <PRE>
  856.  EXTERN_C void
  857.  xs_init()
  858.  {
  859.         char *file = __FILE__;
  860.         /* DynaLoader is a special case */
  861.         newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
  862.         newXS("Socket::bootstrap", boot_Socket, file);
  863.  }</PRE>
  864. <P>Simply put: for each extension linked with your Perl executable
  865. (determined during its initial configuration on your
  866. computer or when adding a new extension),
  867. a Perl subroutine is created to incorporate the extension's
  868. routines.  Normally, that subroutine is named
  869. <EM>Module::bootstrap()</EM> and is invoked when you say <EM>use Module</EM>.  In
  870. turn, this hooks into an XSUB, <EM>boot_Module</EM>, which creates a Perl
  871. counterpart for each of the extension's XSUBs.  Don't worry about this
  872. part; leave that to the <EM>xsubpp</EM> and extension authors.  If your
  873. extension is dynamically loaded, DynaLoader creates <EM>Module::bootstrap()</EM>
  874. for you on the fly.  In fact, if you have a working DynaLoader then there
  875. is rarely any need to link in any other extensions statically.</P>
  876. <P>Once you have this code, slap it into the second argument of <EM>perl_parse()</EM>:</P>
  877. <PRE>
  878.  perl_parse(my_perl, xs_init, argc, my_argv, NULL);</PRE>
  879. <P>Then compile:</P>
  880. <PRE>
  881.  % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`</PRE>
  882. <PRE>
  883.  % interp
  884.    use Socket;
  885.    use SomeDynamicallyLoadedModule;</PRE>
  886. <PRE>
  887.    print "Now I can use extensions!\n"'</PRE>
  888. <P><STRONG>ExtUtils::Embed</STRONG> can also automate writing the <EM>xs_init</EM> glue code.</P>
  889. <PRE>
  890.  % perl -MExtUtils::Embed -e xsinit -- -o perlxsi.c
  891.  % cc -c perlxsi.c `perl -MExtUtils::Embed -e ccopts`
  892.  % cc -c interp.c  `perl -MExtUtils::Embed -e ccopts`
  893.  % cc -o interp perlxsi.o interp.o `perl -MExtUtils::Embed -e ldopts`</PRE>
  894. <P>Consult <A HREF="../../lib/Pod/perlxs.html">the perlxs manpage</A>, <A HREF="../../lib/Pod/perlguts.html">the perlguts manpage</A>, and <A HREF="../../lib/Pod/perlapi.html">the perlapi manpage</A> for more details.</P>
  895. <P>
  896. <HR>
  897. <H1><A NAME="embedding perl under win32">Embedding Perl under Win32</A></H1>
  898. <P>At the time of this writing (5.004), there are two versions of Perl
  899. which run under Win32.  (The two versions are merging in 5.005.)
  900. Interfacing to ActiveState's Perl library is quite different from the
  901. examples in this documentation, as significant changes were made to
  902. the internal Perl API.  However, it is possible to embed ActiveState's
  903. Perl runtime.  For details, see the Perl for Win32 FAQ at
  904. <A HREF="http://www.perl.com/CPAN/doc/FAQs/win32/perlwin32faq.html.">http://www.perl.com/CPAN/doc/FAQs/win32/perlwin32faq.html.</A></P>
  905. <P>With the ``official'' Perl version 5.004 or higher, all the examples
  906. within this documentation will compile and run untouched, although
  907. the build process is slightly different between Unix and Win32.</P>
  908. <P>For starters, backticks don't work under the Win32 native command shell.
  909. The ExtUtils::Embed kit on CPAN ships with a script called
  910. <STRONG>genmake</STRONG>, which generates a simple makefile to build a program from
  911. a single C source file.  It can be used like this:</P>
  912. <PRE>
  913.  C:\ExtUtils-Embed\eg> perl genmake interp.c
  914.  C:\ExtUtils-Embed\eg> nmake
  915.  C:\ExtUtils-Embed\eg> interp -e "print qq{I'm embedded in Win32!\n}"</PRE>
  916. <P>You may wish to use a more robust environment such as the Microsoft
  917. Developer Studio.  In this case, run this to generate perlxsi.c:</P>
  918. <PRE>
  919.  perl -MExtUtils::Embed -e xsinit</PRE>
  920. <P>Create a new project and Insert -> Files into Project: perlxsi.c,
  921. perl.lib, and your own source files, e.g. interp.c.  Typically you'll
  922. find perl.lib in <STRONG>C:\perl\lib\CORE</STRONG>, if not, you should see the
  923. <STRONG>CORE</STRONG> directory relative to <CODE>perl -V:archlib</CODE>.  The studio will
  924. also need this path so it knows where to find Perl include files.
  925. This path can be added via the Tools -> Options -> Directories menu.
  926. Finally, select Build -> Build interp.exe and you're ready to go.</P>
  927. <P>
  928. <HR>
  929. <H1><A NAME="moral">MORAL</A></H1>
  930. <P>You can sometimes <EM>write faster code</EM> in C, but
  931. you can always <EM>write code faster</EM> in Perl.  Because you can use
  932. each from the other, combine them as you wish.</P>
  933. <P>
  934. <HR>
  935. <H1><A NAME="author">AUTHOR</A></H1>
  936. <P>Jon Orwant <<EM><A HREF="mailto:orwant@tpj.com">orwant@tpj.com</A></EM>> and Doug MacEachern
  937. <<EM><A HREF="mailto:dougm@osf.org">dougm@osf.org</A></EM>>, with small contributions from Tim Bunce, Tom
  938. Christiansen, Guy Decoux, Hallvard Furuseth, Dov Grobgeld, and Ilya
  939. Zakharevich.</P>
  940. <P>Doug MacEachern has an article on embedding in Volume 1, Issue 4 of
  941. The Perl Journal (http://tpj.com).  Doug is also the developer of the
  942. most widely-used Perl embedding: the mod_perl system
  943. (perl.apache.org), which embeds Perl in the Apache web server.
  944. Oracle, Binary Evolution, ActiveState, and Ben Sugars's nsapi_perl
  945. have used this model for Oracle, Netscape and Internet Information
  946. Server Perl plugins.</P>
  947. <P>July 22, 1998</P>
  948. <P>
  949. <HR>
  950. <H1><A NAME="copyright">COPYRIGHT</A></H1>
  951. <P>Copyright (C) 1995, 1996, 1997, 1998 Doug MacEachern and Jon Orwant.  All
  952. Rights Reserved.</P>
  953. <P>Permission is granted to make and distribute verbatim copies of this
  954. documentation provided the copyright notice and this permission notice are
  955. preserved on all copies.</P>
  956. <P>Permission is granted to copy and distribute modified versions of this
  957. documentation under the conditions for verbatim copying, provided also
  958. that they are marked clearly as modified versions, that the authors'
  959. names and title are unchanged (though subtitles and additional
  960. authors' names may be added), and that the entire resulting derived
  961. work is distributed under the terms of a permission notice identical
  962. to this one.</P>
  963. <P>Permission is granted to copy and distribute translations of this
  964. documentation into another language, under the above conditions for
  965. modified versions.</P>
  966. <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
  967. <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
  968. <STRONG><P CLASS=block> perlembed - how to embed perl in your C program</P></STRONG>
  969. </TD></TR>
  970. </TABLE>
  971.  
  972. </BODY>
  973.  
  974. </HTML>
  975.