File: perlembed.html

package info (click to toggle)
perl-doc-html 5.14.0-1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 38,588 kB
  • sloc: xml: 36; makefile: 10
file content (907 lines) | stat: -rw-r--r-- 95,214 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>perlembed - perldoc.perl.org</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta http-equiv="Content-Language" content="en-gb">
  <link rel="search" type="application/opensearchdescription+xml" title="Search perldoc.perl.org" href="/static/search.xml"/>
  <link href="static/css-20100830.css" rel="stylesheet" rev="stylesheet" type="text/css" media="screen">
  <link href="static/exploreperl.css" rel="stylesheet" rev="stylesheet" type="text/css">
</head>

<body onLoad="perldoc.startup();" onPageShow="if (event.persisted) perldoc.startup();">
    <div id="page">
      
      <div id="header">
	<div id="homepage_link">
	  <a href="index.html"></a>
	</div>
	<div id="strapline">
	  Perl Programming Documentation
	</div>
	<div id="download_link" class="download">
	  <a href="http://www.perl.org/get.html">Download Perl</a>
	</div>
	<div id="explore_link" class="download">
	  <a id="explore_anchor" href="#">Explore</a>
	</div>
      </div>
      
      <div id="body">
        <div id="left_column">
          <div class="side_group">
            
	    <div class="side_panel doc_panel">
              <p>Manual</p>
              <ul>
                <li><a href="index-overview.html">Overview</a>
                <li><a href="index-tutorials.html">Tutorials</a>
                <li><a href="index-faq.html">FAQs</a>
                <li><a href="index-history.html">History / Changes</a>
                <li><a href="index-licence.html">License</a>
              </ul>
            </div>
            <div class="side_panel doc_panel">
              <p>Reference</p>
              <ul>
                <li><a href="index-language.html">Language</a>
                <li><a href="index-functions.html">Functions</a>
                <li><a href="perlop.html">Operators</a>
                <li><a href="perlvar.html">Special Variables</a>
                <li><a href="index-pragmas.html">Pragmas</a>
                <li><a href="index-utilities.html">Utilities</a>
                <li><a href="index-internals.html">Internals</a>
                <li><a href="index-platforms.html">Platform Specific</a>
              </ul>
            </div>
            <div class="side_panel doc_panel">
              <p>Modules</p>
              <ul>
		<li>
		
                
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		
                  
		
		
                    <a href="index-modules-A.html">A</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-B.html">B</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-C.html">C</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-D.html">D</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-E.html">E</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-F.html">F</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-G.html">G</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-H.html">H</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-I.html">I</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-L.html">L</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-M.html">M</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-N.html">N</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-O.html">O</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-P.html">P</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-S.html">S</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-T.html">T</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-U.html">U</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-X.html">X</a>
                    
                
              </ul>
            </div>
            
	      <div class="side_panel doc_panel">
		<p>Tools</p>
		<ul>
		  <li><a href="preferences.html">Preferences</a>
		</ul>
	      </div>
            
          </div>
        </div>
        <div id="centre_column">
          <div id="content_header">
            <div id="title_bar">
              <div id="page_name">
                <h1>perlembed</h1>
              </div>
              <div id="perl_version">
                Perl 5 version 14.0 documentation
              </div>
              <div class="page_links" id="page_links_top">
                <a href="#" onClick="toolbar.goToTop();return false;">Go to top</a>
		
              </div>
	      <div class="page_links" id="page_links_bottom">
		
                  <a href="#" id="page_index_toggle">Show page index</a> &bull;
		
                <a href="#" id="recent_pages_toggle">Show recent pages</a>		
	      </div>
	      <div id="search_form">
		<form action="search.html" method="GET" id="search">
		  <input type="text" name="q" id="search_box" alt="Search">
		</form>
	      </div>
            </div>
            <div id="breadcrumbs">
                
    <a href="index.html">Home</a> &gt;
    
      
        <a href="index-internals.html">Internals and C language interface</a> &gt;
      
    
    perlembed
  

            </div>
          </div>
          <div id="content_body">
	    <!--[if lt IE 7]>
 <div class="noscript">
   <p>
     <strong>It looks like you're using Internet Explorer 6. This is a very old
     browser which does not offer full support for modern websites.</strong>
   </p>
   <p>
     Unfortunately this means that this website will not work on
     your computer.
   </p>
   <p>
     Don't miss out though! To view the site (and get a better experience from
     many other websites), simply upgrade to
     <a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Internet
Explorer 8</a>
     or download an alternative browser such as
     <a href="http://www.mozilla.com/en-US/firefox/firefox.html">Firefox</a>,
     <a href="http://www.apple.com/safari/download/">Safari</a>, or
     <a href="http://www.google.co.uk/chrome">Google Chrome</a>.
   </p>
   <p>
     All of these browsers are free. If you're using a PC at work, you may
     need to contact your IT administrator.
   </p>
 </div>
<![endif]-->
	    <noscript>
	      <div class="noscript">
	      <p>
                <strong>Please note: Many features of this site require JavaScript. You appear to have JavaScript disabled,
	        or are running a non-JavaScript capable web browser.</strong>
	      </p>
	      <p>
		To get the best experience, please enable JavaScript or download a modern web browser such as <a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Internet Explorer 8</a>, <a href="http://www.mozilla.com/en-US/firefox/firefox.html">Firefox</a>, <a href="http://www.apple.com/safari/download/">Safari</a>, or <a href="http://www.google.co.uk/chrome">Google Chrome</a>.
              </p>
	      </div>
	    </noscript>

	    <div id="recent_pages" class="hud_container">
	      <div id="recent_pages_header" class="hud_header">
		<div id="recent_pages_close" class="hud_close"><a href="#" onClick="recentPages.hide();return false;"></a></div>
		<div id="recent_pages_title" class="hud_title"><span class="hud_span_top">Recently read</span></div>
		<div id="recent_pages_topright" class="hud_topright"></div>
	      </div>
	      <div id="recent_pages_content" class="hud_content">
	      </div>
	      <div id="recent_pages_footer" class="hud_footer">
		<div id="recent_pages_bottomleft" class="hud_bottomleft"></div>
		<div id="recent_pages_bottom" class="hud_bottom"><span class="hud_span_bottom"></span></div>
		<div id="recent_pages_resize" class="hud_resize"></div>
	      </div>
	    </div>
  
	    <div id="from_search"></div>
            <h1>perlembed</h1>


  <!--    -->
<ul><li><a href="#NAME">NAME</a><li><a href="#DESCRIPTION">DESCRIPTION</a><ul><li><a href="#PREAMBLE">PREAMBLE</a><li><a href="#ROADMAP">ROADMAP</a><li><a href="#Compiling-your-C-program">Compiling your C program</a><li><a href="#Adding-a-Perl-interpreter-to-your-C-program">Adding a Perl interpreter to your C program</a><li><a href="#Calling-a-Perl-subroutine-from-your-C-program">Calling a Perl subroutine from your C program</a><li><a href="#Evaluating-a-Perl-statement-from-your-C-program">Evaluating a Perl statement from your C program</a><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><a href="#Fiddling-with-the-Perl-stack-from-your-C-program">Fiddling with the Perl stack from your C program</a><li><a href="#Maintaining-a-persistent-interpreter">Maintaining a persistent interpreter</a><li><a href="#Execution-of-END-blocks">Execution of END blocks</a><li><a href="#%240-assignments">$0 assignments</a><li><a href="#Maintaining-multiple-interpreter-instances">Maintaining multiple interpreter instances</a><li><a href="#Using-Perl-modules%2c-which-themselves-use-C-libraries%2c-from-your-C-program">Using Perl modules, which themselves use C libraries, from your C program</a></ul><li><a href="#Hiding-Perl_">Hiding Perl_</a><li><a href="#MORAL">MORAL</a><li><a href="#AUTHOR">AUTHOR</a><li><a href="#COPYRIGHT">COPYRIGHT</a></ul><a name="NAME"></a><h1>NAME</h1>
<p>perlembed - how to embed perl in your C program</p>
<a name="DESCRIPTION"></a><h1>DESCRIPTION</h1>
<a name="PREAMBLE"></a><h2>PREAMBLE</h2>
<p>Do you want to:</p>
<ul>
<li><a name="*Use-C-from-Perl%3f*"></a><b><b>Use C from Perl?</b></b>
<p>Read <a href="perlxstut.html">perlxstut</a>, <a href="perlxs.html">perlxs</a>, <a href="h2xs.html">h2xs</a>, <a href="perlguts.html">perlguts</a>, and <a href="perlapi.html">perlapi</a>.</p>
</li>
<li><a name="*Use-a-Unix-program-from-Perl%3f*"></a><b><b>Use a Unix program from Perl?</b></b>
<p>Read about back-quotes and about <code class="inline"><a class="l_k" href="functions/system.html">system</a></code> and <code class="inline"><a class="l_k" href="functions/exec.html">exec</a></code> in <a href="perlfunc.html">perlfunc</a>.</p>
</li>
<li><a name="*Use-Perl-from-Perl%3f*"></a><b><b>Use Perl from Perl?</b></b>
<p>Read about <a href="functions/do.html">do</a> and <a href="functions/eval.html">eval</a> and <a href="functions/require.html">require</a> 
and <a href="functions/use.html">use</a>.</p>
</li>
<li><a name="*Use-C-from-C%3f*"></a><b><b>Use C from C?</b></b>
<p>Rethink your design.</p>
</li>
<li><a name="*Use-Perl-from-C%3f*"></a><b><b>Use Perl from C?</b></b>
<p>Read on...</p>
</li>
</ul>
<a name="ROADMAP"></a><h2>ROADMAP</h2>
<ul>
<li>
<p>Compiling your C program</p>
</li>
<li>
<p>Adding a Perl interpreter to your C program</p>
</li>
<li>
<p>Calling a Perl subroutine from your C program</p>
</li>
<li>
<p>Evaluating a Perl statement from your C program</p>
</li>
<li>
<p>Performing Perl pattern matches and substitutions from your C program</p>
</li>
<li>
<p>Fiddling with the Perl stack from your C program</p>
</li>
<li>
<p>Maintaining a persistent interpreter</p>
</li>
<li>
<p>Maintaining multiple interpreter instances</p>
</li>
<li>
<p>Using Perl modules, which themselves use C libraries, from your C program</p>
</li>
<li>
<p>Embedding Perl under Win32</p>
</li>
</ul>
<a name="Compiling-your-C-program"></a><h2>Compiling your C program</h2>
<p>If you have trouble compiling the scripts in this documentation,
you're not alone.  The cardinal rule: COMPILE THE PROGRAMS IN EXACTLY
THE SAME WAY THAT YOUR PERL WAS COMPILED.  (Sorry for yelling.)</p>
<p>Also, every C program that uses Perl must link in the <i>perl library</i>.
What's that, you ask?  Perl is itself written in C; the perl library
is the collection of compiled C programs that were used to create your
perl executable (<i>/usr/bin/perl</i> or equivalent).  (Corollary: you
can't use Perl from your C program unless Perl has been compiled on
your machine, or installed properly--that's why you shouldn't blithely
copy Perl executables from machine to machine without also copying the
<i>lib</i> directory.)</p>
<p>When you use Perl from C, your C program will--usually--allocate,
"run", and deallocate a <i>PerlInterpreter</i> object, which is defined by
the perl library.</p>
<p>If your copy of Perl is recent enough to contain this documentation
(version 5.002 or later), then the perl library (and <i>EXTERN.h</i> and
<i>perl.h</i>, which you'll also need) will reside in a directory
that looks like this:</p>
<pre class="verbatim"><ol><li>    /usr/local/lib/perl5/your_architecture_here/CORE</li></ol></pre><p>or perhaps just</p>
<pre class="verbatim"><ol><li>    /usr/local/lib/perl5/CORE</li></ol></pre><p>or maybe something like</p>
<pre class="verbatim"><ol><li>    /usr/opt/perl5/CORE</li></ol></pre><p>Execute this statement for a hint about where to find CORE:</p>
<pre class="verbatim"><ol><li>    <span class="w">perl</span> -<span class="w">MConfig</span> -e <span class="q">&#39;print $Config{archlib}&#39;</span></li></ol></pre><p>Here's how you'd compile the example in the next section,
<a href="#Adding-a-Perl-interpreter-to-your-C-program">Adding a Perl interpreter to your C program</a>, on my Linux box:</p>
<pre class="verbatim"><ol><li>    % gcc -O2 -Dbool=char -DHAS_BOOL -I/usr/local/include</li><li>    -I/usr/local/lib/perl5/i586-linux/5.003/CORE</li><li>    -L/usr/local/lib/perl5/i586-linux/5.003/CORE</li><li>    -o interp interp.c -lperl -lm</li></ol></pre><p>(That's all one line.)  On my DEC Alpha running old 5.003_05, the 
incantation is a bit different:</p>
<pre class="verbatim"><ol><li>    % cc -O2 -Olimit 2900 -DSTANDARD_C -I/usr/local/include</li><li>    -I/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE</li><li>    -L/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE -L/usr/local/lib</li><li>    -D__LANGUAGE_C__ -D_NO_PROTO -o interp interp.c -lperl -lm</li></ol></pre><p>How can you figure out what to add?  Assuming your Perl is post-5.001,
execute a <code class="inline"><span class="w">perl</span> -<span class="w">V</span></code>
 command and pay special attention to the "cc" and
"ccflags" information.</p>
<p>You'll have to choose the appropriate compiler (<i>cc</i>, <i>gcc</i>, et al.) for
your machine: <code class="inline"><span class="w">perl</span> -<span class="w">MConfig</span> -e <span class="q">&#39;print $Config{cc}&#39;</span></code>
 will tell you what
to use.</p>
<p>You'll also have to choose the appropriate library directory
(<i>/usr/local/lib/...</i>) for your machine.  If your compiler complains
that certain functions are undefined, or that it can't locate
<i>-lperl</i>, then you need to change the path following the <code class="inline">-<span class="w">L</span></code>
.  If it
complains that it can't find <i>EXTERN.h</i> and <i>perl.h</i>, you need to
change the path following the <code class="inline">-<span class="w">I</span></code>
.</p>
<p>You may have to add extra libraries as well.  Which ones?
Perhaps those printed by</p>
<pre class="verbatim"><ol><li>   <span class="w">perl</span> -<span class="w">MConfig</span> -e <span class="q">&#39;print $Config{libs}&#39;</span></li></ol></pre><p>Provided your perl binary was properly configured and installed the
<b>ExtUtils::Embed</b> module will determine all of this information for
you:</p>
<pre class="verbatim"><ol><li>   <span class="i">% cc</span> -<span class="w">o</span> <span class="w">interp</span> <span class="w">interp</span>.<span class="w">c</span> <span class="q">`perl -MExtUtils::Embed -e ccopts -e ldopts`</span></li></ol></pre><p>If the <b>ExtUtils::Embed</b> module isn't part of your Perl distribution,
you can retrieve it from
<a href="http://www.perl.com/perl/CPAN/modules/by-module/ExtUtils/">http://www.perl.com/perl/CPAN/modules/by-module/ExtUtils/</a>
(If this documentation came from your Perl distribution, then you're
running 5.004 or better and you already have it.)</p>
<p>The <b>ExtUtils::Embed</b> kit on CPAN also contains all source code for
the examples in this document, tests, additional examples and other
information you may find useful.</p>
<a name="Adding-a-Perl-interpreter-to-your-C-program"></a><h2>Adding a Perl interpreter to your C program</h2>
<p>In a sense, perl (the C program) is a good example of embedding Perl
(the language), so I'll demonstrate embedding with <i>miniperlmain.c</i>,
included in the source distribution.  Here's a bastardized, non-portable
version of <i>miniperlmain.c</i> containing the essentials of embedding:</p>
<pre class="verbatim"><ol><li>    #include &lt;EXTERN.h&gt;               /* from the Perl distribution     */</li><li>    #include &lt;perl.h&gt;                 /* from the Perl distribution     */</li><li></li><li>    static PerlInterpreter *my_perl;  /***    The Perl interpreter    ***/</li><li></li><li>    int main(int argc, char **argv, char **env)</li><li>    {</li><li>	PERL_SYS_INIT3(&amp;argc,&amp;argv,&amp;env);</li><li>        my_perl = perl_alloc();</li><li>        perl_construct(my_perl);</li><li>	PL_exit_flags |= PERL_EXIT_DESTRUCT_END;</li><li>        perl_parse(my_perl, NULL, argc, argv, (char **)NULL);</li><li>        perl_run(my_perl);</li><li>        perl_destruct(my_perl);</li><li>        perl_free(my_perl);</li><li>	PERL_SYS_TERM();</li><li>    }</li></ol></pre><p>Notice that we don't use the <code class="inline"><span class="w">env</span></code>
 pointer.  Normally handed to
<code class="inline"><span class="w">perl_parse</span></code>
 as its final argument, <code class="inline"><span class="w">env</span></code>
 here is replaced by
<code class="inline"><span class="w">NULL</span></code>
, which means that the current environment will be used.</p>
<p>The macros PERL_SYS_INIT3() and PERL_SYS_TERM() provide system-specific
tune up of the C runtime environment necessary to run Perl interpreters;
they should only be called once regardless of how many interpreters you
create or destroy. Call PERL_SYS_INIT3() before you create your first
interpreter, and PERL_SYS_TERM() after you free your last interpreter.</p>
<p>Since PERL_SYS_INIT3() may change <code class="inline"><span class="w">env</span></code>
, it may be more appropriate to
provide <code class="inline"><span class="w">env</span></code>
 as an argument to perl_parse().</p>
<p>Also notice that no matter what arguments you pass to perl_parse(),
PERL_SYS_INIT3() must be invoked on the C main() argc, argv and env and
only once.</p>
<p>Now compile this program (I'll call it <i>interp.c</i>) into an executable:</p>
<pre class="verbatim"><ol><li>    <span class="i">% cc</span> -<span class="w">o</span> <span class="w">interp</span> <span class="w">interp</span>.<span class="w">c</span> <span class="q">`perl -MExtUtils::Embed -e ccopts -e ldopts`</span></li></ol></pre><p>After a successful compilation, you'll be able to use <i>interp</i> just
like perl itself:</p>
<pre class="verbatim"><ol><li>    % interp</li><li>    print "Pretty Good Perl \n";</li><li>    print "10890 - 9801 is ", 10890 - 9801;</li><li>    &lt;CTRL-D&gt;</li><li>    Pretty Good Perl</li><li>    10890 - 9801 is 1089</li></ol></pre><p>or</p>
<pre class="verbatim"><ol><li>    % interp -e 'printf("%x", 3735928559)'</li><li>    deadbeef</li></ol></pre><p>You can also read and execute Perl statements from a file while in the
midst of your C program, by placing the filename in <i>argv[1]</i> before
calling <i>perl_run</i>.</p>
<a name="Calling-a-Perl-subroutine-from-your-C-program"></a><h2>Calling a Perl subroutine from your C program</h2>
<p>To call individual Perl subroutines, you can use any of the <b>call_*</b>
functions documented in <a href="perlcall.html">perlcall</a>.
In this example we'll use <code class="inline"><span class="w">call_argv</span></code>
.</p>
<p>That's shown below, in a program I'll call <i>showtime.c</i>.</p>
<pre class="verbatim"><ol><li>    #include &lt;EXTERN.h&gt;</li><li>    #include &lt;perl.h&gt;</li><li></li><li>    static PerlInterpreter *my_perl;</li><li></li><li>    int main(int argc, char **argv, char **env)</li><li>    {</li><li>        char *args[] = { NULL };</li><li>	PERL_SYS_INIT3(&amp;argc,&amp;argv,&amp;env);</li><li>        my_perl = perl_alloc();</li><li>        perl_construct(my_perl);</li><li></li><li>        perl_parse(my_perl, NULL, argc, argv, NULL);</li><li>	PL_exit_flags |= PERL_EXIT_DESTRUCT_END;</li><li></li><li>        /*** skipping perl_run() ***/</li><li></li><li>        call_argv("showtime", G_DISCARD | G_NOARGS, args);</li><li></li><li>        perl_destruct(my_perl);</li><li>        perl_free(my_perl);</li><li>	PERL_SYS_TERM();</li><li>    }</li></ol></pre><p>where <i>showtime</i> is a Perl subroutine that takes no arguments (that's the
<i>G_NOARGS</i>) and for which I'll ignore the return value (that's the
<i>G_DISCARD</i>).  Those flags, and others, are discussed in <a href="perlcall.html">perlcall</a>.</p>
<p>I'll define the <i>showtime</i> subroutine in a file called <i>showtime.pl</i>:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;I shan&#39;t be printed.&quot;</span><span class="sc">;</span></li><li></li><li><a name="showtime"></a>    sub <span class="m">showtime</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/time.html">time</a><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>Simple enough.  Now compile and run:</p>
<pre class="verbatim"><ol><li>    <span class="i">% cc</span> -<span class="w">o</span> <span class="w">showtime</span> <span class="w">showtime</span>.<span class="w">c</span> <span class="q">`perl -MExtUtils::Embed -e ccopts -e ldopts`</span></li><li></li><li>    % <span class="w">showtime</span> <span class="w">showtime</span>.<span class="w">pl</span></li><li>    <span class="n">818284590</span></li></ol></pre><p>yielding the number of seconds that elapsed between January 1, 1970
(the beginning of the Unix epoch), and the moment I began writing this
sentence.</p>
<p>In this particular case we don't have to call <i>perl_run</i>, as we set 
the PL_exit_flag PERL_EXIT_DESTRUCT_END which executes END blocks in
perl_destruct.</p>
<p>If you want to pass arguments to the Perl subroutine, you can add
strings to the <code class="inline"><span class="w">NULL</span></code>
-terminated <code class="inline"><span class="w">args</span></code>
 list passed to
<i>call_argv</i>.  For other data types, or to examine return values,
you'll need to manipulate the Perl stack.  That's demonstrated in
<a href="#Fiddling-with-the-Perl-stack-from-your-C-program">Fiddling with the Perl stack from your C program</a>.</p>
<a name="Evaluating-a-Perl-statement-from-your-C-program"></a><h2>Evaluating a Perl statement from your C program</h2>
<p>Perl provides two API functions to evaluate pieces of Perl code.
These are <a href="perlapi.html#eval_sv">eval_sv in perlapi</a> and <a href="perlapi.html#eval_pv">eval_pv in perlapi</a>.</p>
<p>Arguably, these are the only routines you'll ever need to execute
snippets of Perl code from within your C program.  Your code can be as
long as you wish; it can contain multiple statements; it can employ
<a href="functions/use.html">use</a>, <a href="functions/require.html">require</a>, and <a href="functions/do.html">do</a> to
include external Perl files.</p>
<p><i>eval_pv</i> lets us evaluate individual Perl strings, and then
extract variables for coercion into C types.  The following program,
<i>string.c</i>, executes three Perl strings, extracting an <code class="inline"><a class="l_k" href="functions/int.html">int</a></code> from
the first, a <code class="inline"><span class="w">float</span></code>
 from the second, and a <code class="inline"><span class="w">char</span> *</code>
 from the third.</p>
<pre class="verbatim"><ol><li>   #include &lt;EXTERN.h&gt;</li><li>   #include &lt;perl.h&gt;</li><li></li><li>   static PerlInterpreter *my_perl;</li><li></li><li>   main (int argc, char **argv, char **env)</li><li>   {</li><li>       char *embedding[] = { "", "-e", "0" };</li><li></li><li>       PERL_SYS_INIT3(&amp;argc,&amp;argv,&amp;env);</li><li>       my_perl = perl_alloc();</li><li>       perl_construct( my_perl );</li><li></li><li>       perl_parse(my_perl, NULL, 3, embedding, NULL);</li><li>       PL_exit_flags |= PERL_EXIT_DESTRUCT_END;</li><li>       perl_run(my_perl);</li><li></li><li>       /** Treat $a as an integer **/</li><li>       eval_pv("$a = 3; $a **= 2", TRUE);</li><li>       printf("a = %d\n", SvIV(get_sv("a", 0)));</li><li></li><li>       /** Treat $a as a float **/</li><li>       eval_pv("$a = 3.14; $a **= 2", TRUE);</li><li>       printf("a = %f\n", SvNV(get_sv("a", 0)));</li><li></li><li>       /** Treat $a as a string **/</li><li>       eval_pv("$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);", TRUE);</li><li>       printf("a = %s\n", SvPV_nolen(get_sv("a", 0)));</li><li></li><li>       perl_destruct(my_perl);</li><li>       perl_free(my_perl);</li><li>       PERL_SYS_TERM();</li><li>   }</li></ol></pre><p>All of those strange functions with <i>sv</i> in their names help convert Perl scalars to C types.  They're described in <a href="perlguts.html">perlguts</a> and <a href="perlapi.html">perlapi</a>.</p>
<p>If you compile and run <i>string.c</i>, you'll see the results of using
<i>SvIV()</i> to create an <code class="inline"><a class="l_k" href="functions/int.html">int</a></code>, <i>SvNV()</i> to create a <code class="inline"><span class="w">float</span></code>
, and
<i>SvPV()</i> to create a string:</p>
<pre class="verbatim"><ol><li>   a = 9</li><li>   a = 9.859600</li><li>   a = Just Another Perl Hacker</li></ol></pre><p>In the example above, we've created a global variable to temporarily
store the computed value of our eval'ed expression.  It is also
possible and in most cases a better strategy to fetch the return value
from <i>eval_pv()</i> instead.  Example:</p>
<pre class="verbatim"><ol><li>   ...</li><li>   <span class="w">SV</span> *<span class="w">val</span> = <span class="i">eval_pv</span><span class="s">(</span><span class="q">&quot;reverse 'rekcaH lreP rehtonA tsuJ'&quot;</span><span class="cm">,</span> <span class="w">TRUE</span><span class="s">)</span><span class="sc">;</span></li><li>   <a class="l_k" href="functions/printf.html">printf</a><span class="s">(</span><span class="q">&quot;%s\n&quot;</span><span class="cm">,</span> <span class="i">SvPV_nolen</span><span class="s">(</span><span class="w">val</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>   ...</li></ol></pre><p>This way, we avoid namespace pollution by not creating global
variables and we've simplified our code as well.</p>
<a name="Performing-Perl-pattern-matches-and-substitutions-from-your-C-program"></a><h2>Performing Perl pattern matches and substitutions from your C program</h2>
<p>The <i>eval_sv()</i> function lets us evaluate strings of Perl code, so we can
define some functions that use it to "specialize" in matches and
substitutions: <i>match()</i>, <i>substitute()</i>, and <i>matches()</i>.</p>
<pre class="verbatim"><ol><li>   <span class="w">I32</span> <span class="i">match</span><span class="s">(</span><span class="w">SV</span> *<span class="w">string</span><span class="cm">,</span> <span class="w">char</span> *<span class="w">pattern</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Given a string and a pattern (e.g., <code class="inline"><a class="l_k" href="functions/m.html">m/clasp/</a></code> or <code class="inline"><span class="q">/\b\w*\b/</span></code>
, which
in your C program might appear as "/\\b\\w*\\b/"), match()
returns 1 if the string matches the pattern and 0 otherwise.</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/int.html">int</a> <span class="i">substitute</span><span class="s">(</span><span class="w">SV</span> **<span class="w">string</span><span class="cm">,</span> <span class="w">char</span> *<span class="w">pattern</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Given a pointer to an <code class="inline"><span class="w">SV</span></code>
 and an <code class="inline">=~</code>
 operation (e.g.,
<code class="inline"><a class="l_k" href="functions/s.html">s/bob/robert/g</a></code> or <code class="inline"><a class="l_k" href="functions/tr.html">tr[A-Z][a-z]</a></code>), substitute() modifies the string
within the <code class="inline"><span class="w">SV</span></code>
 as according to the operation, returning the number of substitutions
made.</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/int.html">int</a> <span class="i">matches</span><span class="s">(</span><span class="w">SV</span> *<span class="w">string</span><span class="cm">,</span> <span class="w">char</span> *<span class="w">pattern</span><span class="cm">,</span> <span class="w">AV</span> **<span class="w">matches</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Given an <code class="inline"><span class="w">SV</span></code>
, a pattern, and a pointer to an empty <code class="inline"><span class="w">AV</span></code>
,
matches() evaluates <code class="inline"><span class="i">$string</span> =~ <span class="i">$pattern</span></code>
 in a list context, and
fills in <i>matches</i> with the array elements, returning the number of matches found.</p>
<p>Here's a sample program, <i>match.c</i>, that uses all three (long lines have
been wrapped here):</p>
<pre class="verbatim"><ol><li> <span class="c">#include &lt;EXTERN.h&gt;</span></li><li> <span class="c">#include &lt;perl.h&gt;</span></li><li></li><li> <span class="w">static</span> <span class="w">PerlInterpreter</span> *<span class="w">my_perl</span><span class="sc">;</span></li><li></li><li> <span class="q">/** my_eval_sv(code, error_check)</span></li><li> <span class="q"> ** kinda like eval_sv(), </span></li><li> <span class="q"> ** but we pop the return value off the stack </span></li><li> <span class="q"> **/</span></li><li> <span class="w">SV</span>* <span class="i">my_eval_sv</span><span class="s">(</span><span class="w">SV</span> *<span class="w">sv</span><span class="cm">,</span> <span class="w">I32</span> <span class="w">croak_on_error</span><span class="s">)</span></li><li> <span class="s">{</span></li><li>     <span class="w">dSP</span><span class="sc">;</span></li><li>     <span class="w">SV</span>* <span class="w">retval</span><span class="sc">;</span></li><li></li><li></li><li>     <span class="i">PUSHMARK</span><span class="s">(</span><span class="w">SP</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">eval_sv</span><span class="s">(</span><span class="w">sv</span><span class="cm">,</span> <span class="w">G_SCALAR</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="w">SPAGAIN</span><span class="sc">;</span></li><li>     <span class="w">retval</span> = <span class="w">POPs</span><span class="sc">;</span></li><li>     <span class="w">PUTBACK</span><span class="sc">;</span></li><li></li><li>     if <span class="s">(</span><span class="w">croak_on_error</span> &amp;&amp; <span class="i">SvTRUE</span><span class="s">(</span><span class="w">ERRSV</span><span class="s">)</span><span class="s">)</span></li><li> 	<span class="i">croak</span><span class="s">(</span><span class="i">SvPVx_nolen</span><span class="s">(</span><span class="w">ERRSV</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <a class="l_k" href="functions/return.html">return</a> <span class="w">retval</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li> <span class="q">/** match(string, pattern)</span></li><li> <span class="q"> **</span></li><li> <span class="q"> ** Used for matches in a scalar context.</span></li><li> <span class="q"> **</span></li><li> <span class="q"> ** Returns 1 if the match was successful; 0 otherwise.</span></li><li> <span class="q"> **/</span></li><li></li><li> <span class="w">I32</span> <span class="i">match</span><span class="s">(</span><span class="w">SV</span> *<span class="w">string</span><span class="cm">,</span> <span class="w">char</span> *<span class="w">pattern</span><span class="s">)</span></li><li> <span class="s">{</span></li><li>     <span class="w">SV</span> *<span class="w">command</span> = <span class="i">newSV</span><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="cm">,</span> <span class="i">*retval</span><span class="sc">;</span></li><li></li><li>     <span class="i">sv_setpvf</span><span class="s">(</span><span class="w">command</span><span class="cm">,</span> <span class="q">&quot;my $string = &#39;%s&#39;; $string =~ %s&quot;</span><span class="cm">,</span></li><li> 	      <span class="i">SvPV_nolen</span><span class="s">(</span><span class="w">string</span><span class="s">)</span><span class="cm">,</span> <span class="w">pattern</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="w">retval</span> = <span class="i">my_eval_sv</span><span class="s">(</span><span class="w">command</span><span class="cm">,</span> <span class="w">TRUE</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">SvREFCNT_dec</span><span class="s">(</span><span class="w">command</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <a class="l_k" href="functions/return.html">return</a> <span class="i">SvIV</span><span class="s">(</span><span class="w">retval</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li> <span class="q">/** substitute(string, pattern)</span></li><li> <span class="q"> **</span></li><li> <span class="q"> ** Used for =~ operations that modify their left-hand side (s/</span>// and <span class="q">tr///</span><span class="p">)</span></li><li> **</li><li> <span class="i">**</span> <span class="w">Returns</span> <span class="w">the</span> <span class="w">number</span> <span class="w">of</span> <span class="w">successful</span> <span class="w">matches</span><span class="cm">,</span> and</li><li> <span class="i">**</span> <span class="w">modifies</span> <span class="w">the</span> <span class="w">input</span> <span class="w">string</span> if <span class="w">there</span> <span class="w">were</span> <span class="w">any</span>.</li><li> <span class="i">**</span>/</li><li></li><li> <span class="w">I32</span> <span class="i">substitute</span><span class="s">(</span><span class="w">SV</span> **<span class="w">string</span><span class="cm">,</span> <span class="w">char</span> *<span class="w">pattern</span><span class="s">)</span></li><li> <span class="s">{</span></li><li>     <span class="w">SV</span> *<span class="w">command</span> = <span class="i">newSV</span><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="cm">,</span> <span class="i">*retval</span><span class="sc">;</span></li><li></li><li>     <span class="i">sv_setpvf</span><span class="s">(</span><span class="w">command</span><span class="cm">,</span> <span class="q">&quot;$string = &#39;%s&#39;; ($string =~ %s)&quot;</span><span class="cm">,</span></li><li> 	      <span class="i">SvPV_nolen</span><span class="s">(</span><span class="i">*string</span><span class="s">)</span><span class="cm">,</span> <span class="w">pattern</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="w">retval</span> = <span class="i">my_eval_sv</span><span class="s">(</span><span class="w">command</span><span class="cm">,</span> <span class="w">TRUE</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">SvREFCNT_dec</span><span class="s">(</span><span class="w">command</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="i">*string</span> = <span class="i">get_sv</span><span class="s">(</span><span class="q">&quot;string&quot;</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/return.html">return</a> <span class="i">SvIV</span><span class="s">(</span><span class="w">retval</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li> <span class="q">/** matches(string, pattern, matches)</span></li><li> <span class="q"> **</span></li><li> <span class="q"> ** Used for matches in a list context.</span></li><li> <span class="q"> **</span></li><li> <span class="q"> ** Returns the number of matches,</span></li><li> <span class="q"> ** and fills in **matches with the matching substrings</span></li><li> <span class="q"> **/</span></li><li></li><li> <span class="w">I32</span> <span class="i">matches</span><span class="s">(</span><span class="w">SV</span> *<span class="w">string</span><span class="cm">,</span> <span class="w">char</span> *<span class="w">pattern</span><span class="cm">,</span> <span class="w">AV</span> **<span class="w">match_list</span><span class="s">)</span></li><li> <span class="s">{</span></li><li>     <span class="w">SV</span> *<span class="w">command</span> = <span class="i">newSV</span><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="w">I32</span> <span class="w">num_matches</span><span class="sc">;</span></li><li></li><li>     <span class="i">sv_setpvf</span><span class="s">(</span><span class="w">command</span><span class="cm">,</span> <span class="q">&quot;my $string = &#39;%s&#39;; @array = ($string =~ %s)&quot;</span><span class="cm">,</span></li><li> 	      <span class="i">SvPV_nolen</span><span class="s">(</span><span class="w">string</span><span class="s">)</span><span class="cm">,</span> <span class="w">pattern</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="i">my_eval_sv</span><span class="s">(</span><span class="w">command</span><span class="cm">,</span> <span class="w">TRUE</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">SvREFCNT_dec</span><span class="s">(</span><span class="w">command</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="i">*match_list</span> = <span class="i">get_av</span><span class="s">(</span><span class="q">&quot;array&quot;</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="w">num_matches</span> = <span class="i">av_len</span><span class="s">(</span><span class="i">*match_list</span><span class="s">)</span> + <span class="n">1</span><span class="sc">;</span></li><li></li><li>     <a class="l_k" href="functions/return.html">return</a> <span class="w">num_matches</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li> <span class="w">main</span> <span class="s">(</span><a class="l_k" href="functions/int.html">int</a> <span class="w">argc</span><span class="cm">,</span> <span class="w">char</span> **<span class="w">argv</span><span class="cm">,</span> <span class="w">char</span> **<span class="w">env</span><span class="s">)</span></li><li> <span class="s">{</span></li><li>     <span class="w">char</span> *<span class="w">embedding</span><span class="s">[</span><span class="s">]</span> = <span class="s">{</span> <span class="q">&quot;&quot;</span><span class="cm">,</span> <span class="q">&quot;-e&quot;</span><span class="cm">,</span> <span class="q">&quot;0&quot;</span> <span class="s">}</span><span class="sc">;</span></li><li>     <span class="w">AV</span> *<span class="w">match_list</span><span class="sc">;</span></li><li>     <span class="w">I32</span> <span class="w">num_matches</span><span class="cm">,</span> <span class="w">i</span><span class="sc">;</span></li><li>     <span class="w">SV</span> *<span class="w">text</span><span class="sc">;</span></li><li></li><li>     <span class="i">PERL_SYS_INIT3</span><span class="s">(</span><span class="i">&amp;argc</span><span class="cm">,</span><span class="i">&amp;argv</span><span class="cm">,</span><span class="i">&amp;env</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="w">my_perl</span> = <span class="i">perl_alloc</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">perl_construct</span><span class="s">(</span><span class="w">my_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">perl_parse</span><span class="s">(</span><span class="w">my_perl</span><span class="cm">,</span> <span class="w">NULL</span><span class="cm">,</span> <span class="n">3</span><span class="cm">,</span> <span class="w">embedding</span><span class="cm">,</span> <span class="w">NULL</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="w">PL_exit_flags</span> |= <span class="w">PERL_EXIT_DESTRUCT_END</span><span class="sc">;</span></li><li></li><li>     <span class="w">text</span> = <span class="i">newSV</span><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">sv_setpv</span><span class="s">(</span><span class="w">text</span><span class="cm">,</span> <span class="q">&quot;When he is at a convenience store and the &quot;</span></li><li>	<span class="q">&quot;bill comes to some amount like 76 cents, Maynard is &quot;</span></li><li>	<span class="q">&quot;aware that there is something he *should* do, something &quot;</span></li><li>	<span class="q">&quot;that will enable him to get back a quarter, but he has &quot;</span></li><li>	<span class="q">&quot;no idea *what*.  He fumbles through his red squeezey &quot;</span></li><li>	<span class="q">&quot;changepurse and gives the boy three extra pennies with &quot;</span></li><li>	<span class="q">&quot;his dollar, hoping that he might luck into the correct &quot;</span></li><li>	<span class="q">&quot;amount.  The boy gives him back two of his own pennies &quot;</span></li><li>	<span class="q">&quot;and then the big shiny quarter that is his prize. &quot;</span></li><li>	<span class="q">&quot;-RICHH&quot;</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     if <span class="s">(</span><span class="i">match</span><span class="s">(</span><span class="w">text</span><span class="cm">,</span> <span class="q">&quot;m/quarter/&quot;</span><span class="s">)</span><span class="s">)</span> /<span class="i">**</span> <span class="w">Does</span> <span class="w">text</span> <span class="w">contain</span> <span class="q">&#39;quarter&#39;</span>? <span class="i">**</span>/</li><li> 	<a class="l_k" href="functions/printf.html">printf</a><span class="s">(</span><span class="q">&quot;match: Text contains the word &#39;quarter&#39;.\n\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>     else</li><li> 	<a class="l_k" href="functions/printf.html">printf</a><span class="s">(</span><span class="q">&quot;match: Text doesn&#39;t contain the word &#39;quarter&#39;.\n\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     if <span class="s">(</span><span class="i">match</span><span class="s">(</span><span class="w">text</span><span class="cm">,</span> <span class="q">&quot;m/eighth/&quot;</span><span class="s">)</span><span class="s">)</span> /<span class="i">**</span> <span class="w">Does</span> <span class="w">text</span> <span class="w">contain</span> <span class="q">&#39;eighth&#39;</span>? <span class="i">**</span>/</li><li> 	<a class="l_k" href="functions/printf.html">printf</a><span class="s">(</span><span class="q">&quot;match: Text contains the word &#39;eighth&#39;.\n\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>     else</li><li> 	<a class="l_k" href="functions/printf.html">printf</a><span class="s">(</span><span class="q">&quot;match: Text doesn&#39;t contain the word &#39;eighth&#39;.\n\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="q">/** Match all occurrences of /</span><span class="w">wi</span>..<span class="q">/ **/</span></li><li>     <span class="w">num_matches</span> = <span class="i">matches</span><span class="s">(</span><span class="w">text</span><span class="cm">,</span> <span class="q">&quot;m/(wi..)/g&quot;</span><span class="cm">,</span> <span class="i">&amp;match_list</span><span class="s">)</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/printf.html">printf</a><span class="s">(</span><span class="q">&quot;matches: m/(wi..)/g found %d matches...\n&quot;</span><span class="cm">,</span> <span class="w">num_matches</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     for <span class="s">(</span><span class="w">i</span> = <span class="n">0</span><span class="sc">;</span> <span class="w">i</span> &lt; <span class="w">num_matches</span><span class="sc">;</span> <span class="w">i</span>++<span class="s">)</span></li><li> 	<a class="l_k" href="functions/printf.html">printf</a><span class="s">(</span><span class="q">&quot;match: %s\n&quot;</span><span class="cm">,</span> <span class="i">SvPV_nolen</span><span class="s">(</span><span class="i">*av_fetch</span><span class="s">(</span><span class="w">match_list</span><span class="cm">,</span> <span class="w">i</span><span class="cm">,</span> <span class="w">FALSE</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/printf.html">printf</a><span class="s">(</span><span class="q">&quot;\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="q">/** Remove all vowels from text **/</span></li><li>     <span class="w">num_matches</span> = <span class="i">substitute</span><span class="s">(</span><span class="i">&amp;text</span><span class="cm">,</span> <span class="q">&quot;s/[aeiou]//gi&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>     if <span class="s">(</span><span class="w">num_matches</span><span class="s">)</span> <span class="s">{</span></li><li> 	<a class="l_k" href="functions/printf.html">printf</a><span class="s">(</span><span class="q">&quot;substitute: s/[aeiou]//gi...%d substitutions made.\n&quot;</span><span class="cm">,</span></li><li> 	       <span class="w">num_matches</span><span class="s">)</span><span class="sc">;</span></li><li> 	<a class="l_k" href="functions/printf.html">printf</a><span class="s">(</span><span class="q">&quot;Now text is: %s\n\n&quot;</span><span class="cm">,</span> <span class="i">SvPV_nolen</span><span class="s">(</span><span class="w">text</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="s">}</span></li><li></li><li>     <span class="q">/** Attempt a substitution **/</span></li><li>     if <span class="s">(</span>!<span class="i">substitute</span><span class="s">(</span><span class="i">&amp;text</span><span class="cm">,</span> <span class="q">&quot;s/Perl/C/&quot;</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li> 	<a class="l_k" href="functions/printf.html">printf</a><span class="s">(</span><span class="q">&quot;substitute: s/Perl/C...No substitution made.\n\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="s">}</span></li><li></li><li>     <span class="i">SvREFCNT_dec</span><span class="s">(</span><span class="w">text</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="w">PL_perl_destruct_level</span> = <span class="n">1</span><span class="sc">;</span></li><li>     <span class="i">perl_destruct</span><span class="s">(</span><span class="w">my_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">perl_free</span><span class="s">(</span><span class="w">my_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">PERL_SYS_TERM</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>which produces the output (again, long lines have been wrapped here)</p>
<pre class="verbatim"><ol><li>   match: Text contains the word 'quarter'.</li><li></li><li>   match: Text doesn't contain the word 'eighth'.</li><li></li><li>   matches: m/(wi..)/g found 2 matches...</li><li>   match: will</li><li>   match: with</li><li></li><li>   substitute: s/[aeiou]//gi...139 substitutions made.</li><li>   Now text is: Whn h s t  cnvnnc str nd th bll cms t sm mnt lk 76 cnts,</li><li>   Mynrd s wr tht thr s smthng h *shld* d, smthng tht wll nbl hm t gt bck</li><li>   qrtr, bt h hs n d *wht*.  H fmbls thrgh hs rd sqzy chngprs nd gvs th by</li><li>   thr xtr pnns wth hs dllr, hpng tht h mght lck nt th crrct mnt.  Th by gvs</li><li>   hm bck tw f hs wn pnns nd thn th bg shny qrtr tht s hs prz. -RCHH</li><li></li><li>   substitute: s/Perl/C...No substitution made.</li></ol></pre><a name="Fiddling-with-the-Perl-stack-from-your-C-program"></a><h2>Fiddling with the Perl stack from your C program</h2>
<p>When trying to explain stacks, most computer science textbooks mumble
something about spring-loaded columns of cafeteria plates: the last
thing you pushed on the stack is the first thing you pop off.  That'll
do for our purposes: your C program will push some arguments onto "the Perl
stack", shut its eyes while some magic happens, and then pop the
results--the return value of your Perl subroutine--off the stack.</p>
<p>First you'll need to know how to convert between C types and Perl
types, with newSViv() and sv_setnv() and newAV() and all their
friends.  They're described in <a href="perlguts.html">perlguts</a> and <a href="perlapi.html">perlapi</a>.</p>
<p>Then you'll need to know how to manipulate the Perl stack.  That's
described in <a href="perlcall.html">perlcall</a>.</p>
<p>Once you've understood those, embedding Perl in C is easy.</p>
<p>Because C has no builtin function for integer exponentiation, let's
make Perl's ** operator available to it (this is less useful than it
sounds, because Perl implements ** with C's <i>pow()</i> function).  First
I'll create a stub exponentiation function in <i>power.pl</i>:</p>
<pre class="verbatim"><ol><li><a name="expo"></a>    sub <span class="m">expo</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$a</span><span class="cm">,</span> <span class="i">$b</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/return.html">return</a> <span class="i">$a</span> ** <span class="i">$b</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>Now I'll create a C program, <i>power.c</i>, with a function
<i>PerlPower()</i> that contains all the perlguts necessary to push the
two arguments into <i>expo()</i> and to pop the return value out.  Take a
deep breath...</p>
<pre class="verbatim"><ol><li>    #include &lt;EXTERN.h&gt;</li><li>    #include &lt;perl.h&gt;</li><li></li><li>    static PerlInterpreter *my_perl;</li><li></li><li>    static void</li><li>    PerlPower(int a, int b)</li><li>    {</li><li>      dSP;                            /* initialize stack pointer      */</li><li>      ENTER;                          /* everything created after here */</li><li>      SAVETMPS;                       /* ...is a temporary variable.   */</li><li>      PUSHMARK(SP);                   /* remember the stack pointer    */</li><li>      XPUSHs(sv_2mortal(newSViv(a))); /* push the base onto the stack  */</li><li>      XPUSHs(sv_2mortal(newSViv(b))); /* push the exponent onto stack  */</li><li>      PUTBACK;                      /* make local stack pointer global */</li><li>      call_pv("expo", G_SCALAR);      /* call the function             */</li><li>      SPAGAIN;                        /* refresh stack pointer         */</li><li>                                    /* pop the return value from stack */</li><li>      printf ("%d to the %dth power is %d.\n", a, b, POPi);</li><li>      PUTBACK;</li><li>      FREETMPS;                       /* free that return value        */</li><li>      LEAVE;                       /* ...and the XPUSHed "mortal" args.*/</li><li>    }</li><li></li><li>    int main (int argc, char **argv, char **env)</li><li>    {</li><li>      char *my_argv[] = { "", "power.pl" };</li><li></li><li>      PERL_SYS_INIT3(&amp;argc,&amp;argv,&amp;env);</li><li>      my_perl = perl_alloc();</li><li>      perl_construct( my_perl );</li><li></li><li>      perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL);</li><li>      PL_exit_flags |= PERL_EXIT_DESTRUCT_END;</li><li>      perl_run(my_perl);</li><li></li><li>      PerlPower(3, 4);                      /*** Compute 3 ** 4 ***/</li><li></li><li>      perl_destruct(my_perl);</li><li>      perl_free(my_perl);</li><li>      PERL_SYS_TERM();</li><li>    }</li></ol></pre><p>Compile and run:</p>
<pre class="verbatim"><ol><li>    % cc -o power power.c `perl -MExtUtils::Embed -e ccopts -e ldopts`</li><li></li><li>    % power</li><li>    3 to the 4th power is 81.</li></ol></pre><a name="Maintaining-a-persistent-interpreter"></a><h2>Maintaining a persistent interpreter</h2>
<p>When developing interactive and/or potentially long-running
applications, it's a good idea to maintain a persistent interpreter
rather than allocating and constructing a new interpreter multiple
times.  The major reason is speed: since Perl will only be loaded into
memory once.</p>
<p>However, you have to be more cautious with namespace and variable
scoping when using a persistent interpreter.  In previous examples
we've been using global variables in the default package <code class="inline"><span class="w">main</span></code>
.  We
knew exactly what code would be run, and assumed we could avoid
variable collisions and outrageous symbol table growth.</p>
<p>Let's say your application is a server that will occasionally run Perl
code from some arbitrary file.  Your server has no way of knowing what
code it's going to run.  Very dangerous.</p>
<p>If the file is pulled in by <code class="inline"><span class="i">perl_parse</span><span class="s">(</span><span class="s">)</span></code>
, compiled into a newly
constructed interpreter, and subsequently cleaned out with
<code class="inline"><span class="i">perl_destruct</span><span class="s">(</span><span class="s">)</span></code>
 afterwards, you're shielded from most namespace
troubles.</p>
<p>One way to avoid namespace collisions in this scenario is to translate
the filename into a guaranteed-unique package name, and then compile
the code into that package using <a href="functions/eval.html">eval</a>.  In the example
below, each file will only be compiled once.  Or, the application
might choose to clean out the symbol table associated with the file
after it's no longer needed.  Using <a href="perlapi.html#call_argv">call_argv in perlapi</a>, We'll
call the subroutine <code class="inline"><span class="w">Embed::Persistent::eval_file</span></code>
 which lives in the
file <code class="inline"><span class="w">persistent</span>.<span class="w">pl</span></code>
 and pass the filename and boolean cleanup/cache
flag as arguments.</p>
<p>Note that the process will continue to grow for each file that it
uses.  In addition, there might be <code class="inline">AUTOLOAD</code>
ed subroutines and other
conditions that cause Perl's symbol table to grow.  You might want to
add some logic that keeps track of the process size, or restarts
itself after a certain number of requests, to ensure that memory
consumption is minimized.  You'll also want to scope your variables
with <a href="functions/my.html">my</a> whenever possible.</p>
<pre class="verbatim"><ol><li><a name="package-Embed::Persistent"></a> package <span class="i">Embed::Persistent</span><span class="sc">;</span></li><li> <span class="c">#persistent.pl</span></li><li></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">strict</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/our.html">our</a> <span class="i">%Cache</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Symbol</span> <span class="q">qw(delete_package)</span><span class="sc">;</span></li><li></li><li><a name="valid_package_name"></a> sub <span class="m">valid_package_name</span> <span class="s">{</span></li><li>     <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$string</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>     <span class="i">$string</span> =~ <span class="q">s/([^A-Za-z0-9\/])/sprintf(&quot;_%2x&quot;,unpack(&quot;C&quot;,$1))/eg</span><span class="sc">;</span></li><li>     <span class="c"># second pass only for words starting with a digit</span></li><li>     <span class="i">$string</span> =~ <span class="q">s|/(\d)|sprintf(&quot;/_%2x&quot;,unpack(&quot;C&quot;,$1))|eg</span><span class="sc">;</span></li><li></li><li>     <span class="c"># Dress it up as a real package name</span></li><li>     <span class="i">$string</span> =~ <span class="q">s|/|::|g</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/return.html">return</a> <span class="q">&quot;Embed&quot;</span> . <span class="i">$string</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li><a name="eval_file"></a> sub <span class="m">eval_file</span> <span class="s">{</span></li><li>     <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$filename</span><span class="cm">,</span> <span class="i">$delete</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/my.html">my</a> <span class="i">$package</span> = <span class="i">valid_package_name</span><span class="s">(</span><span class="i">$filename</span><span class="s">)</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/my.html">my</a> <span class="i">$mtime</span> = -M <span class="i">$filename</span><span class="sc">;</span></li><li>     if<span class="s">(</span><a class="l_k" href="functions/defined.html">defined</a> <span class="i">$Cache</span>{<span class="i">$package</span>}{<span class="w">mtime</span>}</li><li>        &amp;&amp;</li><li>        <span class="i">$Cache</span>{<span class="i">$package</span>}{<span class="w">mtime</span>} &lt;= <span class="i">$mtime</span><span class="s">)</span></li><li>     <span class="s">{</span></li><li>        <span class="c"># we have compiled this subroutine already,</span></li><li>        <span class="c"># it has not been updated on disk, nothing left to do</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="i">STDERR</span> <span class="q">&quot;already compiled $package-&gt;handler\n&quot;</span><span class="sc">;</span></li><li>     <span class="s">}</span></li><li>     else <span class="s">{</span></li><li>        <a class="l_k" href="functions/local.html">local</a> <span class="i">*FH</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/open.html">open</a> <span class="w">FH</span><span class="cm">,</span> <span class="i">$filename</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;open '$filename' $!&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/local.html">local</a><span class="s">(</span><span class="i">$/</span><span class="s">)</span> = <a class="l_k" href="functions/undef.html">undef</a><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$sub</span> = <span class="q">&lt;FH&gt;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/close.html">close</a> <span class="w">FH</span><span class="sc">;</span></li><li></li><li>        <span class="c">#wrap the code into a subroutine inside our unique package</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$eval</span> = <span class="q">qq{package $package; sub handler { $sub; }}</span><span class="sc">;</span></li><li>        <span class="s">{</span></li><li>            <span class="c"># hide our variables within this block</span></li><li>            <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$filename</span><span class="cm">,</span><span class="i">$mtime</span><span class="cm">,</span><span class="i">$package</span><span class="cm">,</span><span class="i">$sub</span><span class="s">)</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/eval.html">eval</a> <span class="i">$eval</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>        <a class="l_k" href="functions/die.html">die</a> <span class="i">$@</span> if <span class="i">$@</span><span class="sc">;</span></li><li></li><li>        <span class="c">#cache it unless we're cleaning out each time</span></li><li>        <span class="i">$Cache</span>{<span class="i">$package</span>}{<span class="w">mtime</span>} = <span class="i">$mtime</span> unless <span class="i">$delete</span><span class="sc">;</span></li><li>     <span class="s">}</span></li><li></li><li>     <a class="l_k" href="functions/eval.html">eval</a> <span class="s">{</span><span class="i">$package</span><span class="i">-&gt;handler</span><span class="sc">;</span><span class="s">}</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/die.html">die</a> <span class="i">$@</span> if <span class="i">$@</span><span class="sc">;</span></li><li></li><li>     <span class="i">delete_package</span><span class="s">(</span><span class="i">$package</span><span class="s">)</span> if <span class="i">$delete</span><span class="sc">;</span></li><li></li><li>     <span class="c">#take a look if you want</span></li><li>     <span class="c">#print Devel::Symdump-&gt;rnew($package)-&gt;as_string, $/;</span></li><li> <span class="s">}</span></li><li></li><li> <span class="n">1</span><span class="sc">;</span></li><li></li><li><a name="__END__"></a> __END__</li><li></li><li><span class="q"> /* persistent.c */</span></li><li><span class="q"> #include &lt;EXTERN.h&gt;</span></li><li><span class="q"> #include &lt;perl.h&gt;</span></li><li></li><li><span class="q"> /* 1 = clean out filename's symbol table after each request, 0 = don't */</span></li><li><span class="q"> #ifndef DO_CLEAN</span></li><li><span class="q"> #define DO_CLEAN 0</span></li><li><span class="q"> #endif</span></li><li></li><li><span class="q"> #define BUFFER_SIZE 1024</span></li><li></li><li><span class="q"> static PerlInterpreter *my_perl = NULL;</span></li><li></li><li><span class="q"> int</span></li><li><span class="q"> main(int argc, char **argv, char **env)</span></li><li><span class="q"> {</span></li><li><span class="q">     char *embedding[] = { &quot;&quot;, &quot;persistent.pl&quot; };</span></li><li><span class="q">     char *args[] = { &quot;&quot;, DO_CLEAN, NULL };</span></li><li><span class="q">     char filename[BUFFER_SIZE];</span></li><li><span class="q">     int exitstatus = 0;</span></li><li></li><li><span class="q">     PERL_SYS_INIT3(&amp;argc,&amp;argv,&amp;env);</span></li><li><span class="q">     if((my_perl = perl_alloc()) == NULL) {</span></li><li><span class="q">        fprintf(stderr, &quot;no memory!&quot;);</span></li><li><span class="q">        exit(1);</span></li><li><span class="q">     }</span></li><li><span class="q">     perl_construct(my_perl);</span></li><li></li><li><span class="q">     PL_origalen = 1; /* don't let $0 assignment update the proctitle or embedding[0] */</span></li><li><span class="q">     exitstatus = perl_parse(my_perl, NULL, 2, embedding, NULL);</span></li><li><span class="q">     PL_exit_flags |= PERL_EXIT_DESTRUCT_END;</span></li><li><span class="q">     if(!exitstatus) {</span></li><li><span class="q">        exitstatus = perl_run(my_perl);</span></li><li></li><li><span class="q">        while(printf(&quot;Enter file name: &quot;) &amp;&amp;</span></li><li><span class="q">              fgets(filename, BUFFER_SIZE, stdin)) {</span></li><li></li><li><span class="q">            filename[strlen(filename)-1] = '\0'; /* strip \n */</span></li><li><span class="q">            /* call the subroutine, passing it the filename as an argument */</span></li><li><span class="q">            args[0] = filename;</span></li><li><span class="q">            call_argv(&quot;Embed::Persistent::eval_file&quot;,</span></li><li><span class="q">                           G_DISCARD | G_EVAL, args);</span></li><li></li><li><span class="q">            /* check $@ */</span></li><li><span class="q">            if(SvTRUE(ERRSV))</span></li><li><span class="q">                fprintf(stderr, &quot;eval error: %s\n&quot;, SvPV_nolen(ERRSV));</span></li><li><span class="q">        }</span></li><li><span class="q">     }</span></li><li></li><li><span class="q">     PL_perl_destruct_level = 0;</span></li><li><span class="q">     perl_destruct(my_perl);</span></li><li><span class="q">     perl_free(my_perl);</span></li><li><span class="q">     PERL_SYS_TERM();</span></li><li><span class="q">     exit(exitstatus);</span></li><li><span class="q"> }</span></li></ol></pre><p>Now compile:</p>
<pre class="verbatim"><ol><li> <span class="i">% cc</span> -<span class="w">o</span> <span class="w">persistent</span> <span class="w">persistent</span>.<span class="w">c</span> <span class="q">`perl -MExtUtils::Embed -e ccopts -e ldopts`</span></li></ol></pre><p>Here's an example script file:</p>
<pre class="verbatim"><ol><li> <span class="c">#test.pl</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$string</span> = <span class="q">&quot;hello&quot;</span><span class="sc">;</span></li><li> <span class="i">foo</span><span class="s">(</span><span class="i">$string</span><span class="s">)</span><span class="sc">;</span></li><li></li><li><a name="foo"></a> sub <span class="m">foo</span> <span class="s">{</span></li><li>     <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;foo says: @_\n&quot;</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>Now run:</p>
<pre class="verbatim"><ol><li> % persistent</li><li> Enter file name: test.pl</li><li> foo says: hello</li><li> Enter file name: test.pl</li><li> already compiled Embed::test_2epl-&gt;handler</li><li> foo says: hello</li><li> Enter file name: ^C</li></ol></pre><a name="Execution-of-END-blocks"></a><h2>Execution of END blocks</h2>
<p>Traditionally END blocks have been executed at the end of the perl_run.
This causes problems for applications that never call perl_run. Since
perl 5.7.2 you can specify <code class="inline"><span class="w">PL_exit_flags</span> |= <span class="w">PERL_EXIT_DESTRUCT_END</span></code>

to get the new behaviour. This also enables the running of END blocks if
the perl_parse fails and <code class="inline"><span class="w">perl_destruct</span></code>
 will return the exit value.</p>
<a name="%240-assignments"></a><h2>$0 assignments</h2>
<p>When a perl script assigns a value to $0 then the perl runtime will
try to make this value show up as the program name reported by "ps" by
updating the memory pointed to by the argv passed to perl_parse() and
also calling API functions like setproctitle() where available.  This
behaviour might not be appropriate when embedding perl and can be
disabled by assigning the value <code class="inline"><span class="n">1</span></code>
 to the variable <code class="inline"><span class="w">PL_origalen</span></code>

before perl_parse() is called.</p>
<p>The <i>persistent.c</i> example above is for instance likely to segfault
when $0 is assigned to if the <code class="inline"><span class="w">PL_origalen</span> = <span class="n">1</span><span class="sc">;</span></code>
 assignment is
removed.  This because perl will try to write to the read only memory
of the <code class="inline"><span class="w">embedding</span><span class="s">[</span><span class="s">]</span></code>
 strings.</p>
<a name="Maintaining-multiple-interpreter-instances"></a><h2>Maintaining multiple interpreter instances</h2>
<p>Some rare applications will need to create more than one interpreter
during a session.  Such an application might sporadically decide to
release any resources associated with the interpreter.</p>
<p>The program must take care to ensure that this takes place <i>before</i>
the next interpreter is constructed.  By default, when perl is not
built with any special options, the global variable
<code class="inline"><span class="w">PL_perl_destruct_level</span></code>
 is set to <code class="inline"><span class="n">0</span></code>
, since extra cleaning isn't
usually needed when a program only ever creates a single interpreter
in its entire lifetime.</p>
<p>Setting <code class="inline"><span class="w">PL_perl_destruct_level</span></code>
 to <code class="inline"><span class="n">1</span></code>
 makes everything squeaky clean:</p>
<pre class="verbatim"><ol><li> while(1) {</li><li>     ...</li><li>     /* reset global variables here with PL_perl_destruct_level = 1 */</li><li>     PL_perl_destruct_level = 1;</li><li>     perl_construct(my_perl);</li><li>     ...</li><li>     /* clean and reset _everything_ during perl_destruct */</li><li>     PL_perl_destruct_level = 1;</li><li>     perl_destruct(my_perl);</li><li>     perl_free(my_perl);</li><li>     ...</li><li>     /* let's go do it again! */</li><li> }</li></ol></pre><p>When <i>perl_destruct()</i> is called, the interpreter's syntax parse tree
and symbol tables are cleaned up, and global variables are reset.  The
second assignment to <code class="inline"><span class="w">PL_perl_destruct_level</span></code>
 is needed because
perl_construct resets it to <code class="inline"><span class="n">0</span></code>
.</p>
<p>Now suppose we have more than one interpreter instance running at the
same time.  This is feasible, but only if you used the Configure option
<code class="inline">-<span class="w">Dusemultiplicity</span></code>
 or the options <code class="inline">-<span class="w">Dusethreads</span> -<span class="w">Duseithreads</span></code>
 when
building perl.  By default, enabling one of these Configure options
sets the per-interpreter global variable <code class="inline"><span class="w">PL_perl_destruct_level</span></code>
 to
<code class="inline"><span class="n">1</span></code>
, so that thorough cleaning is automatic and interpreter variables
are initialized correctly.  Even if you don't intend to run two or
more interpreters at the same time, but to run them sequentially, like
in the above example, it is recommended to build perl with the
<code class="inline">-<span class="w">Dusemultiplicity</span></code>
 option otherwise some interpreter variables may
not be initialized correctly between consecutive runs and your
application may crash.</p>
<p>See also <a href="perlxs.html#Thread-aware-system-interfaces">Thread-aware system interfaces in perlxs</a>.</p>
<p>Using <code class="inline">-<span class="w">Dusethreads</span> -<span class="w">Duseithreads</span></code>
 rather than <code class="inline">-<span class="w">Dusemultiplicity</span></code>

is more appropriate if you intend to run multiple interpreters
concurrently in different threads, because it enables support for
linking in the thread libraries of your system with the interpreter.</p>
<p>Let's give it a try:</p>
<pre class="verbatim"><ol><li> <span class="c">#include &lt;EXTERN.h&gt;</span></li><li> <span class="c">#include &lt;perl.h&gt;</span></li><li></li><li> <span class="q">/* we&#39;re going to embed two interpreters */</span></li><li></li><li> <span class="c">#define SAY_HELLO &quot;-e&quot;, &quot;print qq(Hi, I&#39;m $^X\n)&quot;</span></li><li></li><li> <a class="l_k" href="functions/int.html">int</a> <span class="i">main</span><span class="s">(</span><a class="l_k" href="functions/int.html">int</a> <span class="w">argc</span><span class="cm">,</span> <span class="w">char</span> **<span class="w">argv</span><span class="cm">,</span> <span class="w">char</span> **<span class="w">env</span><span class="s">)</span></li><li> <span class="s">{</span></li><li>     <span class="w">PerlInterpreter</span> *<span class="w">one_perl</span><span class="cm">,</span> <span class="i">*two_perl</span><span class="sc">;</span></li><li>     <span class="w">char</span> *<span class="w">one_args</span><span class="s">[</span><span class="s">]</span> = <span class="s">{</span> <span class="q">&quot;one_perl&quot;</span><span class="cm">,</span> <span class="w">SAY_HELLO</span> <span class="s">}</span><span class="sc">;</span></li><li>     <span class="w">char</span> *<span class="w">two_args</span><span class="s">[</span><span class="s">]</span> = <span class="s">{</span> <span class="q">&quot;two_perl&quot;</span><span class="cm">,</span> <span class="w">SAY_HELLO</span> <span class="s">}</span><span class="sc">;</span></li><li></li><li>     <span class="i">PERL_SYS_INIT3</span><span class="s">(</span><span class="i">&amp;argc</span><span class="cm">,</span><span class="i">&amp;argv</span><span class="cm">,</span><span class="i">&amp;env</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="w">one_perl</span> = <span class="i">perl_alloc</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="w">two_perl</span> = <span class="i">perl_alloc</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="i">PERL_SET_CONTEXT</span><span class="s">(</span><span class="w">one_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">perl_construct</span><span class="s">(</span><span class="w">one_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">PERL_SET_CONTEXT</span><span class="s">(</span><span class="w">two_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">perl_construct</span><span class="s">(</span><span class="w">two_perl</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="i">PERL_SET_CONTEXT</span><span class="s">(</span><span class="w">one_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">perl_parse</span><span class="s">(</span><span class="w">one_perl</span><span class="cm">,</span> <span class="w">NULL</span><span class="cm">,</span> <span class="n">3</span><span class="cm">,</span> <span class="w">one_args</span><span class="cm">,</span> <span class="s">(</span><span class="w">char</span> **<span class="s">)</span><span class="w">NULL</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">PERL_SET_CONTEXT</span><span class="s">(</span><span class="w">two_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">perl_parse</span><span class="s">(</span><span class="w">two_perl</span><span class="cm">,</span> <span class="w">NULL</span><span class="cm">,</span> <span class="n">3</span><span class="cm">,</span> <span class="w">two_args</span><span class="cm">,</span> <span class="s">(</span><span class="w">char</span> **<span class="s">)</span><span class="w">NULL</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="i">PERL_SET_CONTEXT</span><span class="s">(</span><span class="w">one_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">perl_run</span><span class="s">(</span><span class="w">one_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">PERL_SET_CONTEXT</span><span class="s">(</span><span class="w">two_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">perl_run</span><span class="s">(</span><span class="w">two_perl</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="i">PERL_SET_CONTEXT</span><span class="s">(</span><span class="w">one_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">perl_destruct</span><span class="s">(</span><span class="w">one_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">PERL_SET_CONTEXT</span><span class="s">(</span><span class="w">two_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">perl_destruct</span><span class="s">(</span><span class="w">two_perl</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="i">PERL_SET_CONTEXT</span><span class="s">(</span><span class="w">one_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">perl_free</span><span class="s">(</span><span class="w">one_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">PERL_SET_CONTEXT</span><span class="s">(</span><span class="w">two_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">perl_free</span><span class="s">(</span><span class="w">two_perl</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">PERL_SYS_TERM</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>Note the calls to PERL_SET_CONTEXT().  These are necessary to initialize
the global state that tracks which interpreter is the "current" one on
the particular process or thread that may be running it.  It should
always be used if you have more than one interpreter and are making
perl API calls on both interpreters in an interleaved fashion.</p>
<p>PERL_SET_CONTEXT(interp) should also be called whenever <code class="inline"><span class="w">interp</span></code>
 is
used by a thread that did not create it (using either perl_alloc(), or
the more esoteric perl_clone()).</p>
<p>Compile as usual:</p>
<pre class="verbatim"><ol><li> <span class="i">% cc</span> -<span class="w">o</span> <span class="w">multiplicity</span> <span class="w">multiplicity</span>.<span class="w">c</span> <span class="q">`perl -MExtUtils::Embed -e ccopts -e ldopts`</span></li></ol></pre><p>Run it, Run it:</p>
<pre class="verbatim"><ol><li> % multiplicity</li><li> Hi, I'm one_perl</li><li> Hi, I'm two_perl</li></ol></pre><a name="Using-Perl-modules%2c-which-themselves-use-C-libraries%2c-from-your-C-program"></a><h2>Using Perl modules, which themselves use C libraries, from your C program</h2>
<p>If you've played with the examples above and tried to embed a script
that <i>use()</i>s a Perl module (such as <i>Socket</i>) which itself uses a C or C++ library,
this probably happened:</p>
<pre class="verbatim"><ol><li> <span class="w">Can&#39;t</span> <span class="w">load</span> <span class="w">module</span> <span class="w">Socket</span><span class="cm">,</span> <span class="w">dynamic</span> <span class="w">loading</span> not <span class="w">available</span> <span class="w">in</span> <span class="w">this</span> <span class="w">perl</span>.</li><li>  <span class="s">(</span><span class="w">You</span> <span class="w">may</span> <span class="w">need</span> <span class="w">to</span> <span class="w">build</span> <span class="w">a</span> <span class="w">new</span> <span class="w">perl</span> <span class="w">executable</span> <span class="w">which</span> <span class="w">either</span> <span class="w">supports</span></li><li>  <span class="w">dynamic</span> <span class="w">loading</span> or <span class="w">has</span> <span class="w">the</span> <span class="w">Socket</span> <span class="w">module</span> <span class="w">statically</span> <span class="w">linked</span> <span class="w">into</span> <span class="w">it</span>.<span class="s">)</span></li></ol></pre><p>What's wrong?</p>
<p>Your interpreter doesn't know how to communicate with these extensions
on its own.  A little glue will help.  Up until now you've been
calling <i>perl_parse()</i>, handing it NULL for the second argument:</p>
<pre class="verbatim"><ol><li> <span class="i">perl_parse</span><span class="s">(</span><span class="w">my_perl</span><span class="cm">,</span> <span class="w">NULL</span><span class="cm">,</span> <span class="w">argc</span><span class="cm">,</span> <span class="w">my_argv</span><span class="cm">,</span> <span class="w">NULL</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>That's where the glue code can be inserted to create the initial contact between
Perl and linked C/C++ routines.  Let's take a look some pieces of <i>perlmain.c</i>
to see how Perl does this:</p>
<pre class="verbatim"><ol><li> static void xs_init (pTHX);</li><li></li><li> EXTERN_C void boot_DynaLoader (pTHX_ CV* cv);</li><li> EXTERN_C void boot_Socket (pTHX_ CV* cv);</li><li></li><li></li><li> EXTERN_C void</li><li> xs_init(pTHX)</li><li> {</li><li>        char *file = __FILE__;</li><li>        /* DynaLoader is a special case */</li><li>        newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);</li><li>        newXS("Socket::bootstrap", boot_Socket, file);</li><li> }</li></ol></pre><p>Simply put: for each extension linked with your Perl executable
(determined during its initial configuration on your
computer or when adding a new extension),
a Perl subroutine is created to incorporate the extension's
routines.  Normally, that subroutine is named
<i>Module::bootstrap()</i> and is invoked when you say <i>use Module</i>.  In
turn, this hooks into an XSUB, <i>boot_Module</i>, which creates a Perl
counterpart for each of the extension's XSUBs.  Don't worry about this
part; leave that to the <i>xsubpp</i> and extension authors.  If your
extension is dynamically loaded, DynaLoader creates <i>Module::bootstrap()</i>
for you on the fly.  In fact, if you have a working DynaLoader then there
is rarely any need to link in any other extensions statically.</p>
<p>Once you have this code, slap it into the second argument of <i>perl_parse()</i>:</p>
<pre class="verbatim"><ol><li> <span class="i">perl_parse</span><span class="s">(</span><span class="w">my_perl</span><span class="cm">,</span> <span class="w">xs_init</span><span class="cm">,</span> <span class="w">argc</span><span class="cm">,</span> <span class="w">my_argv</span><span class="cm">,</span> <span class="w">NULL</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Then compile:</p>
<pre class="verbatim"><ol><li> % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`</li><li></li><li> % interp</li><li>   use Socket;</li><li>   use SomeDynamicallyLoadedModule;</li><li></li><li>   print "Now I can use extensions!\n"'</li></ol></pre><p><b>ExtUtils::Embed</b> can also automate writing the <i>xs_init</i> glue code.</p>
<pre class="verbatim"><ol><li> <span class="i">% perl</span> -<span class="w">MExtUtils::Embed</span> -e <span class="w">xsinit</span> -- -<span class="w">o</span> <span class="w">perlxsi</span>.<span class="w">c</span></li><li> % <span class="w">cc</span> -c <span class="w">perlxsi</span>.<span class="w">c</span> <span class="q">`perl -MExtUtils::Embed -e ccopts`</span></li><li> % <span class="w">cc</span> -c <span class="w">interp</span>.<span class="w">c</span>  <span class="q">`perl -MExtUtils::Embed -e ccopts`</span></li><li> % <span class="w">cc</span> -o <span class="w">interp</span> <span class="w">perlxsi</span>.<span class="w">o</span> <span class="w">interp</span>.<span class="w">o</span> <span class="q">`perl -MExtUtils::Embed -e ldopts`</span></li></ol></pre><p>Consult <a href="perlxs.html">perlxs</a>, <a href="perlguts.html">perlguts</a>, and <a href="perlapi.html">perlapi</a> for more details.</p>
<a name="Hiding-Perl_"></a><h1>Hiding Perl_</h1>
<p>If you completely hide the short forms of the Perl public API,
add -DPERL_NO_SHORT_NAMES to the compilation flags.  This means that
for example instead of writing</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/warn.html">warn</a><span class="s">(</span><span class="q">&quot;%d bottles of beer on the wall&quot;</span><span class="cm">,</span> <span class="w">bottlecount</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>you will have to write the explicit full form</p>
<pre class="verbatim"><ol><li>    <span class="i">Perl_warn</span><span class="s">(</span><span class="w">aTHX_</span> <span class="q">&quot;%d bottles of beer on the wall&quot;</span><span class="cm">,</span> <span class="w">bottlecount</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>(See <a href="perlguts.html#Background-and-PERL_IMPLICIT_CONTEXT">Background and PERL_IMPLICIT_CONTEXT in perlguts</a> for the explanation
of the <code class="inline"><span class="w">aTHX_</span></code>
. )  Hiding the short forms is very useful for avoiding
all sorts of nasty (C preprocessor or otherwise) conflicts with other
software packages (Perl defines about 2400 APIs with these short names,
take or leave few hundred, so there certainly is room for conflict.)</p>
<a name="MORAL"></a><h1>MORAL</h1>
<p>You can sometimes <i>write faster code</i> in C, but
you can always <i>write code faster</i> in Perl.  Because you can use
each from the other, combine them as you wish.</p>
<a name="AUTHOR"></a><h1>AUTHOR</h1>
<p>Jon Orwant &lt;<i>orwant@media.mit.edu</i>&gt; and Doug MacEachern
&lt;<i>dougm@covalent.net</i>&gt;, with small contributions from Tim Bunce, Tom
Christiansen, Guy Decoux, Hallvard Furuseth, Dov Grobgeld, and Ilya
Zakharevich.</p>
<p>Doug MacEachern has an article on embedding in Volume 1, Issue 4 of
The Perl Journal ( <a href="http://www.tpj.com/">http://www.tpj.com/</a> ).  Doug is also the developer of the
most widely-used Perl embedding: the mod_perl system
(perl.apache.org), which embeds Perl in the Apache web server.
Oracle, Binary Evolution, ActiveState, and Ben Sugars's nsapi_perl
have used this model for Oracle, Netscape and Internet Information
Server Perl plugins.</p>
<a name="COPYRIGHT"></a><h1>COPYRIGHT</h1>
<p>Copyright (C) 1995, 1996, 1997, 1998 Doug MacEachern and Jon Orwant.  All
Rights Reserved.</p>
<p>Permission is granted to make and distribute verbatim copies of this
documentation provided the copyright notice and this permission notice are
preserved on all copies.</p>
<p>Permission is granted to copy and distribute modified versions of this
documentation under the conditions for verbatim copying, provided also
that they are marked clearly as modified versions, that the authors'
names and title are unchanged (though subtitles and additional
authors' names may be added), and that the entire resulting derived
work is distributed under the terms of a permission notice identical
to this one.</p>
<p>Permission is granted to copy and distribute translations of this
documentation into another language, under the above conditions for
modified versions.</p>




  <div id="page_index" class="hud_container">
    <div id="page_index_header" class="hud_header">
      <div id="page_index_close" class="hud_close"><a href="#" onClick="pageIndex.hide();return false;"></a></div>
      <div id="page_index_title" class="hud_title"><span class="hud_span_top">Page index</span></div>
      <div id="page_index_topright" class="hud_topright"></div>
    </div>
    <div id="page_index_content" class="hud_content">
      <ul><li><a href="#NAME">NAME</a><li><a href="#DESCRIPTION">DESCRIPTION</a><ul><li><a href="#PREAMBLE">PREAMBLE</a><li><a href="#ROADMAP">ROADMAP</a><li><a href="#Compiling-your-C-program">Compiling your C program</a><li><a href="#Adding-a-Perl-interpreter-to-your-C-program">Adding a Perl interpreter to your C program</a><li><a href="#Calling-a-Perl-subroutine-from-your-C-program">Calling a Perl subroutine from your C program</a><li><a href="#Evaluating-a-Perl-statement-from-your-C-program">Evaluating a Perl statement from your C program</a><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><a href="#Fiddling-with-the-Perl-stack-from-your-C-program">Fiddling with the Perl stack from your C program</a><li><a href="#Maintaining-a-persistent-interpreter">Maintaining a persistent interpreter</a><li><a href="#Execution-of-END-blocks">Execution of END blocks</a><li><a href="#%240-assignments">$0 assignments</a><li><a href="#Maintaining-multiple-interpreter-instances">Maintaining multiple interpreter instances</a><li><a href="#Using-Perl-modules%2c-which-themselves-use-C-libraries%2c-from-your-C-program">Using Perl modules, which themselves use C libraries, from your C program</a></ul><li><a href="#Hiding-Perl_">Hiding Perl_</a><li><a href="#MORAL">MORAL</a><li><a href="#AUTHOR">AUTHOR</a><li><a href="#COPYRIGHT">COPYRIGHT</a></ul>
    </div>
    <div id="page_index_footer" class="hud_footer">
      <div id="page_index_bottomleft" class="hud_bottomleft"></div>
      <div id="page_index_bottom" class="hud_bottom"><span class="hud_span_bottom"></span></div>
      <div id="page_index_resize" class="hud_resize"></div>
    </div>
  </div>


	    &nbsp;
          </div>
          <div id="content_footer">
          </div>
        </div>
        <div class="clear"></div>
      </div>
      
    <div id="footer">
      <div id="footer_content">
        <div id="footer_strapline">
          perldoc.perl.org - Official documentation for the Perl programming language
        </div>
        <div id="footer_links">
          <div id="address">
            <p class="name">Contact details</p>
            <p class="address">
	      Site maintained by <a href="http://perl.jonallen.info">Jon Allen (JJ)</a><br>
	      See the <a href="http://perl.jonallen.info/projects/perldoc">project page</a> for more details
	    </p>
            <p class="contact">
              Documentation maintained by the <a href="http://lists.cpan.org/showlist.cgi?name=perl5-porters">Perl 5 Porters</a>
            </p>
          </div>
          <ul class="f1">
            <li>Manual
              <ul class="f2">
                <li><a href="index-overview.html">Overview</a>
                <li><a href="index-tutorials.html">Tutorials</a>
                <li><a href="index-faq.html">FAQs</a>
                <li><a href="index-history.html">Changes</a>
              </ul>
            <li>Reference
              <ul class="f2">
                <li><a href="index-language.html">Language</a>
                <li><a href="index-functions.html">Functions</a>
                <li><a href="perlop.html">Operators</a>
                <li><a href="perlvar.html">Variables</a>
              </ul>
            <li>Modules
              <ul class="f2">
                <li><a href="index-modules-A.html">Modules</a>
                <li><a href="index-pragmas.html">Pragmas</a>
                <li><a href="index-utilities.html">Utilities</a>
              </ul>
            <li>Misc
              <ul class="f2">
                <li><a href="index-licence.html">License</a>
                <li><a href="index-internals.html">Internals</a>
                <li><a href="index-platforms.html">Platforms</a>
              </ul>          </ul>
          <div class="clear"></div>
        </div>
      </div>
      <div id="footer_end">
      </div>
    </div>
      
    </div>
      <script language="JavaScript" type="text/javascript" src="static/exploreperl.js"></script>
      <script language="JavaScript" src="static/combined-20100403.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
  perldoc.setPath(0);
  perldoc.pageName    = 'perlembed';
  perldoc.pageAddress = 'perlembed.html';
  perldoc.contentPage = 1;
  explorePerl.render();
  explorePerl.addEvents('explore_anchor');
</script>
    
  </body>
</html>