File: perlxstut.html

package info (click to toggle)
perl-doc-html 5.26.0-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 39,400 kB
  • sloc: xml: 36; makefile: 7
file content (1294 lines) | stat: -rw-r--r-- 111,555 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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>perlxstut - 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>perlxstut</h1>
              </div>
              <div id="perl_version">
                Perl 5 version 26.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;
      
    
    perlxstut
  

            </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>perlxstut</h1>


  <!--    -->
<ul><li><a href="#NAME">NAME</a><li><a href="#DESCRIPTION">DESCRIPTION</a><li><a href="#SPECIAL-NOTES">SPECIAL NOTES</a><ul><li><a href="#make">make</a><li><a href="#Version-caveat">Version caveat</a><li><a href="#Dynamic-Loading-versus-Static-Loading">Dynamic Loading versus Static Loading</a><li><a href="#Threads-and-PERL_NO_GET_CONTEXT">Threads and PERL_NO_GET_CONTEXT</a></ul><li><a href="#TUTORIAL">TUTORIAL</a><ul><li><a href="#EXAMPLE-1">EXAMPLE 1</a><li><a href="#EXAMPLE-2">EXAMPLE 2</a><li><a href="#What-has-gone-on%3f">What has gone on?</a><li><a href="#Writing-good-test-scripts">Writing good test scripts</a><li><a href="#EXAMPLE-3">EXAMPLE 3</a><li><a href="#What's-new-here%3f">What's new here?</a><li><a href="#Input-and-Output-Parameters">Input and Output Parameters</a><li><a href="#The-XSUBPP-Program">The XSUBPP Program</a><li><a href="#The-TYPEMAP-file">The TYPEMAP file</a><li><a href="#Warning-about-Output-Arguments">Warning about Output Arguments</a><li><a href="#EXAMPLE-4">EXAMPLE 4</a><li><a href="#What-has-happened-here%3f">What has happened here?</a><li><a href="#Anatomy-of-.xs-file">Anatomy of .xs file</a><li><a href="#Getting-the-fat-out-of-XSUBs">Getting the fat out of XSUBs</a><li><a href="#More-about-XSUB-arguments">More about XSUB arguments</a><li><a href="#The-Argument-Stack">The Argument Stack</a><li><a href="#Extending-your-Extension">Extending your Extension</a><li><a href="#Documenting-your-Extension">Documenting your Extension</a><li><a href="#Installing-your-Extension">Installing your Extension</a><li><a href="#EXAMPLE-5">EXAMPLE 5</a><li><a href="#New-Things-in-this-Example">New Things in this Example</a><li><a href="#EXAMPLE-6">EXAMPLE 6</a><li><a href="#New-Things-in-this-Example">New Things in this Example</a><li><a href="#EXAMPLE-7-(Coming-Soon)">EXAMPLE 7 (Coming Soon)</a><li><a href="#EXAMPLE-8-(Coming-Soon)">EXAMPLE 8 (Coming Soon)</a><li><a href="#EXAMPLE-9-Passing-open-files-to-XSes">EXAMPLE 9 Passing open files to XSes</a><li><a href="#Troubleshooting-these-Examples">Troubleshooting these Examples</a></ul><li><a href="#See-also">See also</a><li><a href="#Author">Author</a><ul><li><a href="#Last-Changed">Last Changed</a></ul></ul><a name="NAME"></a><h1>NAME</h1>
<p>perlxstut - Tutorial for writing XSUBs</p>
<a name="DESCRIPTION"></a><h1>DESCRIPTION</h1>
<p>This tutorial will educate the reader on the steps involved in creating
a Perl extension.  The reader is assumed to have access to <a href="perlguts.html">perlguts</a>,
<a href="perlapi.html">perlapi</a> and <a href="perlxs.html">perlxs</a>.</p>
<p>This tutorial starts with very simple examples and becomes more complex,
with each new example adding new features.  Certain concepts may not be
completely explained until later in the tutorial in order to slowly ease
the reader into building extensions.</p>
<p>This tutorial was written from a Unix point of view.  Where I know them
to be otherwise different for other platforms (e.g. Win32), I will list
them.  If you find something that was missed, please let me know.</p>
<a name="SPECIAL-NOTES"></a><h1>SPECIAL NOTES</h1>
<a name="make"></a><h2>make</h2>
<p>This tutorial assumes that the make program that Perl is configured to
use is called <code class="inline"><span class="w">make</span></code>
.  Instead of running "make" in the examples that
follow, you may have to substitute whatever make program Perl has been
configured to use.  Running <b>perl -V:make</b> should tell you what it is.</p>
<a name="Version-caveat"></a><h2>Version caveat</h2>
<p>When writing a Perl extension for general consumption, one should expect that
the extension will be used with versions of Perl different from the
version available on your machine.  Since you are reading this document,
the version of Perl on your machine is probably 5.005 or later, but the users
of your extension may have more ancient versions.</p>
<p>To understand what kinds of incompatibilities one may expect, and in the rare
case that the version of Perl on your machine is older than this document,
see the section on "Troubleshooting these Examples" for more information.</p>
<p>If your extension uses some features of Perl which are not available on older
releases of Perl, your users would appreciate an early meaningful warning.
You would probably put this information into the <i>README</i> file, but nowadays
installation of extensions may be performed automatically, guided by <i>CPAN.pm</i>
module or other tools.</p>
<p>In MakeMaker-based installations, <i>Makefile.PL</i> provides the earliest
opportunity to perform version checks.  One can put something like this
in <i>Makefile.PL</i> for this purpose:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/eval.html">eval</a> <span class="s">{</span> <a class="l_k" href="functions/require.html">require</a> <span class="n">5.007</span> <span class="s">}</span></li><li>        <a class="l_k" href="functions/or.html">or</a> <a class="l_k" href="functions/die.html">die</a> <span class="h">&lt;&lt;EOD</span><span class="sc">;</span></li><li><span class="hh">    ############</span></li><li><span class="hh">    ### This module uses frobnication framework which is not available</span></li><li><span class="hh">    ### before version 5.007 of Perl.  Upgrade your Perl before</span></li><li><span class="hh">    ### installing Kara::Mba.</span></li><li><span class="hh">    ############</span></li><li><span class="hh">    EOD</span></li></ol></pre><a name="Dynamic-Loading-versus-Static-Loading"></a><h2>Dynamic Loading versus Static Loading</h2>
<p>It is commonly thought that if a system does not have the capability to
dynamically load a library, you cannot build XSUBs.  This is incorrect.
You <i>can</i> build them, but you must link the XSUBs subroutines with the
rest of Perl, creating a new executable.  This situation is similar to
Perl 4.</p>
<p>This tutorial can still be used on such a system.  The XSUB build mechanism
will check the system and build a dynamically-loadable library if possible,
or else a static library and then, optionally, a new statically-linked
executable with that static library linked in.</p>
<p>Should you wish to build a statically-linked executable on a system which
can dynamically load libraries, you may, in all the following examples,
where the command "<code class="inline"><span class="w">make</span></code>
" with no arguments is executed, run the command
"<code class="inline"><span class="w">make</span> <span class="w">perl</span></code>
" instead.</p>
<p>If you have generated such a statically-linked executable by choice, then
instead of saying "<code class="inline"><span class="w">make</span> <span class="w">test</span></code>
", you should say "<code class="inline"><span class="w">make</span> <span class="w">test_static</span></code>
".
On systems that cannot build dynamically-loadable libraries at all, simply
saying "<code class="inline"><span class="w">make</span> <span class="w">test</span></code>
" is sufficient.</p>
<a name="Threads-and-PERL_NO_GET_CONTEXT"></a><h2>Threads and PERL_NO_GET_CONTEXT</h2>
<p>For threaded builds, perl requires the context pointer for the current
thread, without <code class="inline"><span class="w">PERL_NO_GET_CONTEXT</span></code>
, perl will call a function to
retrieve the context.</p>
<p>For improved performance, include:</p>
<pre class="verbatim"><ol><li>  <span class="c">#define PERL_NO_GET_CONTEXT</span></li></ol></pre><p>as shown below.</p>
<p>For more details, see <a href="perlguts.html#How-multiple-interpreters-and-concurrency-are-supported">perlguts</a>.</p>
<a name="TUTORIAL"></a><h1>TUTORIAL</h1>
<p>Now let's go on with the show!</p>
<a name="EXAMPLE-1"></a><h2>EXAMPLE 1</h2>
<p>Our first extension will be very simple.  When we call the routine in the
extension, it will print out a well-known message and return.</p>
<p>Run "<code class="inline"><span class="w">h2xs</span> -A -<span class="w">n</span> <span class="w">Mytest</span></code>
".  This creates a directory named Mytest,
possibly under ext/ if that directory exists in the current working
directory.  Several files will be created under the Mytest dir, including
MANIFEST, Makefile.PL, lib/Mytest.pm, Mytest.xs, t/Mytest.t, and Changes.</p>
<p>The MANIFEST file contains the names of all the files just created in the
Mytest directory.</p>
<p>The file Makefile.PL should look something like this:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">ExtUtils::MakeMaker</span><span class="sc">;</span></li><li>    <span class="c"># See lib/ExtUtils/MakeMaker.pm for details of how to influence</span></li><li>    <span class="c"># the contents of the Makefile that is written.</span></li><li>    <span class="i">WriteMakefile</span><span class="s">(</span></li><li>	<span class="w">NAME</span>         <span class="cm">=&gt;</span> <span class="q">'Mytest'</span><span class="cm">,</span></li><li>	<span class="w">VERSION_FROM</span> <span class="cm">=&gt;</span> <span class="q">'Mytest.pm'</span><span class="cm">,</span> <span class="c"># finds $VERSION</span></li><li>	<span class="w">LIBS</span>         <span class="cm">=&gt;</span> <span class="s">[</span><span class="q">''</span><span class="s">]</span><span class="cm">,</span>   <span class="c"># e.g., '-lm'</span></li><li>	<span class="w">DEFINE</span>       <span class="cm">=&gt;</span> <span class="q">''</span><span class="cm">,</span>     <span class="c"># e.g., '-DHAVE_SOMETHING'</span></li><li>	<span class="w">INC</span>          <span class="cm">=&gt;</span> <span class="q">''</span><span class="cm">,</span>     <span class="c"># e.g., '-I/usr/include/other'</span></li><li>    <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The file Mytest.pm should start with something like this:</p>
<pre class="verbatim"><ol><li><a name="package-Mytest"></a>    package <span class="i">Mytest</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="n">5.008008</span><span class="sc">;</span></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/use.html">use</a> <span class="w">warnings</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/require.html">require</a> <span class="w">Exporter</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/our.html">our</a> <span class="i">@ISA</span> = <span class="q">qw(Exporter)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/our.html">our</a> <span class="i">%EXPORT_TAGS</span> = <span class="s">(</span> <span class="q">&#39;all&#39;</span> <span class="cm">=&gt;</span> <span class="s">[</span> <span class="q">qw(</span></li><li></li><li>    <span class="q">)</span> <span class="s">]</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/our.html">our</a> <span class="i">@EXPORT_OK</span> = <span class="s">(</span> <span class="i">@</span>{ <span class="i">$EXPORT_TAGS</span>{<span class="q">&#39;all&#39;</span>} } <span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/our.html">our</a> <span class="i">@EXPORT</span> = <span class="q">qw(</span></li><li></li><li>    <span class="q">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/our.html">our</a> <span class="i">$VERSION</span> = <span class="q">&#39;0.01&#39;</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/require.html">require</a> <span class="w">XSLoader</span><span class="sc">;</span></li><li>    <span class="i">XSLoader::load</span><span class="s">(</span><span class="q">&#39;Mytest&#39;</span><span class="cm">,</span> <span class="i">$VERSION</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="c"># Preloaded methods go here.</span></li><li></li><li>    <span class="n">1</span><span class="sc">;</span></li><li><a name="__END__"></a>    __END__</li><li><span class="q">    # Below is the stub of documentation for your module. You better</span></li><li><span class="q">    # edit it!</span></li></ol></pre><p>The rest of the .pm file contains sample code for providing documentation for
the extension.</p>
<p>Finally, the Mytest.xs file should look something like this:</p>
<pre class="verbatim"><ol><li>    <span class="c">#define PERL_NO_GET_CONTEXT</span></li><li>    <span class="c">#include &quot;EXTERN.h&quot;</span></li><li>    <span class="c">#include &quot;perl.h&quot;</span></li><li>    <span class="c">#include &quot;XSUB.h&quot;</span></li><li></li><li>    <span class="c">#include &quot;ppport.h&quot;</span></li><li></li><li>    <span class="w">MODULE</span> = <span class="w">Mytest</span>		<span class="w">PACKAGE</span> = <span class="w">Mytest</span></li></ol></pre><p>Let's edit the .xs file by adding this to the end of the file:</p>
<pre class="verbatim"><ol><li>    void</li><li>    hello()</li><li>	CODE:</li><li>	    printf("Hello, world!\n");</li></ol></pre><p>It is okay for the lines starting at the "CODE:" line to not be indented.
However, for readability purposes, it is suggested that you indent CODE:
one level and the lines following one more level.</p>
<p>Now we'll run "<code class="inline"><span class="w">perl</span> <span class="w">Makefile</span>.<span class="w">PL</span></code>
".  This will create a real Makefile,
which make needs.  Its output looks something like:</p>
<pre class="verbatim"><ol><li>    % perl Makefile.PL</li><li>    Checking if your kit is complete...</li><li>    Looks good</li><li>    Writing Makefile for Mytest</li><li>    %</li></ol></pre><p>Now, running make will produce output that looks something like this (some
long lines have been shortened for clarity and some extraneous lines have
been deleted):</p>
<pre class="verbatim"><ol><li> <span class="i">% make</span></li><li> <span class="w">cp</span> <span class="w">lib</span>/<span class="w">Mytest</span>.<span class="w">pm</span> <span class="w">blib</span>/<span class="w">lib</span>/<span class="w">Mytest</span>.<span class="w">pm</span></li><li> <span class="w">perl</span> <span class="w">xsubpp</span>  -<span class="w">typemap</span> <span class="w">typemap</span>  <span class="w">Mytest</span>.<span class="w">xs</span> &gt; <span class="w">Mytest</span>.<span class="w">xsc</span> &amp;&amp; \</li><li> <span class="w">mv</span> <span class="w">Mytest</span>.<span class="w">xsc</span> <span class="w">Mytest</span>.<span class="w">c</span></li><li> <span class="w">Please</span> <span class="w">specify</span> <span class="w">prototyping</span> <span class="w">behavior</span> <a class="l_k" href="functions/for.html">for</a> <span class="w">Mytest</span>.<span class="w">xs</span> <span class="s">(</span><span class="w">see</span> <span class="w">perlxs</span> <span class="w">manual</span><span class="s">)</span></li><li> <span class="w">cc</span> -c     <span class="w">Mytest</span>.<span class="w">c</span></li><li> <span class="w">Running</span> <span class="w">Mkbootstrap</span> <a class="l_k" href="functions/for.html">for</a> <span class="w">Mytest</span> <span class="s">(</span><span class="s">)</span></li><li> <a class="l_k" href="functions/chmod.html">chmod</a> <span class="n">644</span> <span class="w">Mytest</span>.<span class="w">bs</span></li><li> <span class="w">rm</span> -f <span class="w">blib</span>/<span class="w">arch</span>/<span class="w">auto</span>/<span class="w">Mytest</span>/<span class="w">Mytest</span>.<span class="w">so</span></li><li> <span class="w">cc</span> -<span class="w">shared</span> -<span class="w">L</span>/<span class="w">usr</span>/<a class="l_k" href="functions/local.html">local</a><span class="q">/lib Mytest.o -o blib/</span><span class="w">arch</span>/<span class="w">auto</span>/<span class="w">Mytest</span>/<span class="w">Mytest</span>.<span class="w">so</span></li><li></li><li> <a class="l_k" href="functions/chmod.html">chmod</a> <span class="n">755</span> <span class="w">blib</span>/<span class="w">arch</span>/<span class="w">auto</span>/<span class="w">Mytest</span>/<span class="w">Mytest</span>.<span class="w">so</span></li><li> <span class="w">cp</span> <span class="w">Mytest</span>.<span class="w">bs</span> <span class="w">blib</span>/<span class="w">arch</span>/<span class="w">auto</span>/<span class="w">Mytest</span>/<span class="w">Mytest</span>.<span class="w">bs</span></li><li> <a class="l_k" href="functions/chmod.html">chmod</a> <span class="n">644</span> <span class="w">blib</span>/<span class="w">arch</span>/<span class="w">auto</span>/<span class="w">Mytest</span>/<span class="w">Mytest</span>.<span class="w">bs</span></li><li> <span class="w">Manifying</span> <span class="w">blib</span>/<span class="w">man3</span>/<span class="w">Mytest</span><span class="n">.3</span><span class="w">pm</span></li><li> %</li></ol></pre><p>You can safely ignore the line about "prototyping behavior" - it is
explained in <a href="perlxs.html#The-PROTOTYPES%3a-Keyword">The PROTOTYPES: Keyword in perlxs</a>.</p>
<p>Perl has its own special way of easily writing test scripts, but for this
example only, we'll create our own test script.  Create a file called hello
that looks like this:</p>
<pre class="verbatim"><ol><li>    <span class="c">#! /opt/perl5/bin/perl</span></li><li></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">ExtUtils::testlib</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Mytest</span><span class="sc">;</span></li><li></li><li>    <span class="i">Mytest::hello</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Now we make the script executable (<code class="inline"><a class="l_k" href="functions/chmod.html">chmod</a> +<span class="w">x</span> <span class="w">hello</span></code>
), run the script
and we should see the following output:</p>
<pre class="verbatim"><ol><li>    <span class="i">% .</span>/<span class="w">hello</span></li><li>    <span class="w">Hello</span><span class="cm">,</span> <span class="w">world</span>!</li><li>    <span class="i">%</span></li></ol></pre><a name="EXAMPLE-2"></a><h2>EXAMPLE 2</h2>
<p>Now let's add to our extension a subroutine that will take a single numeric
argument as input and return 1 if the number is even or 0 if the number
is odd.</p>
<p>Add the following to the end of Mytest.xs:</p>
<pre class="verbatim"><ol><li>    int</li><li>    is_even(input)</li><li>	    int input</li><li>	CODE:</li><li>	    RETVAL = (input % 2 == 0);</li><li>	OUTPUT:</li><li>	    RETVAL</li></ol></pre><p>There does not need to be whitespace at the start of the "<code class="inline"><a class="l_k" href="functions/int.html">int</a> <span class="w">input</span></code>
"
line, but it is useful for improving readability.  Placing a semi-colon at
the end of that line is also optional.  Any amount and kind of whitespace
may be placed between the "<code class="inline"><a class="l_k" href="functions/int.html">int</a></code>" and "<code class="inline"><span class="w">input</span></code>
".</p>
<p>Now re-run make to rebuild our new shared library.</p>
<p>Now perform the same steps as before, generating a Makefile from the
Makefile.PL file, and running make.</p>
<p>In order to test that our extension works, we now need to look at the
file Mytest.t.  This file is set up to imitate the same kind of testing
structure that Perl itself has.  Within the test script, you perform a
number of tests to confirm the behavior of the extension, printing "ok"
when the test is correct, "not ok" when it is not.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Test::More</span> <span class="w">tests</span> <span class="cm">=&gt;</span> <span class="n">4</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/BEGIN.html">BEGIN</a> <span class="s">{</span> <span class="i">use_ok</span><span class="s">(</span><span class="q">&#39;Mytest&#39;</span><span class="s">)</span> <span class="s">}</span><span class="sc">;</span></li><li></li><li>    <span class="c">#########################</span></li><li></li><li>    <span class="c"># Insert your test code below, the Test::More module is use()ed here</span></li><li>    <span class="c"># so read its man page ( perldoc Test::More ) for help writing this</span></li><li>    <span class="c"># test script.</span></li><li></li><li>    <span class="i">is</span><span class="s">(</span><span class="i">&amp;Mytest::is_even</span><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">is</span><span class="s">(</span><span class="i">&amp;Mytest::is_even</span><span class="s">(</span><span class="n">1</span><span class="s">)</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">is</span><span class="s">(</span><span class="i">&amp;Mytest::is_even</span><span class="s">(</span><span class="n">2</span><span class="s">)</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>We will be calling the test script through the command "<code class="inline"><span class="w">make</span> <span class="w">test</span></code>
".  You
should see output that looks something like this:</p>
<pre class="verbatim"><ol><li> <span class="i">%make</span> <span class="w">test</span></li><li> <span class="w">PERL_DL_NONLAZY</span>=<span class="n">1</span> /<span class="w">usr</span>/<span class="w">bin</span>/<span class="w">perl</span> <span class="q">&quot;-MExtUtils::Command::MM&quot;</span> <span class="q">&quot;-e&quot;</span></li><li> <span class="q">&quot;test_harness(0, &#39;blib/lib&#39;, &#39;blib/arch&#39;)&quot;</span> <span class="w">t</span><span class="q">/*.t</span></li><li> <span class="q"> t/</span><span class="w">Mytest</span>....<span class="w">ok</span></li><li> <span class="w">All</span> <span class="w">tests</span> <span class="w">successful</span>.</li><li> <span class="w">Files</span>=<span class="n">1</span><span class="cm">,</span> <span class="w">Tests</span>=<span class="n">4</span><span class="cm">,</span> <span class="n">0</span> <span class="w">wallclock</span> <span class="w">secs</span> <span class="s">(</span> <span class="n">0.03</span> <span class="w">cusr</span> + <span class="n">0.00</span> <span class="w">csys</span> = <span class="n">0.03</span> <span class="w">CPU</span><span class="s">)</span></li><li> %</li></ol></pre><a name="What-has-gone-on%3f"></a><h2>What has gone on?</h2>
<p>The program h2xs is the starting point for creating extensions.  In later
examples we'll see how we can use h2xs to read header files and generate
templates to connect to C routines.</p>
<p>h2xs creates a number of files in the extension directory.  The file
Makefile.PL is a perl script which will generate a true Makefile to build
the extension.  We'll take a closer look at it later.</p>
<p>The .pm and .xs files contain the meat of the extension.  The .xs file holds
the C routines that make up the extension.  The .pm file contains routines
that tell Perl how to load your extension.</p>
<p>Generating the Makefile and running <code class="inline"><span class="w">make</span></code>
 created a directory called blib
(which stands for "build library") in the current working directory.  This
directory will contain the shared library that we will build.  Once we have
tested it, we can install it into its final location.</p>
<p>Invoking the test script via "<code class="inline"><span class="w">make</span> <span class="w">test</span></code>
" did something very important.
It invoked perl with all those <code class="inline">-<span class="w">I</span></code>
 arguments so that it could find the
various files that are part of the extension.  It is <i>very</i> important that
while you are still testing extensions that you use "<code class="inline"><span class="w">make</span> <span class="w">test</span></code>
".  If you
try to run the test script all by itself, you will get a fatal error.
Another reason it is important to use "<code class="inline"><span class="w">make</span> <span class="w">test</span></code>
" to run your test
script is that if you are testing an upgrade to an already-existing version,
using "<code class="inline"><span class="w">make</span> <span class="w">test</span></code>
" ensures that you will test your new extension, not the
already-existing version.</p>
<p>When Perl sees a <code class="inline"><a class="l_k" href="functions/use.html">use</a> <span class="w">extension</span><span class="sc">;</span></code>
, it searches for a file with the same name
as the <code class="inline"><a class="l_k" href="functions/use.html">use</a></code>'d extension that has a .pm suffix.  If that file cannot be found,
Perl dies with a fatal error.  The default search path is contained in the
<code class="inline"><span class="i">@INC</span></code>
 array.</p>
<p>In our case, Mytest.pm tells perl that it will need the Exporter and Dynamic
Loader extensions.  It then sets the <code class="inline"><span class="i">@ISA</span></code>
 and <code class="inline"><span class="i">@EXPORT</span></code>
 arrays and the
<code class="inline"><span class="i">$VERSION</span></code>
 scalar; finally it tells perl to bootstrap the module.  Perl
will call its dynamic loader routine (if there is one) and load the shared
library.</p>
<p>The two arrays <code class="inline"><span class="i">@ISA</span></code>
 and <code class="inline"><span class="i">@EXPORT</span></code>
 are very important.  The <code class="inline"><span class="i">@ISA</span></code>

array contains a list of other packages in which to search for methods (or
subroutines) that do not exist in the current package.  This is usually
only important for object-oriented extensions (which we will talk about
much later), and so usually doesn't need to be modified.</p>
<p>The <code class="inline"><span class="i">@EXPORT</span></code>
 array tells Perl which of the extension's variables and
subroutines should be placed into the calling package's namespace.  Because
you don't know if the user has already used your variable and subroutine
names, it's vitally important to carefully select what to export.  Do <i>not</i>
export method or variable names <i>by default</i> without a good reason.</p>
<p>As a general rule, if the module is trying to be object-oriented then don't
export anything.  If it's just a collection of functions and variables, then
you can export them via another array, called <code class="inline"><span class="i">@EXPORT_OK</span></code>
.  This array
does not automatically place its subroutine and variable names into the
namespace unless the user specifically requests that this be done.</p>
<p>See <a href="perlmod.html">perlmod</a> for more information.</p>
<p>The <code class="inline"><span class="i">$VERSION</span></code>
 variable is used to ensure that the .pm file and the shared
library are "in sync" with each other.  Any time you make changes to
the .pm or .xs files, you should increment the value of this variable.</p>
<a name="Writing-good-test-scripts"></a><h2>Writing good test scripts</h2>
<p>The importance of writing good test scripts cannot be over-emphasized.  You
should closely follow the "ok/not ok" style that Perl itself uses, so that
it is very easy and unambiguous to determine the outcome of each test case.
When you find and fix a bug, make sure you add a test case for it.</p>
<p>By running "<code class="inline"><span class="w">make</span> <span class="w">test</span></code>
", you ensure that your Mytest.t script runs and uses
the correct version of your extension.  If you have many test cases,
save your test files in the "t" directory and use the suffix ".t".
When you run "<code class="inline"><span class="w">make</span> <span class="w">test</span></code>
", all of these test files will be executed.</p>
<a name="EXAMPLE-3"></a><h2>EXAMPLE 3</h2>
<p>Our third extension will take one argument as its input, round off that
value, and set the <i>argument</i> to the rounded value.</p>
<p>Add the following to the end of Mytest.xs:</p>
<pre class="verbatim"><ol><li>	void</li><li>	round(arg)</li><li>		double  arg</li><li>	    CODE:</li><li>		if (arg &gt; 0.0) {</li><li>			arg = floor(arg + 0.5);</li><li>		} else if (arg &lt; 0.0) {</li><li>			arg = ceil(arg - 0.5);</li><li>		} else {</li><li>			arg = 0.0;</li><li>		}</li><li>	    OUTPUT:</li><li>		arg</li></ol></pre><p>Edit the Makefile.PL file so that the corresponding line looks like this:</p>
<pre class="verbatim"><ol><li>	<span class="q">&#39;LIBS&#39;</span>      <span class="cm">=&gt;</span> <span class="s">[</span><span class="q">&#39;-lm&#39;</span><span class="s">]</span><span class="cm">,</span>   <span class="c"># e.g., &#39;-lm&#39;</span></li></ol></pre><p>Generate the Makefile and run make.  Change the test number in Mytest.t to
"9" and add the following tests:</p>
<pre class="verbatim"><ol><li>	<span class="i">$i</span> = <span class="n">-1.5</span><span class="sc">;</span> <span class="i">&amp;Mytest::round</span><span class="s">(</span><span class="i">$i</span><span class="s">)</span><span class="sc">;</span> <span class="i">is</span><span class="s">(</span> <span class="i">$i</span><span class="cm">,</span> <span class="n">-2.0</span> <span class="s">)</span><span class="sc">;</span></li><li>	<span class="i">$i</span> = <span class="n">-1.1</span><span class="sc">;</span> <span class="i">&amp;Mytest::round</span><span class="s">(</span><span class="i">$i</span><span class="s">)</span><span class="sc">;</span> <span class="i">is</span><span class="s">(</span> <span class="i">$i</span><span class="cm">,</span> <span class="n">-1.0</span> <span class="s">)</span><span class="sc">;</span></li><li>	<span class="i">$i</span> = <span class="n">0.0</span><span class="sc">;</span> <span class="i">&amp;Mytest::round</span><span class="s">(</span><span class="i">$i</span><span class="s">)</span><span class="sc">;</span>  <span class="i">is</span><span class="s">(</span> <span class="i">$i</span><span class="cm">,</span>  <span class="n">0.0</span> <span class="s">)</span><span class="sc">;</span></li><li>	<span class="i">$i</span> = <span class="n">0.5</span><span class="sc">;</span> <span class="i">&amp;Mytest::round</span><span class="s">(</span><span class="i">$i</span><span class="s">)</span><span class="sc">;</span>  <span class="i">is</span><span class="s">(</span> <span class="i">$i</span><span class="cm">,</span>  <span class="n">1.0</span> <span class="s">)</span><span class="sc">;</span></li><li>	<span class="i">$i</span> = <span class="n">1.2</span><span class="sc">;</span> <span class="i">&amp;Mytest::round</span><span class="s">(</span><span class="i">$i</span><span class="s">)</span><span class="sc">;</span>  <span class="i">is</span><span class="s">(</span> <span class="i">$i</span><span class="cm">,</span>  <span class="n">1.0</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Running "<code class="inline"><span class="w">make</span> <span class="w">test</span></code>
" should now print out that all nine tests are okay.</p>
<p>Notice that in these new test cases, the argument passed to round was a
scalar variable.  You might be wondering if you can round a constant or
literal.  To see what happens, temporarily add the following line to Mytest.t:</p>
<pre class="verbatim"><ol><li>	<span class="i">&amp;Mytest::round</span><span class="s">(</span><span class="n">3</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Run "<code class="inline"><span class="w">make</span> <span class="w">test</span></code>
" and notice that Perl dies with a fatal error.  Perl won't
let you change the value of constants!</p>
<a name="What's-new-here%3f"></a><h2>What's new here?</h2>
<ul>
<li>
<p>We've made some changes to Makefile.PL.  In this case, we've specified an
extra library to be linked into the extension's shared library, the math
library libm in this case.  We'll talk later about how to write XSUBs that
can call every routine in a library.</p>
</li>
<li>
<p>The value of the function is not being passed back as the function's return
value, but by changing the value of the variable that was passed into the
function.  You might have guessed that when you saw that the return value
of round is of type "void".</p>
</li>
</ul>
<a name="Input-and-Output-Parameters"></a><h2>Input and Output Parameters</h2>
<p>You specify the parameters that will be passed into the XSUB on the line(s)
after you declare the function's return value and name.  Each input parameter
line starts with optional whitespace, and may have an optional terminating
semicolon.</p>
<p>The list of output parameters occurs at the very end of the function, just
after the OUTPUT: directive.  The use of RETVAL tells Perl that you
wish to send this value back as the return value of the XSUB function.  In
Example 3, we wanted the "return value" placed in the original variable
which we passed in, so we listed it (and not RETVAL) in the OUTPUT: section.</p>
<a name="The-XSUBPP-Program"></a><h2>The XSUBPP Program</h2>
<p>The <b>xsubpp</b> program takes the XS code in the .xs file and translates it into
C code, placing it in a file whose suffix is .c.  The C code created makes
heavy use of the C functions within Perl.</p>
<a name="The-TYPEMAP-file"></a><h2>The TYPEMAP file</h2>
<p>The <b>xsubpp</b> program uses rules to convert from Perl's data types (scalar,
array, etc.) to C's data types (int, char, etc.).  These rules are stored
in the typemap file ($PERLLIB/ExtUtils/typemap).  There's a brief discussion
below, but all the nitty-gritty details can be found in <a href="perlxstypemap.html">perlxstypemap</a>.
If you have a new-enough version of perl (5.16 and up) or an upgraded
XS compiler (<code class="inline"><span class="w">ExtUtils::ParseXS</span></code>
 3.13_01 or better), then you can inline
typemaps in your XS instead of writing separate files.
Either way, this typemap thing is split into three parts:</p>
<p>The first section maps various C data types to a name, which corresponds
somewhat with the various Perl types.  The second section contains C code
which <b>xsubpp</b> uses to handle input parameters.  The third section contains
C code which <b>xsubpp</b> uses to handle output parameters.</p>
<p>Let's take a look at a portion of the .c file created for our extension.
The file name is Mytest.c:</p>
<pre class="verbatim"><ol><li>	<span class="i">XS</span><span class="s">(</span><span class="w">XS_Mytest_round</span><span class="s">)</span></li><li>	<span class="s">{</span></li><li>	    <span class="w">dXSARGS</span><span class="sc">;</span></li><li>	    <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="w">items</span> != <span class="n">1</span><span class="s">)</span></li><li>		<span class="i">Perl_croak</span><span class="s">(</span><span class="w">aTHX_</span> <span class="q">&quot;Usage: Mytest::round(arg)&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>	    <span class="i">PERL_UNUSED_VAR</span><span class="s">(</span><span class="w">cv</span><span class="s">)</span><span class="sc">;</span> <span class="q">/* -W */</span></li><li>	    <span class="s">{</span></li><li>		<span class="w">double</span>  <span class="w">arg</span> = <span class="s">(</span><span class="w">double</span><span class="s">)</span><span class="i">SvNV</span><span class="s">(</span><span class="i">ST</span><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span>	<span class="q">/* XXXXX */</span></li><li>		<a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="w">arg</span> &gt; <span class="n">0.0</span><span class="s">)</span> <span class="s">{</span></li><li>			<span class="w">arg</span> = <span class="i">floor</span><span class="s">(</span><span class="w">arg</span> + <span class="n">0.5</span><span class="s">)</span><span class="sc">;</span></li><li>		<span class="s">}</span> <a class="l_k" href="functions/else.html">else</a> <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="w">arg</span> &lt; <span class="n">0.0</span><span class="s">)</span> <span class="s">{</span></li><li>			<span class="w">arg</span> = <span class="i">ceil</span><span class="s">(</span><span class="w">arg</span> - <span class="n">0.5</span><span class="s">)</span><span class="sc">;</span></li><li>		<span class="s">}</span> <a class="l_k" href="functions/else.html">else</a> <span class="s">{</span></li><li>			<span class="w">arg</span> = <span class="n">0.0</span><span class="sc">;</span></li><li>		<span class="s">}</span></li><li>		<span class="i">sv_setnv</span><span class="s">(</span><span class="i">ST</span><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="cm">,</span> <span class="s">(</span><span class="w">double</span><span class="s">)</span><span class="w">arg</span><span class="s">)</span><span class="sc">;</span>	<span class="q">/* XXXXX */</span></li><li>		<span class="i">SvSETMAGIC</span><span class="s">(</span><span class="i">ST</span><span class="s">(</span><span class="n">0</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>	    <span class="s">}</span></li><li>	    <span class="w">XSRETURN_EMPTY</span><span class="sc">;</span></li><li>	<span class="s">}</span></li></ol></pre><p>Notice the two lines commented with "XXXXX".  If you check the first part
of the typemap file (or section), you'll see that doubles are of type
T_DOUBLE.  In the INPUT part of the typemap, an argument that is T_DOUBLE
is assigned to the variable arg by calling the routine SvNV on something,
then casting it to double, then assigned to the variable arg.  Similarly,
in the OUTPUT section, once arg has its final value, it is passed to the
sv_setnv function to be passed back to the calling subroutine.  These two
functions are explained in <a href="perlguts.html">perlguts</a>; we'll talk more later about what
that "ST(0)" means in the section on the argument stack.</p>
<a name="Warning-about-Output-Arguments"></a><h2>Warning about Output Arguments</h2>
<p>In general, it's not a good idea to write extensions that modify their input
parameters, as in Example 3.  Instead, you should probably return multiple
values in an array and let the caller handle them (we'll do this in a later
example).  However, in order to better accommodate calling pre-existing C
routines, which often do modify their input parameters, this behavior is
tolerated.</p>
<a name="EXAMPLE-4"></a><h2>EXAMPLE 4</h2>
<p>In this example, we'll now begin to write XSUBs that will interact with
pre-defined C libraries.  To begin with, we will build a small library of
our own, then let h2xs write our .pm and .xs files for us.</p>
<p>Create a new directory called Mytest2 at the same level as the directory
Mytest.  In the Mytest2 directory, create another directory called mylib,
and cd into that directory.</p>
<p>Here we'll create some files that will generate a test library.  These will
include a C source file and a header file.  We'll also create a Makefile.PL
in this directory.  Then we'll make sure that running make at the Mytest2
level will automatically run this Makefile.PL file and the resulting Makefile.</p>
<p>In the mylib directory, create a file mylib.h that looks like this:</p>
<pre class="verbatim"><ol><li>	<span class="c">#define TESTVAL	4</span></li><li></li><li>	<span class="w">extern</span> <span class="w">double</span>	<span class="i">foo</span><span class="s">(</span><a class="l_k" href="functions/int.html">int</a><span class="cm">,</span> <span class="w">long</span><span class="cm">,</span> <span class="w">const</span> <span class="w">char</span>*<span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Also create a file mylib.c that looks like this:</p>
<pre class="verbatim"><ol><li>	#include &lt;stdlib.h&gt;</li><li>	#include "./mylib.h"</li><li></li><li>	double</li><li>	foo(int a, long b, const char *c)</li><li>	{</li><li>		return (a + b + atof(c) + TESTVAL);</li><li>	}</li></ol></pre><p>And finally create a file Makefile.PL that looks like this:</p>
<pre class="verbatim"><ol><li>	<a class="l_k" href="functions/use.html">use</a> <span class="w">ExtUtils::MakeMaker</span><span class="sc">;</span></li><li>	<span class="i">$Verbose</span> = <span class="n">1</span><span class="sc">;</span></li><li>	<span class="i">WriteMakefile</span><span class="s">(</span></li><li>	    <span class="w">NAME</span>   <span class="cm">=&gt;</span> <span class="q">&#39;Mytest2::mylib&#39;</span><span class="cm">,</span></li><li>	    <span class="w">SKIP</span>   <span class="cm">=&gt;</span> <span class="s">[</span><span class="q">qw(all static static_lib dynamic dynamic_lib)</span><span class="s">]</span><span class="cm">,</span></li><li>	    <span class="w">clean</span>  <span class="cm">=&gt;</span> <span class="s">{</span><span class="q">&#39;FILES&#39;</span> <span class="cm">=&gt;</span> <span class="q">&#39;libmylib$(LIB_EXT)&#39;</span><span class="s">}</span><span class="cm">,</span></li><li>	<span class="s">)</span><span class="sc">;</span></li><li></li><li></li><li><a name="MY::top_targets"></a>	sub <span class="m">MY::top_targets</span> <span class="s">{</span></li><li>		<span class="q">&#39;</span></li><li>	<span class="q">	all :: static</span></li><li></li><li>	<span class="q">	pure_all :: static</span></li><li></li><li>	<span class="q">	static ::       libmylib$(LIB_EXT)</span></li><li></li><li>	<span class="q">	libmylib$(LIB_EXT): $(O_FILES)</span></li><li>		<span class="q">		$(AR) cr libmylib$(LIB_EXT) $(O_FILES)</span></li><li>		<span class="q">		$(RANLIB) libmylib$(LIB_EXT)</span></li><li></li><li>	<span class="q">	&#39;</span><span class="sc">;</span></li><li>	<span class="s">}</span></li></ol></pre><p>Make sure you use a tab and not spaces on the lines beginning with "$(AR)"
and "$(RANLIB)".  Make will not function properly if you use spaces.
It has also been reported that the "cr" argument to $(AR) is unnecessary
on Win32 systems.</p>
<p>We will now create the main top-level Mytest2 files.  Change to the directory
above Mytest2 and run the following command:</p>
<pre class="verbatim"><ol><li>	% h2xs -O -n Mytest2 ./Mytest2/mylib/mylib.h</li></ol></pre><p>This will print out a warning about overwriting Mytest2, but that's okay.
Our files are stored in Mytest2/mylib, and will be untouched.</p>
<p>The normal Makefile.PL that h2xs generates doesn't know about the mylib
directory.  We need to tell it that there is a subdirectory and that we
will be generating a library in it.  Let's add the argument MYEXTLIB to
the WriteMakefile call so that it looks like this:</p>
<pre class="verbatim"><ol><li>	<span class="i">WriteMakefile</span><span class="s">(</span></li><li>	    <span class="q">&#39;NAME&#39;</span>      <span class="cm">=&gt;</span> <span class="q">&#39;Mytest2&#39;</span><span class="cm">,</span></li><li>	    <span class="q">&#39;VERSION_FROM&#39;</span> <span class="cm">=&gt;</span> <span class="q">&#39;Mytest2.pm&#39;</span><span class="cm">,</span> <span class="c"># finds $VERSION</span></li><li>	    <span class="q">&#39;LIBS&#39;</span>      <span class="cm">=&gt;</span> <span class="s">[</span><span class="q">&#39;&#39;</span><span class="s">]</span><span class="cm">,</span>   <span class="c"># e.g., &#39;-lm&#39;</span></li><li>	    <span class="q">&#39;DEFINE&#39;</span>    <span class="cm">=&gt;</span> <span class="q">&#39;&#39;</span><span class="cm">,</span>     <span class="c"># e.g., &#39;-DHAVE_SOMETHING&#39;</span></li><li>	    <span class="q">&#39;INC&#39;</span>       <span class="cm">=&gt;</span> <span class="q">&#39;&#39;</span><span class="cm">,</span>     <span class="c"># e.g., &#39;-I/usr/include/other&#39;</span></li><li>	    <span class="q">&#39;MYEXTLIB&#39;</span> <span class="cm">=&gt;</span> <span class="q">&#39;mylib/libmylib$(LIB_EXT)&#39;</span><span class="cm">,</span></li><li>	<span class="s">)</span><span class="sc">;</span></li></ol></pre><p>and then at the end add a subroutine (which will override the pre-existing
subroutine).  Remember to use a tab character to indent the line beginning
with "cd"!</p>
<pre class="verbatim"><ol><li><a name="MY::postamble"></a>	sub <span class="m">MY::postamble</span> <span class="s">{</span></li><li>	<span class="q">&#39;</span></li><li>	<span class="q">	$(MYEXTLIB): mylib/Makefile</span></li><li>		<span class="q">		cd mylib &amp;&amp; $(MAKE) $(PASSTHRU)</span></li><li>	<span class="q">	&#39;</span><span class="sc">;</span></li><li>	<span class="s">}</span></li></ol></pre><p>Let's also fix the MANIFEST file so that it accurately reflects the contents
of our extension.  The single line that says "mylib" should be replaced by
the following three lines:</p>
<pre class="verbatim"><ol><li>	<span class="w">mylib</span>/<span class="w">Makefile</span>.<span class="w">PL</span></li><li>	<span class="w">mylib</span>/<span class="w">mylib</span>.<span class="w">c</span></li><li>	<span class="w">mylib</span>/<span class="w">mylib</span>.<span class="w">h</span></li></ol></pre><p>To keep our namespace nice and unpolluted, edit the .pm file and change
the variable <code class="inline"><span class="i">@EXPORT</span></code>
 to <code class="inline"><span class="i">@EXPORT_OK</span></code>
.  Finally, in the
.xs file, edit the #include line to read:</p>
<pre class="verbatim"><ol><li>	<span class="c">#include &quot;mylib/mylib.h&quot;</span></li></ol></pre><p>And also add the following function definition to the end of the .xs file:</p>
<pre class="verbatim"><ol><li>	double</li><li>	foo(a,b,c)</li><li>		int             a</li><li>		long            b</li><li>		const char *    c</li><li>	    OUTPUT:</li><li>		RETVAL</li></ol></pre><p>Now we also need to create a typemap because the default Perl doesn't
currently support the <code class="inline"><span class="w">const</span> <span class="w">char</span> *</code>
 type.  Include a new TYPEMAP
section in your XS code before the above function:</p>
<pre class="verbatim"><ol><li>        <span class="j">TYPEMAP:</span> <span class="h">&lt;&lt;END</span></li><li><span class="hh">	const char *	T_PV</span></li><li><span class="hh">        END</span></li></ol></pre><p>Now run perl on the top-level Makefile.PL.  Notice that it also created a
Makefile in the mylib directory.  Run make and watch that it does cd into
the mylib directory and run make in there as well.</p>
<p>Now edit the Mytest2.t script and change the number of tests to "4",
and add the following lines to the end of the script:</p>
<pre class="verbatim"><ol><li>	<span class="i">is</span><span class="s">(</span> <span class="i">&amp;Mytest2::foo</span><span class="s">(</span><span class="n">1</span><span class="cm">,</span> <span class="n">2</span><span class="cm">,</span> <span class="q">&quot;Hello, world!&quot;</span><span class="s">)</span><span class="cm">,</span> <span class="n">7</span> <span class="s">)</span><span class="sc">;</span></li><li>	<span class="i">is</span><span class="s">(</span> <span class="i">&amp;Mytest2::foo</span><span class="s">(</span><span class="n">1</span><span class="cm">,</span> <span class="n">2</span><span class="cm">,</span> <span class="q">&quot;0.0&quot;</span><span class="s">)</span><span class="cm">,</span> <span class="n">7</span> <span class="s">)</span><span class="sc">;</span></li><li>	<span class="i">ok</span><span class="s">(</span> <a class="l_k" href="functions/abs.html">abs</a><span class="s">(</span><span class="i">&amp;Mytest2::foo</span><span class="s">(</span><span class="n">0</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="q">&quot;-3.4&quot;</span><span class="s">)</span> - <span class="n">0.6</span><span class="s">)</span> &lt;= <span class="n">0.01</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>(When dealing with floating-point comparisons, it is best to not check for
equality, but rather that the difference between the expected and actual
result is below a certain amount (called epsilon) which is 0.01 in this case)</p>
<p>Run "<code class="inline"><span class="w">make</span> <span class="w">test</span></code>
" and all should be well. There are some warnings on missing
tests for the Mytest2::mylib extension, but you can ignore them.</p>
<a name="What-has-happened-here%3f"></a><h2>What has happened here?</h2>
<p>Unlike previous examples, we've now run h2xs on a real include file.  This
has caused some extra goodies to appear in both the .pm and .xs files.</p>
<ul>
<li>
<p>In the .xs file, there's now a #include directive with the absolute path to
the mylib.h header file.  We changed this to a relative path so that we
could move the extension directory if we wanted to.</p>
</li>
<li>
<p>There's now some new C code that's been added to the .xs file.  The purpose
of the <code class="inline"><span class="w">constant</span></code>
 routine is to make the values that are #define'd in the
header file accessible by the Perl script (by calling either <code class="inline"><span class="w">TESTVAL</span></code>
 or
<code class="inline"><span class="i">&amp;Mytest2::TESTVAL</span></code>
).  There's also some XS code to allow calls to the
<code class="inline"><span class="w">constant</span></code>
 routine.</p>
</li>
<li>
<p>The .pm file originally exported the name <code class="inline"><span class="w">TESTVAL</span></code>
 in the <code class="inline"><span class="i">@EXPORT</span></code>
 array.
This could lead to name clashes.  A good rule of thumb is that if the #define
is only going to be used by the C routines themselves, and not by the user,
they should be removed from the <code class="inline"><span class="i">@EXPORT</span></code>
 array.  Alternately, if you don't
mind using the "fully qualified name" of a variable, you could move most
or all of the items from the <code class="inline"><span class="i">@EXPORT</span></code>
 array into the <code class="inline"><span class="i">@EXPORT_OK</span></code>
 array.</p>
</li>
<li>
<p>If our include file had contained #include directives, these would not have
been processed by h2xs.  There is no good solution to this right now.</p>
</li>
<li>
<p>We've also told Perl about the library that we built in the mylib
subdirectory.  That required only the addition of the <code class="inline"><span class="w">MYEXTLIB</span></code>
 variable
to the WriteMakefile call and the replacement of the postamble subroutine
to cd into the subdirectory and run make.  The Makefile.PL for the
library is a bit more complicated, but not excessively so.  Again we
replaced the postamble subroutine to insert our own code.  This code
simply specified that the library to be created here was a static archive
library (as opposed to a dynamically loadable library) and provided the
commands to build it.</p>
</li>
</ul>
<a name="Anatomy-of-.xs-file"></a><h2>Anatomy of .xs file</h2>
<p>The .xs file of <a href="#EXAMPLE-4">EXAMPLE 4</a> contained some new elements.  To understand
the meaning of these elements, pay attention to the line which reads</p>
<pre class="verbatim"><ol><li>	<span class="w">MODULE</span> = <span class="w">Mytest2</span>		<span class="w">PACKAGE</span> = <span class="w">Mytest2</span></li></ol></pre><p>Anything before this line is plain C code which describes which headers
to include, and defines some convenience functions.  No translations are
performed on this part, apart from having embedded POD documentation
skipped over (see <a href="perlpod.html">perlpod</a>) it goes into the generated output C file as is.</p>
<p>Anything after this line is the description of XSUB functions.
These descriptions are translated by <b>xsubpp</b> into C code which
implements these functions using Perl calling conventions, and which
makes these functions visible from Perl interpreter.</p>
<p>Pay a special attention to the function <code class="inline"><span class="w">constant</span></code>
.  This name appears
twice in the generated .xs file: once in the first part, as a static C
function, then another time in the second part, when an XSUB interface to
this static C function is defined.</p>
<p>This is quite typical for .xs files: usually the .xs file provides
an interface to an existing C function.  Then this C function is defined
somewhere (either in an external library, or in the first part of .xs file),
and a Perl interface to this function (i.e. "Perl glue") is described in the
second part of .xs file.  The situation in <a href="#EXAMPLE-1">EXAMPLE 1</a>, <a href="#EXAMPLE-2">EXAMPLE 2</a>,
and <a href="#EXAMPLE-3">EXAMPLE 3</a>, when all the work is done inside the "Perl glue", is
somewhat of an exception rather than the rule.</p>
<a name="Getting-the-fat-out-of-XSUBs"></a><h2>Getting the fat out of XSUBs</h2>
<p>In <a href="#EXAMPLE-4">EXAMPLE 4</a> the second part of .xs file contained the following
description of an XSUB:</p>
<pre class="verbatim"><ol><li>	double</li><li>	foo(a,b,c)</li><li>		int             a</li><li>		long            b</li><li>		const char *    c</li><li>	    OUTPUT:</li><li>		RETVAL</li></ol></pre><p>Note that in contrast with <a href="#EXAMPLE-1">EXAMPLE 1</a>, <a href="#EXAMPLE-2">EXAMPLE 2</a> and <a href="#EXAMPLE-3">EXAMPLE 3</a>,
this description does not contain the actual <i>code</i> for what is done
during a call to Perl function foo().  To understand what is going
on here, one can add a CODE section to this XSUB:</p>
<pre class="verbatim"><ol><li>	double</li><li>	foo(a,b,c)</li><li>		int             a</li><li>		long            b</li><li>		const char *    c</li><li>	    CODE:</li><li>		RETVAL = foo(a,b,c);</li><li>	    OUTPUT:</li><li>		RETVAL</li></ol></pre><p>However, these two XSUBs provide almost identical generated C code: <b>xsubpp</b>
compiler is smart enough to figure out the <code class="inline"><span class="j">CODE:</span></code>
 section from the first
two lines of the description of XSUB.  What about <code class="inline"><span class="j">OUTPUT:</span></code>
 section?  In
fact, that is absolutely the same!  The <code class="inline"><span class="j">OUTPUT:</span></code>
 section can be removed
as well, <i>as far as <code class="inline"><span class="j">CODE:</span></code>
 section or <code class="inline"><span class="j">PPCODE:</span></code>
 section</i> is not
specified: <b>xsubpp</b> can see that it needs to generate a function call
section, and will autogenerate the OUTPUT section too.  Thus one can
shortcut the XSUB to become:</p>
<pre class="verbatim"><ol><li>	<span class="w">double</span></li><li>	<span class="i">foo</span><span class="s">(</span><span class="w">a</span><span class="cm">,</span><span class="w">b</span><span class="cm">,</span><span class="w">c</span><span class="s">)</span></li><li>		<a class="l_k" href="functions/int.html">int</a>             <span class="w">a</span></li><li>		<span class="w">long</span>            <span class="w">b</span></li><li>		<span class="w">const</span> <span class="w">char</span> *    <span class="w">c</span></li></ol></pre><p>Can we do the same with an XSUB</p>
<pre class="verbatim"><ol><li>	int</li><li>	is_even(input)</li><li>		int	input</li><li>	    CODE:</li><li>		RETVAL = (input % 2 == 0);</li><li>	    OUTPUT:</li><li>		RETVAL</li></ol></pre><p>of <a href="#EXAMPLE-2">EXAMPLE 2</a>?  To do this, one needs to define a C function <code class="inline"><a class="l_k" href="functions/int.html">int</a>
<span class="i">is_even</span><span class="s">(</span><a class="l_k" href="functions/int.html">int</a> <span class="w">input</span><span class="s">)</span></code>
.  As we saw in <a href="#Anatomy-of-.xs-file">Anatomy of .xs file</a>, a proper place
for this definition is in the first part of .xs file.  In fact a C function</p>
<pre class="verbatim"><ol><li>	int</li><li>	is_even(int arg)</li><li>	{</li><li>		return (arg % 2 == 0);</li><li>	}</li></ol></pre><p>is probably overkill for this.  Something as simple as a <code class="inline"><span class="c">#define</span></code>
 will
do too:</p>
<pre class="verbatim"><ol><li>	<span class="c">#define is_even(arg)	((arg) % 2 == 0)</span></li></ol></pre><p>After having this in the first part of .xs file, the "Perl glue" part becomes
as simple as</p>
<pre class="verbatim"><ol><li>	<a class="l_k" href="functions/int.html">int</a></li><li>	<span class="i">is_even</span><span class="s">(</span><span class="w">input</span><span class="s">)</span></li><li>		<a class="l_k" href="functions/int.html">int</a>	<span class="w">input</span></li></ol></pre><p>This technique of separation of the glue part from the workhorse part has
obvious tradeoffs: if you want to change a Perl interface, you need to
change two places in your code.  However, it removes a lot of clutter,
and makes the workhorse part independent from idiosyncrasies of Perl calling
convention.  (In fact, there is nothing Perl-specific in the above description,
a different version of <b>xsubpp</b> might have translated this to TCL glue or
Python glue as well.)</p>
<a name="More-about-XSUB-arguments"></a><h2>More about XSUB arguments</h2>
<p>With the completion of Example 4, we now have an easy way to simulate some
real-life libraries whose interfaces may not be the cleanest in the world.
We shall now continue with a discussion of the arguments passed to the
<b>xsubpp</b> compiler.</p>
<p>When you specify arguments to routines in the .xs file, you are really
passing three pieces of information for each argument listed.  The first
piece is the order of that argument relative to the others (first, second,
etc).  The second is the type of argument, and consists of the type
declaration of the argument (e.g., int, char*, etc).  The third piece is
the calling convention for the argument in the call to the library function.</p>
<p>While Perl passes arguments to functions by reference,
C passes arguments by value; to implement a C function which modifies data
of one of the "arguments", the actual argument of this C function would be
a pointer to the data.  Thus two C functions with declarations</p>
<pre class="verbatim"><ol><li>	int string_length(char *s);</li><li>	int upper_case_char(char *cp);</li></ol></pre><p>may have completely different semantics: the first one may inspect an array
of chars pointed by s, and the second one may immediately dereference <code class="inline"><span class="w">cp</span></code>

and manipulate <code class="inline"><span class="i">*cp</span></code>
 only (using the return value as, say, a success
indicator).  From Perl one would use these functions in
a completely different manner.</p>
<p>One conveys this info to <b>xsubpp</b> by replacing <code class="inline"><span class="i">*</span></code>
 before the
argument by <code class="inline"><span class="i">&amp;</span></code>
.  <code class="inline"><span class="i">&amp;</span></code>
 means that the argument should be passed to a library
function by its address.  The above two function may be XSUB-ified as</p>
<pre class="verbatim"><ol><li>	int</li><li>	string_length(s)</li><li>		char *	s</li><li></li><li>	int</li><li>	upper_case_char(cp)</li><li>		char	&amp;cp</li></ol></pre><p>For example, consider:</p>
<pre class="verbatim"><ol><li>	int</li><li>	foo(a,b)</li><li>		char	&amp;a</li><li>		char *	b</li></ol></pre><p>The first Perl argument to this function would be treated as a char and
assigned to the variable a, and its address would be passed into the function
foo. The second Perl argument would be treated as a string pointer and assigned
to the variable b. The <i>value</i> of b would be passed into the function foo.
The actual call to the function foo that <b>xsubpp</b> generates would look like
this:</p>
<pre class="verbatim"><ol><li>	<span class="i">foo</span><span class="s">(</span><span class="i">&amp;a</span><span class="cm">,</span> <span class="w">b</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p><b>xsubpp</b> will parse the following function argument lists identically:</p>
<pre class="verbatim"><ol><li>	char	&amp;a</li><li>	char&amp;a</li><li>	char	&amp; a</li></ol></pre><p>However, to help ease understanding, it is suggested that you place a "&amp;"
next to the variable name and away from the variable type), and place a
"*" near the variable type, but away from the variable name (as in the
call to foo above).  By doing so, it is easy to understand exactly what
will be passed to the C function; it will be whatever is in the "last
column".</p>
<p>You should take great pains to try to pass the function the type of variable
it wants, when possible.  It will save you a lot of trouble in the long run.</p>
<a name="The-Argument-Stack"></a><h2>The Argument Stack</h2>
<p>If we look at any of the C code generated by any of the examples except
example 1, you will notice a number of references to ST(n), where n is
usually 0.  "ST" is actually a macro that points to the n'th argument
on the argument stack.  ST(0) is thus the first argument on the stack and
therefore the first argument passed to the XSUB, ST(1) is the second
argument, and so on.</p>
<p>When you list the arguments to the XSUB in the .xs file, that tells <b>xsubpp</b>
which argument corresponds to which of the argument stack (i.e., the first
one listed is the first argument, and so on).  You invite disaster if you
do not list them in the same order as the function expects them.</p>
<p>The actual values on the argument stack are pointers to the values passed
in.  When an argument is listed as being an OUTPUT value, its corresponding
value on the stack (i.e., ST(0) if it was the first argument) is changed.
You can verify this by looking at the C code generated for Example 3.
The code for the round() XSUB routine contains lines that look like this:</p>
<pre class="verbatim"><ol><li>	double  arg = (double)SvNV(ST(0));</li><li>	/* Round the contents of the variable arg */</li><li>	sv_setnv(ST(0), (double)arg);</li></ol></pre><p>The arg variable is initially set by taking the value from ST(0), then is
stored back into ST(0) at the end of the routine.</p>
<p>XSUBs are also allowed to return lists, not just scalars.  This must be
done by manipulating stack values ST(0), ST(1), etc, in a subtly
different way.  See <a href="perlxs.html">perlxs</a> for details.</p>
<p>XSUBs are also allowed to avoid automatic conversion of Perl function arguments
to C function arguments.  See <a href="perlxs.html">perlxs</a> for details.  Some people prefer
manual conversion by inspecting <code class="inline"><span class="i">ST</span><span class="s">(</span><span class="w">i</span><span class="s">)</span></code>
 even in the cases when automatic
conversion will do, arguing that this makes the logic of an XSUB call clearer.
Compare with <a href="#Getting-the-fat-out-of-XSUBs">Getting the fat out of XSUBs</a> for a similar tradeoff of
a complete separation of "Perl glue" and "workhorse" parts of an XSUB.</p>
<p>While experts may argue about these idioms, a novice to Perl guts may
prefer a way which is as little Perl-guts-specific as possible, meaning
automatic conversion and automatic call generation, as in
<a href="#Getting-the-fat-out-of-XSUBs">Getting the fat out of XSUBs</a>.  This approach has the additional
benefit of protecting the XSUB writer from future changes to the Perl API.</p>
<a name="Extending-your-Extension"></a><h2>Extending your Extension</h2>
<p>Sometimes you might want to provide some extra methods or subroutines
to assist in making the interface between Perl and your extension simpler
or easier to understand.  These routines should live in the .pm file.
Whether they are automatically loaded when the extension itself is loaded
or only loaded when called depends on where in the .pm file the subroutine
definition is placed.  You can also consult <a href="AutoLoader.html">AutoLoader</a> for an alternate
way to store and load your extra subroutines.</p>
<a name="Documenting-your-Extension"></a><h2>Documenting your Extension</h2>
<p>There is absolutely no excuse for not documenting your extension.
Documentation belongs in the .pm file.  This file will be fed to pod2man,
and the embedded documentation will be converted to the manpage format,
then placed in the blib directory.  It will be copied to Perl's
manpage directory when the extension is installed.</p>
<p>You may intersperse documentation and Perl code within the .pm file.
In fact, if you want to use method autoloading, you must do this,
as the comment inside the .pm file explains.</p>
<p>See <a href="perlpod.html">perlpod</a> for more information about the pod format.</p>
<a name="Installing-your-Extension"></a><h2>Installing your Extension</h2>
<p>Once your extension is complete and passes all its tests, installing it
is quite simple: you simply run "make install".  You will either need
to have write permission into the directories where Perl is installed,
or ask your system administrator to run the make for you.</p>
<p>Alternately, you can specify the exact directory to place the extension's
files by placing a "PREFIX=/destination/directory" after the make install
(or in between the make and install if you have a brain-dead version of make).
This can be very useful if you are building an extension that will eventually
be distributed to multiple systems.  You can then just archive the files in
the destination directory and distribute them to your destination systems.</p>
<a name="EXAMPLE-5"></a><h2>EXAMPLE 5</h2>
<p>In this example, we'll do some more work with the argument stack.  The
previous examples have all returned only a single value.  We'll now
create an extension that returns an array.</p>
<p>This extension is very Unix-oriented (struct statfs and the statfs system
call).  If you are not running on a Unix system, you can substitute for
statfs any other function that returns multiple values, you can hard-code
values to be returned to the caller (although this will be a bit harder
to test the error case), or you can simply not do this example.  If you
change the XSUB, be sure to fix the test cases to match the changes.</p>
<p>Return to the Mytest directory and add the following code to the end of
Mytest.xs:</p>
<pre class="verbatim"><ol><li>	void</li><li>	statfs(path)</li><li>		char *  path</li><li>	    INIT:</li><li>		int i;</li><li>		struct statfs buf;</li><li></li><li>	    PPCODE:</li><li>		i = statfs(path, &amp;buf);</li><li>		if (i == 0) {</li><li>			XPUSHs(sv_2mortal(newSVnv(buf.f_bavail)));</li><li>			XPUSHs(sv_2mortal(newSVnv(buf.f_bfree)));</li><li>			XPUSHs(sv_2mortal(newSVnv(buf.f_blocks)));</li><li>			XPUSHs(sv_2mortal(newSVnv(buf.f_bsize)));</li><li>			XPUSHs(sv_2mortal(newSVnv(buf.f_ffree)));</li><li>			XPUSHs(sv_2mortal(newSVnv(buf.f_files)));</li><li>			XPUSHs(sv_2mortal(newSVnv(buf.f_type)));</li><li>		} else {</li><li>			XPUSHs(sv_2mortal(newSVnv(errno)));</li><li>		}</li></ol></pre><p>You'll also need to add the following code to the top of the .xs file, just
after the include of "XSUB.h":</p>
<pre class="verbatim"><ol><li>	<span class="c">#include &lt;sys/vfs.h&gt;</span></li></ol></pre><p>Also add the following code segment to Mytest.t while incrementing the "9"
tests to "11":</p>
<pre class="verbatim"><ol><li>	<span class="i">@a</span> = <span class="i">&amp;Mytest::statfs</span><span class="s">(</span><span class="q">&quot;/blech&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>	<span class="i">ok</span><span class="s">(</span> <a class="l_k" href="functions/scalar.html">scalar</a><span class="s">(</span><span class="i">@a</span><span class="s">)</span> == <span class="n">1</span> &amp;&amp; <span class="i">$a</span>[<span class="n">0</span>] == <span class="n">2</span> <span class="s">)</span><span class="sc">;</span></li><li>	<span class="i">@a</span> = <span class="i">&amp;Mytest::statfs</span><span class="s">(</span><span class="q">&quot;/&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>	<span class="i">is</span><span class="s">(</span> <a class="l_k" href="functions/scalar.html">scalar</a><span class="s">(</span><span class="i">@a</span><span class="s">)</span><span class="cm">,</span> <span class="n">7</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><a name="New-Things-in-this-Example"></a><h2>New Things in this Example</h2>
<p>This example added quite a few new concepts.  We'll take them one at a time.</p>
<ul>
<li>
<p>The INIT: directive contains code that will be placed immediately after
the argument stack is decoded.  C does not allow variable declarations at
arbitrary locations inside a function,
so this is usually the best way to declare local variables needed by the XSUB.
(Alternatively, one could put the whole <code class="inline"><span class="j">PPCODE:</span></code>
 section into braces, and
put these declarations on top.)</p>
</li>
<li>
<p>This routine also returns a different number of arguments depending on the
success or failure of the call to statfs.  If there is an error, the error
number is returned as a single-element array.  If the call is successful,
then a 7-element array is returned.  Since only one argument is passed into
this function, we need room on the stack to hold the 7 values which may be
returned.</p>
<p>We do this by using the PPCODE: directive, rather than the CODE: directive.
This tells <b>xsubpp</b> that we will be managing the return values that will be
put on the argument stack by ourselves.</p>
</li>
<li>
<p>When we want to place values to be returned to the caller onto the stack,
we use the series of macros that begin with "XPUSH".  There are five
different versions, for placing integers, unsigned integers, doubles,
strings, and Perl scalars on the stack.  In our example, we placed a
Perl scalar onto the stack.  (In fact this is the only macro which
can be used to return multiple values.)</p>
<p>The XPUSH* macros will automatically extend the return stack to prevent
it from being overrun.  You push values onto the stack in the order you
want them seen by the calling program.</p>
</li>
<li>
<p>The values pushed onto the return stack of the XSUB are actually mortal SV's.
They are made mortal so that once the values are copied by the calling
program, the SV's that held the returned values can be deallocated.
If they were not mortal, then they would continue to exist after the XSUB
routine returned, but would not be accessible.  This is a memory leak.</p>
</li>
<li>
<p>If we were interested in performance, not in code compactness, in the success
branch we would not use <code class="inline"><span class="w">XPUSHs</span></code>
 macros, but <code class="inline"><span class="w">PUSHs</span></code>
 macros, and would
pre-extend the stack before pushing the return values:</p>
<pre class="verbatim"><ol><li>	<span class="i">EXTEND</span><span class="s">(</span><span class="w">SP</span><span class="cm">,</span> <span class="n">7</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The tradeoff is that one needs to calculate the number of return values
in advance (though overextending the stack will not typically hurt
anything but memory consumption).</p>
<p>Similarly, in the failure branch we could use <code class="inline"><span class="w">PUSHs</span></code>
 <i>without</i> extending
the stack: the Perl function reference comes to an XSUB on the stack, thus
the stack is <i>always</i> large enough to take one return value.</p>
</li>
</ul>
<a name="EXAMPLE-6"></a><h2>EXAMPLE 6</h2>
<p>In this example, we will accept a reference to an array as an input
parameter, and return a reference to an array of hashes.  This will
demonstrate manipulation of complex Perl data types from an XSUB.</p>
<p>This extension is somewhat contrived.  It is based on the code in
the previous example.  It calls the statfs function multiple times,
accepting a reference to an array of filenames as input, and returning
a reference to an array of hashes containing the data for each of the
filesystems.</p>
<p>Return to the Mytest directory and add the following code to the end of
Mytest.xs:</p>
<pre class="verbatim"><ol><li>    <span class="w">SV</span> *</li><li>    <span class="i">multi_statfs</span><span class="s">(</span><span class="w">paths</span><span class="s">)</span></li><li>	    <span class="w">SV</span> * <span class="w">paths</span></li><li>	<a class="l_k" href="functions/INIT.html">INIT</a><span class="co">:</span></li><li>	    <span class="w">AV</span> * <span class="w">results</span><span class="sc">;</span></li><li>	    <span class="w">SSize_t</span> <span class="w">numpaths</span> = <span class="n">0</span><span class="cm">,</span> <span class="w">n</span><span class="sc">;</span></li><li>	    <a class="l_k" href="functions/int.html">int</a> <span class="w">i</span><span class="sc">;</span></li><li>	    <span class="w">struct</span> <span class="w">statfs</span> <span class="w">buf</span><span class="sc">;</span></li><li></li><li>	    <span class="i">SvGETMAGIC</span><span class="s">(</span><span class="w">paths</span><span class="s">)</span><span class="sc">;</span></li><li>	    <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="s">(</span>!<span class="i">SvROK</span><span class="s">(</span><span class="w">paths</span><span class="s">)</span><span class="s">)</span></li><li>		|| <span class="s">(</span><span class="i">SvTYPE</span><span class="s">(</span><span class="i">SvRV</span><span class="s">(</span><span class="w">paths</span><span class="s">)</span><span class="s">)</span> != <span class="w">SVt_PVAV</span><span class="s">)</span></li><li>		|| <span class="s">(</span><span class="s">(</span><span class="w">numpaths</span> = <span class="i">av_top_index</span><span class="s">(</span><span class="s">(</span><span class="w">AV</span> *<span class="s">)</span><span class="i">SvRV</span><span class="s">(</span><span class="w">paths</span><span class="s">)</span><span class="s">)</span><span class="s">)</span> &lt; <span class="n">0</span><span class="s">)</span><span class="s">)</span></li><li>	    <span class="s">{</span></li><li>		<span class="w">XSRETURN_UNDEF</span><span class="sc">;</span></li><li>	    <span class="s">}</span></li><li>	    <span class="w">results</span> = <span class="s">(</span><span class="w">AV</span> *<span class="s">)</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="s">(</span><span class="w">SV</span> *<span class="s">)</span><span class="i">newAV</span><span class="s">(</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>	<span class="j">CODE:</span></li><li>	    <a class="l_k" href="functions/for.html">for</a> <span class="s">(</span><span class="w">n</span> = <span class="n">0</span><span class="sc">;</span> <span class="w">n</span> &lt;= <span class="w">numpaths</span><span class="sc">;</span> <span class="w">n</span>++<span class="s">)</span> <span class="s">{</span></li><li>		<span class="w">HV</span> * <span class="w">rh</span><span class="sc">;</span></li><li>		<span class="w">STRLEN</span> <span class="w">l</span><span class="sc">;</span></li><li>		<span class="w">char</span> * <span class="w">fn</span> = <span class="i">SvPV</span><span class="s">(</span><span class="i">*av_fetch</span><span class="s">(</span><span class="s">(</span><span class="w">AV</span> *<span class="s">)</span><span class="i">SvRV</span><span class="s">(</span><span class="w">paths</span><span class="s">)</span><span class="cm">,</span> <span class="w">n</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="cm">,</span> <span class="w">l</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>		<span class="w">i</span> = <span class="i">statfs</span><span class="s">(</span><span class="w">fn</span><span class="cm">,</span> <span class="i">&amp;buf</span><span class="s">)</span><span class="sc">;</span></li><li>		<a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="w">i</span> != <span class="n">0</span><span class="s">)</span> <span class="s">{</span></li><li>		    <span class="i">av_push</span><span class="s">(</span><span class="w">results</span><span class="cm">,</span> <span class="i">newSVnv</span><span class="s">(</span><span class="w">errno</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>		    <a class="l_k" href="functions/continue.html">continue</a><span class="sc">;</span></li><li>		<span class="s">}</span></li><li></li><li>		<span class="w">rh</span> = <span class="s">(</span><span class="w">HV</span> *<span class="s">)</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="s">(</span><span class="w">SV</span> *<span class="s">)</span><span class="i">newHV</span><span class="s">(</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>		<span class="i">hv_store</span><span class="s">(</span><span class="w">rh</span><span class="cm">,</span> <span class="q">&quot;f_bavail&quot;</span><span class="cm">,</span> <span class="n">8</span><span class="cm">,</span> <span class="i">newSVnv</span><span class="s">(</span><span class="w">buf</span>.<span class="w">f_bavail</span><span class="s">)</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>		<span class="i">hv_store</span><span class="s">(</span><span class="w">rh</span><span class="cm">,</span> <span class="q">&quot;f_bfree&quot;</span><span class="cm">,</span>  <span class="n">7</span><span class="cm">,</span> <span class="i">newSVnv</span><span class="s">(</span><span class="w">buf</span>.<span class="w">f_bfree</span><span class="s">)</span><span class="cm">,</span>  <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>		<span class="i">hv_store</span><span class="s">(</span><span class="w">rh</span><span class="cm">,</span> <span class="q">&quot;f_blocks&quot;</span><span class="cm">,</span> <span class="n">8</span><span class="cm">,</span> <span class="i">newSVnv</span><span class="s">(</span><span class="w">buf</span>.<span class="w">f_blocks</span><span class="s">)</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>		<span class="i">hv_store</span><span class="s">(</span><span class="w">rh</span><span class="cm">,</span> <span class="q">&quot;f_bsize&quot;</span><span class="cm">,</span>  <span class="n">7</span><span class="cm">,</span> <span class="i">newSVnv</span><span class="s">(</span><span class="w">buf</span>.<span class="w">f_bsize</span><span class="s">)</span><span class="cm">,</span>  <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>		<span class="i">hv_store</span><span class="s">(</span><span class="w">rh</span><span class="cm">,</span> <span class="q">&quot;f_ffree&quot;</span><span class="cm">,</span>  <span class="n">7</span><span class="cm">,</span> <span class="i">newSVnv</span><span class="s">(</span><span class="w">buf</span>.<span class="w">f_ffree</span><span class="s">)</span><span class="cm">,</span>  <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>		<span class="i">hv_store</span><span class="s">(</span><span class="w">rh</span><span class="cm">,</span> <span class="q">&quot;f_files&quot;</span><span class="cm">,</span>  <span class="n">7</span><span class="cm">,</span> <span class="i">newSVnv</span><span class="s">(</span><span class="w">buf</span>.<span class="w">f_files</span><span class="s">)</span><span class="cm">,</span>  <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li>		<span class="i">hv_store</span><span class="s">(</span><span class="w">rh</span><span class="cm">,</span> <span class="q">&quot;f_type&quot;</span><span class="cm">,</span>   <span class="n">6</span><span class="cm">,</span> <span class="i">newSVnv</span><span class="s">(</span><span class="w">buf</span>.<span class="w">f_type</span><span class="s">)</span><span class="cm">,</span>   <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>		<span class="i">av_push</span><span class="s">(</span><span class="w">results</span><span class="cm">,</span> <span class="i">newRV_inc</span><span class="s">(</span><span class="s">(</span><span class="w">SV</span> *<span class="s">)</span><span class="w">rh</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>	    <span class="s">}</span></li><li>	    <span class="w">RETVAL</span> = <span class="i">newRV_inc</span><span class="s">(</span><span class="s">(</span><span class="w">SV</span> *<span class="s">)</span><span class="w">results</span><span class="s">)</span><span class="sc">;</span></li><li>	<span class="j">OUTPUT:</span></li><li>	    <span class="w">RETVAL</span></li></ol></pre><p>And add the following code to Mytest.t, while incrementing the "11"
tests to "13":</p>
<pre class="verbatim"><ol><li>	<span class="i">$results</span> = <span class="i">Mytest::multi_statfs</span><span class="s">(</span><span class="s">[</span> <span class="q">&#39;/&#39;</span><span class="cm">,</span> <span class="q">&#39;/blech&#39;</span> <span class="s">]</span><span class="s">)</span><span class="sc">;</span></li><li>	<span class="i">ok</span><span class="s">(</span> <a class="l_k" href="functions/ref.html">ref</a> <span class="i">$results</span>-&gt;[<span class="n">0</span>] <span class="s">)</span><span class="sc">;</span></li><li>	<span class="i">ok</span><span class="s">(</span> ! <a class="l_k" href="functions/ref.html">ref</a> <span class="i">$results</span>-&gt;[<span class="n">1</span>] <span class="s">)</span><span class="sc">;</span></li></ol></pre><a name="New-Things-in-this-Example"></a><h2>New Things in this Example</h2>
<p>There are a number of new concepts introduced here, described below:</p>
<ul>
<li>
<p>This function does not use a typemap.  Instead, we declare it as accepting
one SV* (scalar) parameter, and returning an SV* value, and we take care of
populating these scalars within the code.  Because we are only returning
one value, we don't need a <code class="inline"><span class="j">PPCODE:</span></code>
 directive - instead, we use <code class="inline"><span class="j">CODE:</span></code>

and <code class="inline"><span class="j">OUTPUT:</span></code>
 directives.</p>
</li>
<li>
<p>When dealing with references, it is important to handle them with caution.
The <code class="inline"><span class="j">INIT:</span></code>
 block first calls SvGETMAGIC(paths), in case
paths is a tied variable.  Then it checks that <code class="inline"><span class="w">SvROK</span></code>
 returns
true, which indicates that paths is a valid reference.  (Simply
checking <code class="inline"><span class="w">SvROK</span></code>
 won't trigger FETCH on a tied variable.)  It
then verifies that the object referenced by paths is an array, using <code class="inline"><span class="w">SvRV</span></code>

to dereference paths, and <code class="inline"><span class="w">SvTYPE</span></code>
 to discover its type.  As an added test,
it checks that the array referenced by paths is non-empty, using the
<code class="inline"><span class="w">av_top_index</span></code>
 function (which returns -1 if the array is empty). The
XSRETURN_UNDEF macro is used to abort the XSUB and return the undefined value
whenever all three of these conditions are not met.</p>
</li>
<li>
<p>We manipulate several arrays in this XSUB.  Note that an array is represented
internally by an AV* pointer.  The functions and macros for manipulating
arrays are similar to the functions in Perl: <code class="inline"><span class="w">av_top_index</span></code>
 returns the
highest index in an AV*, much like $#array; <code class="inline"><span class="w">av_fetch</span></code>
 fetches a single scalar
value from an array, given its index; <code class="inline"><span class="w">av_push</span></code>
 pushes a scalar value onto the
end of the array, automatically extending the array as necessary.</p>
<p>Specifically, we read pathnames one at a time from the input array, and
store the results in an output array (results) in the same order.  If
statfs fails, the element pushed onto the return array is the value of
errno after the failure.  If statfs succeeds, though, the value pushed
onto the return array is a reference to a hash containing some of the
information in the statfs structure.</p>
<p>As with the return stack, it would be possible (and a small performance win)
to pre-extend the return array before pushing data into it, since we know
how many elements we will return:</p>
<pre class="verbatim"><ol><li>	<span class="i">av_extend</span><span class="s">(</span><span class="w">results</span><span class="cm">,</span> <span class="w">numpaths</span><span class="s">)</span><span class="sc">;</span></li></ol></pre></li>
<li>
<p>We are performing only one hash operation in this function, which is storing
a new scalar under a key using <code class="inline"><span class="w">hv_store</span></code>
.  A hash is represented by an HV*
pointer.  Like arrays, the functions for manipulating hashes from an XSUB
mirror the functionality available from Perl.  See <a href="perlguts.html">perlguts</a> and <a href="perlapi.html">perlapi</a>
for details.</p>
</li>
<li>
<p>To create a reference, we use the <code class="inline"><span class="w">newRV_inc</span></code>
 function.  Note that you can
cast an AV* or an HV* to type SV* in this case (and many others).  This
allows you to take references to arrays, hashes and scalars with the same
function.  Conversely, the <code class="inline"><span class="w">SvRV</span></code>
 function always returns an SV*, which may
need to be cast to the appropriate type if it is something other than a
scalar (check with <code class="inline"><span class="w">SvTYPE</span></code>
).</p>
</li>
<li>
<p>At this point, xsubpp is doing very little work - the differences between
Mytest.xs and Mytest.c are minimal.</p>
</li>
</ul>
<a name="EXAMPLE-7-(Coming-Soon)"></a><h2>EXAMPLE 7 (Coming Soon)</h2>
<p>XPUSH args AND set RETVAL AND assign return value to array</p>
<a name="EXAMPLE-8-(Coming-Soon)"></a><h2>EXAMPLE 8 (Coming Soon)</h2>
<p>Setting $!</p>
<a name="EXAMPLE-9-Passing-open-files-to-XSes"></a><h2>EXAMPLE 9 Passing open files to XSes</h2>
<p>You would think passing files to an XS is difficult, with all the
typeglobs and stuff. Well, it isn't.</p>
<p>Suppose that for some strange reason we need a wrapper around the
standard C library function <code class="inline"><span class="i">fputs</span><span class="s">(</span><span class="s">)</span></code>
. This is all we need:</p>
<pre class="verbatim"><ol><li>	<span class="c">#define PERLIO_NOT_STDIO 0</span></li><li>	<span class="c">#define PERL_NO_GET_CONTEXT</span></li><li>	<span class="c">#include &quot;EXTERN.h&quot;</span></li><li>	<span class="c">#include &quot;perl.h&quot;</span></li><li>	<span class="c">#include &quot;XSUB.h&quot;</span></li><li></li><li>	<span class="c">#include &lt;stdio.h&gt;</span></li><li></li><li>	<a class="l_k" href="functions/int.html">int</a></li><li>	<span class="i">fputs</span><span class="s">(</span><span class="q">s, stream)</span></li><li>		<span class="q">		char *          s</span></li><li>		<span class="q">		FILE *	        stream</span></li></ol></pre><p>The real work is done in the standard typemap.</p>
<p><b>But</b> you lose all the fine stuff done by the perlio layers. This
calls the stdio function <code class="inline"><span class="i">fputs</span><span class="s">(</span><span class="s">)</span></code>
, which knows nothing about them.</p>
<p>The standard typemap offers three variants of PerlIO *:
<code class="inline"><span class="w">InputStream</span></code>
 (T_IN), <code class="inline"><span class="w">InOutStream</span></code>
 (T_INOUT) and <code class="inline"><span class="w">OutputStream</span></code>

(T_OUT). A bare <code class="inline"><span class="w">PerlIO</span> *</code>
 is considered a T_INOUT. If it matters
in your code (see below for why it might) #define or typedef
one of the specific names and use that as the argument or result
type in your XS file.</p>
<p>The standard typemap does not contain PerlIO * before perl 5.7,
but it has the three stream variants. Using a PerlIO * directly
is not backwards compatible unless you provide your own typemap.</p>
<p>For streams coming <i>from</i> perl the main difference is that
<code class="inline"><span class="w">OutputStream</span></code>
 will get the output PerlIO * - which may make
a difference on a socket. Like in our example...</p>
<p>For streams being handed <i>to</i> perl a new file handle is created
(i.e. a reference to a new glob) and associated with the PerlIO *
provided. If the read/write state of the PerlIO * is not correct then you
may get errors or warnings from when the file handle is used.
So if you opened the PerlIO * as "w" it should really be an
<code class="inline"><span class="w">OutputStream</span></code>
 if open as "r" it should be an <code class="inline"><span class="w">InputStream</span></code>
.</p>
<p>Now, suppose you want to use perlio layers in your XS. We'll use the
perlio <code class="inline"><span class="i">PerlIO_puts</span><span class="s">(</span><span class="s">)</span></code>
 function as an example.</p>
<p>In the C part of the XS file (above the first MODULE line) you
have</p>
<pre class="verbatim"><ol><li>	<span class="c">#define OutputStream	PerlIO *</span></li><li>    or</li><li>	<span class="w">typedef</span> <span class="w">PerlIO</span> *	<span class="w">OutputStream</span><span class="sc">;</span></li></ol></pre><p>And this is the XS code:</p>
<pre class="verbatim"><ol><li>	int</li><li>	perlioputs(s, stream)</li><li>		char *          s</li><li>		OutputStream	stream</li><li>	CODE:</li><li>		RETVAL = PerlIO_puts(stream, s);</li><li>	OUTPUT:</li><li>		RETVAL</li></ol></pre><p>We have to use a <code class="inline"><span class="w">CODE</span></code>
 section because <code class="inline"><span class="i">PerlIO_puts</span><span class="s">(</span><span class="s">)</span></code>
 has the arguments
reversed compared to <code class="inline"><span class="i">fputs</span><span class="s">(</span><span class="s">)</span></code>
, and we want to keep the arguments the same.</p>
<p>Wanting to explore this thoroughly, we want to use the stdio <code class="inline"><span class="i">fputs</span><span class="s">(</span><span class="s">)</span></code>

on a PerlIO *. This means we have to ask the perlio system for a stdio
<code class="inline"><span class="w">FILE</span> *</code>
:</p>
<pre class="verbatim"><ol><li>	int</li><li>	perliofputs(s, stream)</li><li>		char *          s</li><li>		OutputStream	stream</li><li>	PREINIT:</li><li>		FILE *fp = PerlIO_findFILE(stream);</li><li>	CODE:</li><li>		if (fp != (FILE*) 0) {</li><li>			RETVAL = fputs(s, fp);</li><li>		} else {</li><li>			RETVAL = -1;</li><li>		}</li><li>	OUTPUT:</li><li>		RETVAL</li></ol></pre><p>Note: <code class="inline"><span class="i">PerlIO_findFILE</span><span class="s">(</span><span class="s">)</span></code>
 will search the layers for a stdio
layer. If it can't find one, it will call <code class="inline"><span class="i">PerlIO_exportFILE</span><span class="s">(</span><span class="s">)</span></code>
 to
generate a new stdio <code class="inline"><span class="w">FILE</span></code>
. Please only call <code class="inline"><span class="i">PerlIO_exportFILE</span><span class="s">(</span><span class="s">)</span></code>
 if
you want a <i>new</i> <code class="inline"><span class="w">FILE</span></code>
. It will generate one on each call and push a
new stdio layer. So don't call it repeatedly on the same
file. <code class="inline"><span class="i">PerlIO_findFILE</span><span class="s">(</span><span class="s">)</span></code>
 will retrieve the stdio layer once it has been
generated by <code class="inline"><span class="i">PerlIO_exportFILE</span><span class="s">(</span><span class="s">)</span></code>
.</p>
<p>This applies to the perlio system only. For versions before 5.7,
<code class="inline"><span class="i">PerlIO_exportFILE</span><span class="s">(</span><span class="s">)</span></code>
 is equivalent to <code class="inline"><span class="i">PerlIO_findFILE</span><span class="s">(</span><span class="s">)</span></code>
.</p>
<a name="Troubleshooting-these-Examples"></a><h2>Troubleshooting these Examples</h2>
<p>As mentioned at the top of this document, if you are having problems with
these example extensions, you might see if any of these help you.</p>
<ul>
<li>
<p>In versions of 5.002 prior to the gamma version, the test script in Example
1 will not function properly.  You need to change the "use lib" line to
read:</p>
<pre class="verbatim"><ol><li>	<a class="l_k" href="functions/use.html">use</a> <span class="w">lib</span> <span class="q">&#39;./blib&#39;</span><span class="sc">;</span></li></ol></pre></li>
<li>
<p>In versions of 5.002 prior to version 5.002b1h, the test.pl file was not
automatically created by h2xs.  This means that you cannot say "make test"
to run the test script.  You will need to add the following line before the
"use extension" statement:</p>
<pre class="verbatim"><ol><li>	<a class="l_k" href="functions/use.html">use</a> <span class="w">lib</span> <span class="q">&#39;./blib&#39;</span><span class="sc">;</span></li></ol></pre></li>
<li>
<p>In versions 5.000 and 5.001, instead of using the above line, you will need
to use the following line:</p>
<pre class="verbatim"><ol><li>	BEGIN <span class="s">{</span> <a class="l_k" href="functions/unshift.html">unshift</a><span class="s">(</span><span class="i">@INC</span><span class="cm">,</span> <span class="q">&quot;./blib&quot;</span><span class="s">)</span> <span class="s">}</span></li></ol></pre></li>
<li>
<p>This document assumes that the executable named "perl" is Perl version 5.
Some systems may have installed Perl version 5 as "perl5".</p>
</li>
</ul>
<a name="See-also"></a><h1>See also</h1>
<p>For more information, consult <a href="perlguts.html">perlguts</a>, <a href="perlapi.html">perlapi</a>, <a href="perlxs.html">perlxs</a>, <a href="perlmod.html">perlmod</a>,
and <a href="perlpod.html">perlpod</a>.</p>
<a name="Author"></a><h1>Author</h1>
<p>Jeff Okamoto &lt;<i>okamoto@corp.hp.com</i>&gt;</p>
<p>Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig,
and Tim Bunce.</p>
<p>PerlIO material contributed by Lupe Christoph, with some clarification
by Nick Ing-Simmons.</p>
<p>Changes for h2xs as of Perl 5.8.x by Renee Baecker</p>
<a name="Last-Changed"></a><h2>Last Changed</h2>
<p>2012-01-20</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><li><a href="#SPECIAL-NOTES">SPECIAL NOTES</a><ul><li><a href="#make">make</a><li><a href="#Version-caveat">Version caveat</a><li><a href="#Dynamic-Loading-versus-Static-Loading">Dynamic Loading versus Static Loading</a><li><a href="#Threads-and-PERL_NO_GET_CONTEXT">Threads and PERL_NO_GET_CONTEXT</a></ul><li><a href="#TUTORIAL">TUTORIAL</a><ul><li><a href="#EXAMPLE-1">EXAMPLE 1</a><li><a href="#EXAMPLE-2">EXAMPLE 2</a><li><a href="#What-has-gone-on%3f">What has gone on?</a><li><a href="#Writing-good-test-scripts">Writing good test scripts</a><li><a href="#EXAMPLE-3">EXAMPLE 3</a><li><a href="#What's-new-here%3f">What's new here?</a><li><a href="#Input-and-Output-Parameters">Input and Output Parameters</a><li><a href="#The-XSUBPP-Program">The XSUBPP Program</a><li><a href="#The-TYPEMAP-file">The TYPEMAP file</a><li><a href="#Warning-about-Output-Arguments">Warning about Output Arguments</a><li><a href="#EXAMPLE-4">EXAMPLE 4</a><li><a href="#What-has-happened-here%3f">What has happened here?</a><li><a href="#Anatomy-of-.xs-file">Anatomy of .xs file</a><li><a href="#Getting-the-fat-out-of-XSUBs">Getting the fat out of XSUBs</a><li><a href="#More-about-XSUB-arguments">More about XSUB arguments</a><li><a href="#The-Argument-Stack">The Argument Stack</a><li><a href="#Extending-your-Extension">Extending your Extension</a><li><a href="#Documenting-your-Extension">Documenting your Extension</a><li><a href="#Installing-your-Extension">Installing your Extension</a><li><a href="#EXAMPLE-5">EXAMPLE 5</a><li><a href="#New-Things-in-this-Example">New Things in this Example</a><li><a href="#EXAMPLE-6">EXAMPLE 6</a><li><a href="#New-Things-in-this-Example">New Things in this Example</a><li><a href="#EXAMPLE-7-(Coming-Soon)">EXAMPLE 7 (Coming Soon)</a><li><a href="#EXAMPLE-8-(Coming-Soon)">EXAMPLE 8 (Coming Soon)</a><li><a href="#EXAMPLE-9-Passing-open-files-to-XSes">EXAMPLE 9 Passing open files to XSes</a><li><a href="#Troubleshooting-these-Examples">Troubleshooting these Examples</a></ul><li><a href="#See-also">See also</a><li><a href="#Author">Author</a><ul><li><a href="#Last-Changed">Last Changed</a></ul></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="mailto:jj@jonallen.info">Jon Allen (JJ)</a><br>
	    </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    = 'perlxstut';
  perldoc.pageAddress = 'perlxstut.html';
  perldoc.contentPage = 1;
  explorePerl.render();
  explorePerl.addEvents('explore_anchor');
</script>
    
  </body>
</html>