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