File: perlcall.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 (1466 lines) | stat: -rw-r--r-- 141,381 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
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>perlcall - 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>perlcall</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;
      
    
    perlcall
  

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


  <!--    -->
<ul><li><a href="#NAME">NAME</a><li><a href="#DESCRIPTION">DESCRIPTION</a><li><a href="#THE-CALL_-FUNCTIONS">THE CALL_ FUNCTIONS</a><li><a href="#FLAG-VALUES">FLAG VALUES</a><ul><li><a href="#G_VOID">G_VOID</a><li><a href="#G_SCALAR">G_SCALAR</a><li><a href="#G_ARRAY">G_ARRAY</a><li><a href="#G_DISCARD">G_DISCARD</a><li><a href="#G_NOARGS">G_NOARGS</a><li><a href="#G_EVAL">G_EVAL</a><li><a href="#G_KEEPERR">G_KEEPERR</a><li><a href="#Determining-the-Context">Determining the Context</a></ul><li><a href="#EXAMPLES">EXAMPLES</a><ul><li><a href="#No-Parameters%2c-Nothing-Returned">No Parameters, Nothing Returned</a><li><a href="#Passing-Parameters">Passing Parameters</a><li><a href="#Returning-a-Scalar">Returning a Scalar</a><li><a href="#Returning-a-List-of-Values">Returning a List of Values</a><li><a href="#Returning-a-List-in-Scalar-Context">Returning a List in Scalar Context</a><li><a href="#Returning-Data-from-Perl-via-the-Parameter-List">Returning Data from Perl via the Parameter List</a><li><a href="#Using-G_EVAL">Using G_EVAL</a><li><a href="#Using-G_KEEPERR">Using G_KEEPERR</a><li><a href="#Using-call_sv">Using call_sv</a><li><a href="#Using-call_argv">Using call_argv</a><li><a href="#Using-call_method">Using call_method</a><li><a href="#Using-GIMME_V">Using GIMME_V</a><li><a href="#Using-Perl-to-Dispose-of-Temporaries">Using Perl to Dispose of Temporaries</a><li><a href="#Strategies-for-Storing-Callback-Context-Information">Strategies for Storing Callback Context Information</a><li><a href="#Alternate-Stack-Manipulation">Alternate Stack Manipulation</a><li><a href="#Creating-and-Calling-an-Anonymous-Subroutine-in-C">Creating and Calling an Anonymous Subroutine in C</a></ul><li><a href="#LIGHTWEIGHT-CALLBACKS">LIGHTWEIGHT CALLBACKS</a><li><a href="#SEE-ALSO">SEE ALSO</a><li><a href="#AUTHOR">AUTHOR</a><li><a href="#DATE">DATE</a></ul><a name="NAME"></a><h1>NAME</h1>
<p>perlcall - Perl calling conventions from C</p>
<a name="DESCRIPTION"></a><h1>DESCRIPTION</h1>
<p>The purpose of this document is to show you how to call Perl subroutines
directly from C, i.e., how to write <i>callbacks</i>.</p>
<p>Apart from discussing the C interface provided by Perl for writing
callbacks the document uses a series of examples to show how the
interface actually works in practice.  In addition some techniques for
coding callbacks are covered.</p>
<p>Examples where callbacks are necessary include</p>
<ul>
<li><a name="*-An-Error-Handler"></a><b>An Error Handler</b>
<p>You have created an XSUB interface to an application's C API.</p>
<p>A fairly common feature in applications is to allow you to define a C
function that will be called whenever something nasty occurs. What we
would like is to be able to specify a Perl subroutine that will be
called instead.</p>
</li>
<li><a name="*-An-Event-Driven-Program"></a><b>An Event-Driven Program</b>
<p>The classic example of where callbacks are used is when writing an
event driven program, such as for an X11 application.  In this case
you register functions to be called whenever specific events occur,
e.g., a mouse button is pressed, the cursor moves into a window or a
menu item is selected.</p>
</li>
</ul>
<p>Although the techniques described here are applicable when embedding
Perl in a C program, this is not the primary goal of this document.
There are other details that must be considered and are specific to
embedding Perl. For details on embedding Perl in C refer to
<a href="perlembed.html">perlembed</a>.</p>
<p>Before you launch yourself head first into the rest of this document,
it would be a good idea to have read the following two documents--<a href="perlxs.html">perlxs</a>
and <a href="perlguts.html">perlguts</a>.</p>
<a name="THE-CALL_-FUNCTIONS"></a><h1>THE CALL_ FUNCTIONS</h1>
<p>Although this stuff is easier to explain using examples, you first need
be aware of a few important definitions.</p>
<p>Perl has a number of C functions that allow you to call Perl
subroutines.  They are</p>
<pre class="verbatim"><ol><li>    <span class="w">I32</span> <span class="i">call_sv</span><span class="s">(</span><span class="w">SV</span>* <span class="w">sv</span><span class="cm">,</span> <span class="w">I32</span> <span class="w">flags</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="w">I32</span> <span class="i">call_pv</span><span class="s">(</span><span class="w">char</span> *<span class="w">subname</span><span class="cm">,</span> <span class="w">I32</span> <span class="w">flags</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="w">I32</span> <span class="i">call_method</span><span class="s">(</span><span class="w">char</span> *<span class="w">methname</span><span class="cm">,</span> <span class="w">I32</span> <span class="w">flags</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="w">I32</span> <span class="i">call_argv</span><span class="s">(</span><span class="w">char</span> *<span class="w">subname</span><span class="cm">,</span> <span class="w">I32</span> <span class="w">flags</span><span class="cm">,</span> <span class="w">char</span> **<span class="w">argv</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The key function is <i>call_sv</i>.  All the other functions are
fairly simple wrappers which make it easier to call Perl subroutines in
special cases. At the end of the day they will all call <i>call_sv</i>
to invoke the Perl subroutine.</p>
<p>All the <i>call_*</i> functions have a <code class="inline"><span class="w">flags</span></code>
 parameter which is
used to pass a bit mask of options to Perl.  This bit mask operates
identically for each of the functions.  The settings available in the
bit mask are discussed in <a href="#FLAG-VALUES">FLAG VALUES</a>.</p>
<p>Each of the functions will now be discussed in turn.</p>
<ul>
<li><a name="call_sv"></a><b>call_sv</b>
<p><i>call_sv</i> takes two parameters. The first, <code class="inline"><span class="w">sv</span></code>
, is an SV*.
This allows you to specify the Perl subroutine to be called either as a
C string (which has first been converted to an SV) or a reference to a
subroutine. The section, <a href="#Using-call_sv">Using call_sv</a>, shows how you can make
use of <i>call_sv</i>.</p>
</li>
<li><a name="call_pv"></a><b>call_pv</b>
<p>The function, <i>call_pv</i>, is similar to <i>call_sv</i> except it
expects its first parameter to be a C char* which identifies the Perl
subroutine you want to call, e.g., <code class="inline"><span class="i">call_pv</span><span class="s">(</span><span class="q">&quot;fred&quot;</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span></code>
.  If the
subroutine you want to call is in another package, just include the
package name in the string, e.g., <code class="inline"><span class="q">&quot;pkg::fred&quot;</span></code>
.</p>
</li>
<li><a name="call_method"></a><b>call_method</b>
<p>The function <i>call_method</i> is used to call a method from a Perl
class.  The parameter <code class="inline"><span class="w">methname</span></code>
 corresponds to the name of the method
to be called.  Note that the class that the method belongs to is passed
on the Perl stack rather than in the parameter list. This class can be
either the name of the class (for a static method) or a reference to an
object (for a virtual method).  See <a href="perlobj.html">perlobj</a> for more information on
static and virtual methods and <a href="#Using-call_method">Using call_method</a> for an example
of using <i>call_method</i>.</p>
</li>
<li><a name="call_argv"></a><b>call_argv</b>
<p><i>call_argv</i> calls the Perl subroutine specified by the C string
stored in the <code class="inline"><span class="w">subname</span></code>
 parameter. It also takes the usual <code class="inline"><span class="w">flags</span></code>

parameter.  The final parameter, <code class="inline"><span class="w">argv</span></code>
, consists of a NULL-terminated
list of C strings to be passed as parameters to the Perl subroutine.
See <a href="#Using-call_argv">Using call_argv</a>.</p>
</li>
</ul>
<p>All the functions return an integer. This is a count of the number of
items returned by the Perl subroutine. The actual items returned by the
subroutine are stored on the Perl stack.</p>
<p>As a general rule you should <i>always</i> check the return value from
these functions.  Even if you are expecting only a particular number of
values to be returned from the Perl subroutine, there is nothing to
stop someone from doing something unexpected--don't say you haven't
been warned.</p>
<a name="FLAG-VALUES"></a><h1>FLAG VALUES</h1>
<p>The <code class="inline"><span class="w">flags</span></code>
 parameter in all the <i>call_*</i> functions is one of G_VOID,
G_SCALAR, or G_ARRAY, which indicate the call context, OR'ed together
with a bit mask of any combination of the other G_* symbols defined below.</p>
<a name="G_VOID"></a><h2>G_VOID</h2>
<p>Calls the Perl subroutine in a void context.</p>
<p>This flag has 2 effects:</p>
<dl>
<dt>1.</dt><dd>
<p>It indicates to the subroutine being called that it is executing in
a void context (if it executes <i>wantarray</i> the result will be the
undefined value).</p>
</dd>
<dt>2.</dt><dd>
<p>It ensures that nothing is actually returned from the subroutine.</p>
</dd>
</dl>
<p>The value returned by the <i>call_*</i> function indicates how many
items have been returned by the Perl subroutine--in this case it will
be 0.</p>
<a name="G_SCALAR"></a><h2>G_SCALAR</h2>
<p>Calls the Perl subroutine in a scalar context.  This is the default
context flag setting for all the <i>call_*</i> functions.</p>
<p>This flag has 2 effects:</p>
<dl>
<dt>1.</dt><dd>
<p>It indicates to the subroutine being called that it is executing in a
scalar context (if it executes <i>wantarray</i> the result will be false).</p>
</dd>
<dt>2.</dt><dd>
<p>It ensures that only a scalar is actually returned from the subroutine.
The subroutine can, of course,  ignore the <i>wantarray</i> and return a
list anyway. If so, then only the last element of the list will be
returned.</p>
</dd>
</dl>
<p>The value returned by the <i>call_*</i> function indicates how many
items have been returned by the Perl subroutine - in this case it will
be either 0 or 1.</p>
<p>If 0, then you have specified the G_DISCARD flag.</p>
<p>If 1, then the item actually returned by the Perl subroutine will be
stored on the Perl stack - the section <a href="#Returning-a-Scalar">Returning a Scalar</a> shows how
to access this value on the stack.  Remember that regardless of how
many items the Perl subroutine returns, only the last one will be
accessible from the stack - think of the case where only one value is
returned as being a list with only one element.  Any other items that
were returned will not exist by the time control returns from the
<i>call_*</i> function.  The section <a href="#Returning-a-List-in-Scalar-Context">Returning a List in Scalar Context</a> shows an example of this behavior.</p>
<a name="G_ARRAY"></a><h2>G_ARRAY</h2>
<p>Calls the Perl subroutine in a list context.</p>
<p>As with G_SCALAR, this flag has 2 effects:</p>
<dl>
<dt>1.</dt><dd>
<p>It indicates to the subroutine being called that it is executing in a
list context (if it executes <i>wantarray</i> the result will be true).</p>
</dd>
<dt>2.</dt><dd>
<p>It ensures that all items returned from the subroutine will be
accessible when control returns from the <i>call_*</i> function.</p>
</dd>
</dl>
<p>The value returned by the <i>call_*</i> function indicates how many
items have been returned by the Perl subroutine.</p>
<p>If 0, then you have specified the G_DISCARD flag.</p>
<p>If not 0, then it will be a count of the number of items returned by
the subroutine. These items will be stored on the Perl stack.  The
section <a href="#Returning-a-List-of-Values">Returning a List of Values</a> gives an example of using the
G_ARRAY flag and the mechanics of accessing the returned items from the
Perl stack.</p>
<a name="G_DISCARD"></a><h2>G_DISCARD</h2>
<p>By default, the <i>call_*</i> functions place the items returned from
by the Perl subroutine on the stack.  If you are not interested in
these items, then setting this flag will make Perl get rid of them
automatically for you.  Note that it is still possible to indicate a
context to the Perl subroutine by using either G_SCALAR or G_ARRAY.</p>
<p>If you do not set this flag then it is <i>very</i> important that you make
sure that any temporaries (i.e., parameters passed to the Perl
subroutine and values returned from the subroutine) are disposed of
yourself.  The section <a href="#Returning-a-Scalar">Returning a Scalar</a> gives details of how to
dispose of these temporaries explicitly and the section <a href="#Using-Perl-to-Dispose-of-Temporaries">Using Perl to Dispose of Temporaries</a> discusses the specific circumstances where you
can ignore the problem and let Perl deal with it for you.</p>
<a name="G_NOARGS"></a><h2>G_NOARGS</h2>
<p>Whenever a Perl subroutine is called using one of the <i>call_*</i>
functions, it is assumed by default that parameters are to be passed to
the subroutine.  If you are not passing any parameters to the Perl
subroutine, you can save a bit of time by setting this flag.  It has
the effect of not creating the <code class="inline"><span class="i">@_</span></code>
 array for the Perl subroutine.</p>
<p>Although the functionality provided by this flag may seem
straightforward, it should be used only if there is a good reason to do
so.  The reason for being cautious is that, even if you have specified
the G_NOARGS flag, it is still possible for the Perl subroutine that
has been called to think that you have passed it parameters.</p>
<p>In fact, what can happen is that the Perl subroutine you have called
can access the <code class="inline"><span class="i">@_</span></code>
 array from a previous Perl subroutine.  This will
occur when the code that is executing the <i>call_*</i> function has
itself been called from another Perl subroutine. The code below
illustrates this</p>
<pre class="verbatim"><ol><li><a name="fred"></a>    sub <span class="m">fred</span></li><li>      <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;@_\n&quot;</span>  <span class="s">}</span></li><li></li><li><a name="joe"></a>    sub <span class="m">joe</span></li><li>      <span class="s">{</span> <span class="i">&amp;fred</span> <span class="s">}</span></li><li></li><li>    <span class="i">&amp;joe</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="n">3</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>This will print</p>
<pre class="verbatim"><ol><li>    1 2 3</li></ol></pre><p>What has happened is that <code class="inline"><span class="w">fred</span></code>
 accesses the <code class="inline"><span class="i">@_</span></code>
 array which
belongs to <code class="inline"><span class="w">joe</span></code>
.</p>
<a name="G_EVAL"></a><h2>G_EVAL</h2>
<p>It is possible for the Perl subroutine you are calling to terminate
abnormally, e.g., by calling <i>die</i> explicitly or by not actually
existing.  By default, when either of these events occurs, the
process will terminate immediately.  If you want to trap this
type of event, specify the G_EVAL flag.  It will put an <i>eval { }</i>
around the subroutine call.</p>
<p>Whenever control returns from the <i>call_*</i> function you need to
check the <code class="inline"><span class="i">$@</span></code>
 variable as you would in a normal Perl script.</p>
<p>The value returned from the <i>call_*</i> function is dependent on
what other flags have been specified and whether an error has
occurred.  Here are all the different cases that can occur:</p>
<ul>
<li>
<p>If the <i>call_*</i> function returns normally, then the value
returned is as specified in the previous sections.</p>
</li>
<li>
<p>If G_DISCARD is specified, the return value will always be 0.</p>
</li>
<li>
<p>If G_ARRAY is specified <i>and</i> an error has occurred, the return value
will always be 0.</p>
</li>
<li>
<p>If G_SCALAR is specified <i>and</i> an error has occurred, the return value
will be 1 and the value on the top of the stack will be <i>undef</i>. This
means that if you have already detected the error by checking <code class="inline"><span class="i">$@</span></code>
 and
you want the program to continue, you must remember to pop the <i>undef</i>
from the stack.</p>
</li>
</ul>
<p>See <a href="#Using-G_EVAL">Using G_EVAL</a> for details on using G_EVAL.</p>
<a name="G_KEEPERR"></a><h2>G_KEEPERR</h2>
<p>Using the G_EVAL flag described above will always set <code class="inline"><span class="i">$@</span></code>
: clearing
it if there was no error, and setting it to describe the error if there
was an error in the called code.  This is what you want if your intention
is to handle possible errors, but sometimes you just want to trap errors
and stop them interfering with the rest of the program.</p>
<p>This scenario will mostly be applicable to code that is meant to be called
from within destructors, asynchronous callbacks, and signal handlers.
In such situations, where the code being called has little relation to the
surrounding dynamic context, the main program needs to be insulated from
errors in the called code, even if they can't be handled intelligently.
It may also be useful to do this with code for <code class="inline"><span class="w">__DIE__</span></code>
 or <code class="inline"><span class="w">__WARN__</span></code>

hooks, and <code class="inline"><a class="l_k" href="functions/tie.html">tie</a></code> functions.</p>
<p>The G_KEEPERR flag is meant to be used in conjunction with G_EVAL in
<i>call_*</i> functions that are used to implement such code, or with
<code class="inline"><span class="w">eval_sv</span></code>
.  This flag has no effect on the <code class="inline"><span class="w">call_</span>*</code>
 functions when
G_EVAL is not used.</p>
<p>When G_KEEPERR is used, any error in the called code will terminate the
call as usual, and the error will not propagate beyond the call (as usual
for G_EVAL), but it will not go into <code class="inline"><span class="i">$@</span></code>
.  Instead the error will be
converted into a warning, prefixed with the string "\t(in cleanup)".
This can be disabled using <code class="inline"><a class="l_k" href="functions/no.html">no</a> <span class="w">warnings</span> <span class="q">&#39;misc&#39;</span></code>
.  If there is no error,
<code class="inline"><span class="i">$@</span></code>
 will not be cleared.</p>
<p>Note that the G_KEEPERR flag does not propagate into inner evals; these
may still set <code class="inline"><span class="i">$@</span></code>
.</p>
<p>The G_KEEPERR flag was introduced in Perl version 5.002.</p>
<p>See <a href="#Using-G_KEEPERR">Using G_KEEPERR</a> for an example of a situation that warrants the
use of this flag.</p>
<a name="Determining-the-Context"></a><h2>Determining the Context</h2>
<p>As mentioned above, you can determine the context of the currently
executing subroutine in Perl with <i>wantarray</i>.  The equivalent test
can be made in C by using the <code class="inline"><span class="w">GIMME_V</span></code>
 macro, which returns
<code class="inline"><span class="w">G_ARRAY</span></code>
 if you have been called in a list context, <code class="inline"><span class="w">G_SCALAR</span></code>
 if
in a scalar context, or <code class="inline"><span class="w">G_VOID</span></code>
 if in a void context (i.e., the
return value will not be used).  An older version of this macro is
called <code class="inline"><span class="w">GIMME</span></code>
; in a void context it returns <code class="inline"><span class="w">G_SCALAR</span></code>
 instead of
<code class="inline"><span class="w">G_VOID</span></code>
.  An example of using the <code class="inline"><span class="w">GIMME_V</span></code>
 macro is shown in
section <a href="#Using-GIMME_V">Using GIMME_V</a>.</p>
<a name="EXAMPLES"></a><h1>EXAMPLES</h1>
<p>Enough of the definition talk! Let's have a few examples.</p>
<p>Perl provides many macros to assist in accessing the Perl stack.
Wherever possible, these macros should always be used when interfacing
to Perl internals.  We hope this should make the code less vulnerable
to any changes made to Perl in the future.</p>
<p>Another point worth noting is that in the first series of examples I
have made use of only the <i>call_pv</i> function.  This has been done
to keep the code simpler and ease you into the topic.  Wherever
possible, if the choice is between using <i>call_pv</i> and
<i>call_sv</i>, you should always try to use <i>call_sv</i>.  See
<a href="#Using-call_sv">Using call_sv</a> for details.</p>
<a name="No-Parameters%2c-Nothing-Returned"></a><h2>No Parameters, Nothing Returned</h2>
<p>This first trivial example will call a Perl subroutine, <i>PrintUID</i>, to
print out the UID of the process.</p>
<pre class="verbatim"><ol><li><a name="PrintUID"></a>    sub <span class="m">PrintUID</span></li><li>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;UID is $&lt;\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>and here is a C function to call it</p>
<pre class="verbatim"><ol><li>    static void</li><li>    call_PrintUID()</li><li>    {</li><li>        dSP;</li><li></li><li>        PUSHMARK(SP);</li><li>        call_pv("PrintUID", G_DISCARD|G_NOARGS);</li><li>    }</li></ol></pre><p>Simple, eh?</p>
<p>A few points to note about this example:</p>
<dl>
<dt>1.</dt><dd>
<p>Ignore <code class="inline"><span class="w">dSP</span></code>
 and <code class="inline"><span class="i">PUSHMARK</span><span class="s">(</span><span class="w">SP</span><span class="s">)</span></code>
 for now. They will be discussed in
the next example.</p>
</dd>
<dt>2.</dt><dd>
<p>We aren't passing any parameters to <i>PrintUID</i> so G_NOARGS can be
specified.</p>
</dd>
<dt>3.</dt><dd>
<p>We aren't interested in anything returned from <i>PrintUID</i>, so
G_DISCARD is specified. Even if <i>PrintUID</i> was changed to
return some value(s), having specified G_DISCARD will mean that they
will be wiped by the time control returns from <i>call_pv</i>.</p>
</dd>
<dt>4.</dt><dd>
<p>As <i>call_pv</i> is being used, the Perl subroutine is specified as a
C string. In this case the subroutine name has been 'hard-wired' into the
code.</p>
</dd>
<dt>5.</dt><dd>
<p>Because we specified G_DISCARD, it is not necessary to check the value
returned from <i>call_pv</i>. It will always be 0.</p>
</dd>
</dl>
<a name="Passing-Parameters"></a><h2>Passing Parameters</h2>
<p>Now let's make a slightly more complex example. This time we want to
call a Perl subroutine, <code class="inline"><span class="w">LeftString</span></code>
, which will take 2 parameters--a
string ($s) and an integer ($n).  The subroutine will simply
print the first $n characters of the string.</p>
<p>So the Perl subroutine would look like this:</p>
<pre class="verbatim"><ol><li><a name="LeftString"></a>    sub <span class="m">LeftString</span></li><li>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$s</span><span class="cm">,</span> <span class="i">$n</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$s</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="i">$n</span><span class="s">)</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>The C function required to call <i>LeftString</i> would look like this:</p>
<pre class="verbatim"><ol><li>    <span class="w">static</span> <span class="w">void</span></li><li>    <span class="i">call_LeftString</span><span class="s">(</span><span class="w">a</span><span class="cm">,</span> <span class="w">b</span><span class="s">)</span></li><li>    <span class="w">char</span> * <span class="w">a</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/int.html">int</a> <span class="w">b</span><span class="sc">;</span></li><li>    <span class="s">{</span></li><li>        <span class="w">dSP</span><span class="sc">;</span></li><li></li><li>	<span class="w">ENTER</span><span class="sc">;</span></li><li>        <span class="w">SAVETMPS</span><span class="sc">;</span></li><li></li><li>        <span class="i">PUSHMARK</span><span class="s">(</span><span class="w">SP</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">EXTEND</span><span class="s">(</span><span class="w">SP</span><span class="cm">,</span> <span class="n">2</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSVpv</span><span class="s">(</span><span class="w">a</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">b</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="w">PUTBACK</span><span class="sc">;</span></li><li></li><li>        <span class="i">call_pv</span><span class="s">(</span><span class="q">&quot;LeftString&quot;</span><span class="cm">,</span> <span class="w">G_DISCARD</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <span class="w">FREETMPS</span><span class="sc">;</span></li><li>        <span class="w">LEAVE</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>Here are a few notes on the C function <i>call_LeftString</i>.</p>
<dl>
<dt>1.</dt><dd>
<p>Parameters are passed to the Perl subroutine using the Perl stack.
This is the purpose of the code beginning with the line <code class="inline"><span class="w">dSP</span></code>
 and
ending with the line <code class="inline"><span class="w">PUTBACK</span></code>
.  The <code class="inline"><span class="w">dSP</span></code>
 declares a local copy
of the stack pointer.  This local copy should <b>always</b> be accessed
as <code class="inline"><span class="w">SP</span></code>
.</p>
</dd>
<dt>2.</dt><dd>
<p>If you are going to put something onto the Perl stack, you need to know
where to put it. This is the purpose of the macro <code class="inline"><span class="w">dSP</span></code>
--it declares
and initializes a <i>local</i> copy of the Perl stack pointer.</p>
<p>All the other macros which will be used in this example require you to
have used this macro.</p>
<p>The exception to this rule is if you are calling a Perl subroutine
directly from an XSUB function. In this case it is not necessary to
use the <code class="inline"><span class="w">dSP</span></code>
 macro explicitly--it will be declared for you
automatically.</p>
</dd>
<dt>3.</dt><dd>
<p>Any parameters to be pushed onto the stack should be bracketed by the
<code class="inline"><span class="w">PUSHMARK</span></code>
 and <code class="inline"><span class="w">PUTBACK</span></code>
 macros.  The purpose of these two macros, in
this context, is to count the number of parameters you are
pushing automatically.  Then whenever Perl is creating the <code class="inline"><span class="i">@_</span></code>
 array for the
subroutine, it knows how big to make it.</p>
<p>The <code class="inline"><span class="w">PUSHMARK</span></code>
 macro tells Perl to make a mental note of the current
stack pointer. Even if you aren't passing any parameters (like the
example shown in the section <a href="#No-Parameters%2c-Nothing-Returned">No Parameters, Nothing Returned</a>) you
must still call the <code class="inline"><span class="w">PUSHMARK</span></code>
 macro before you can call any of the
<i>call_*</i> functions--Perl still needs to know that there are no
parameters.</p>
<p>The <code class="inline"><span class="w">PUTBACK</span></code>
 macro sets the global copy of the stack pointer to be
the same as our local copy. If we didn't do this, <i>call_pv</i>
wouldn't know where the two parameters we pushed were--remember that
up to now all the stack pointer manipulation we have done is with our
local copy, <i>not</i> the global copy.</p>
</dd>
<dt>4.</dt><dd>
<p>Next, we come to EXTEND and PUSHs. This is where the parameters
actually get pushed onto the stack. In this case we are pushing a
string and an integer.</p>
<p>Alternatively you can use the XPUSHs() macro, which combines a
<code class="inline"><span class="i">EXTEND</span><span class="s">(</span><span class="w">SP</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span></code>
 and <code class="inline"><span class="i">PUSHs</span><span class="s">(</span><span class="s">)</span></code>
.  This is less efficient if you're
pushing multiple values.</p>
<p>See <a href="perlguts.html#XSUBs-and-the-Argument-Stack">XSUBs and the Argument Stack in perlguts</a> for details
on how the PUSH macros work.</p>
</dd>
<dt>5.</dt><dd>
<p>Because we created temporary values (by means of sv_2mortal() calls)
we will have to tidy up the Perl stack and dispose of mortal SVs.</p>
<p>This is the purpose of</p>
<pre class="verbatim"><ol><li>    <span class="w">ENTER</span><span class="sc">;</span></li><li>    <span class="w">SAVETMPS</span><span class="sc">;</span></li></ol></pre><p>at the start of the function, and</p>
<pre class="verbatim"><ol><li>    <span class="w">FREETMPS</span><span class="sc">;</span></li><li>    <span class="w">LEAVE</span><span class="sc">;</span></li></ol></pre><p>at the end. The <code class="inline"><span class="w">ENTER</span></code>
/<code class="inline"><span class="w">SAVETMPS</span></code>
 pair creates a boundary for any
temporaries we create.  This means that the temporaries we get rid of
will be limited to those which were created after these calls.</p>
<p>The <code class="inline"><span class="w">FREETMPS</span></code>
/<code class="inline"><span class="w">LEAVE</span></code>
 pair will get rid of any values returned by
the Perl subroutine (see next example), plus it will also dump the
mortal SVs we have created.  Having <code class="inline"><span class="w">ENTER</span></code>
/<code class="inline"><span class="w">SAVETMPS</span></code>
 at the
beginning of the code makes sure that no other mortals are destroyed.</p>
<p>Think of these macros as working a bit like <code class="inline">{</code> and <code class="inline">}</code> in Perl
to limit the scope of local variables.</p>
<p>See the section <a href="#Using-Perl-to-Dispose-of-Temporaries">Using Perl to Dispose of Temporaries</a> for details of
an alternative to using these macros.</p>
</dd>
<dt>6.</dt><dd>
<p>Finally, <i>LeftString</i> can now be called via the <i>call_pv</i> function.
The only flag specified this time is G_DISCARD. Because we are passing
2 parameters to the Perl subroutine this time, we have not specified
G_NOARGS.</p>
</dd>
</dl>
<a name="Returning-a-Scalar"></a><h2>Returning a Scalar</h2>
<p>Now for an example of dealing with the items returned from a Perl
subroutine.</p>
<p>Here is a Perl subroutine, <i>Adder</i>, that takes 2 integer parameters
and simply returns their sum.</p>
<pre class="verbatim"><ol><li><a name="Adder"></a>    sub <span class="m">Adder</span></li><li>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$a</span><span class="cm">,</span> <span class="i">$b</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>        <span class="i">$a</span> + <span class="i">$b</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>Because we are now concerned with the return value from <i>Adder</i>, the C
function required to call it is now a bit more complex.</p>
<pre class="verbatim"><ol><li>    <span class="w">static</span> <span class="w">void</span></li><li>    <span class="i">call_Adder</span><span class="s">(</span><span class="w">a</span><span class="cm">,</span> <span class="w">b</span><span class="s">)</span></li><li>    <a class="l_k" href="functions/int.html">int</a> <span class="w">a</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/int.html">int</a> <span class="w">b</span><span class="sc">;</span></li><li>    <span class="s">{</span></li><li>        <span class="w">dSP</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/int.html">int</a> <span class="w">count</span><span class="sc">;</span></li><li></li><li>        <span class="w">ENTER</span><span class="sc">;</span></li><li>        <span class="w">SAVETMPS</span><span class="sc">;</span></li><li></li><li>        <span class="i">PUSHMARK</span><span class="s">(</span><span class="w">SP</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">EXTEND</span><span class="s">(</span><span class="w">SP</span><span class="cm">,</span> <span class="n">2</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">a</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">b</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="w">PUTBACK</span><span class="sc">;</span></li><li></li><li>        <span class="w">count</span> = <span class="i">call_pv</span><span class="s">(</span><span class="q">&quot;Adder&quot;</span><span class="cm">,</span> <span class="w">G_SCALAR</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <span class="w">SPAGAIN</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="w">count</span> != <span class="n">1</span><span class="s">)</span></li><li>            <span class="i">croak</span><span class="s">(</span><span class="q">&quot;Big trouble\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;The sum of %d and %d is %d\n&quot;</span><span class="cm">,</span> <span class="w">a</span><span class="cm">,</span> <span class="w">b</span><span class="cm">,</span> <span class="w">POPi</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <span class="w">PUTBACK</span><span class="sc">;</span></li><li>        <span class="w">FREETMPS</span><span class="sc">;</span></li><li>        <span class="w">LEAVE</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>Points to note this time are</p>
<dl>
<dt>1.</dt><dd>
<p>The only flag specified this time was G_SCALAR. That means that the <code class="inline"><span class="i">@_</span></code>

array will be created and that the value returned by <i>Adder</i> will
still exist after the call to <i>call_pv</i>.</p>
</dd>
<dt>2.</dt><dd>
<p>The purpose of the macro <code class="inline"><span class="w">SPAGAIN</span></code>
 is to refresh the local copy of the
stack pointer. This is necessary because it is possible that the memory
allocated to the Perl stack has been reallocated during the
<i>call_pv</i> call.</p>
<p>If you are making use of the Perl stack pointer in your code you must
always refresh the local copy using SPAGAIN whenever you make use
of the <i>call_*</i> functions or any other Perl internal function.</p>
</dd>
<dt>3.</dt><dd>
<p>Although only a single value was expected to be returned from <i>Adder</i>,
it is still good practice to check the return code from <i>call_pv</i>
anyway.</p>
<p>Expecting a single value is not quite the same as knowing that there
will be one. If someone modified <i>Adder</i> to return a list and we
didn't check for that possibility and take appropriate action the Perl
stack would end up in an inconsistent state. That is something you
<i>really</i> don't want to happen ever.</p>
</dd>
<dt>4.</dt><dd>
<p>The <code class="inline"><span class="w">POPi</span></code>
 macro is used here to pop the return value from the stack.
In this case we wanted an integer, so <code class="inline"><span class="w">POPi</span></code>
 was used.</p>
<p>Here is the complete list of POP macros available, along with the types
they return.</p>
<pre class="verbatim"><ol><li>    <span class="w">POPs</span>	<span class="w">SV</span></li><li>    <span class="w">POPp</span>	<span class="w">pointer</span> <span class="s">(</span><span class="w">PV</span><span class="s">)</span></li><li>    <span class="w">POPpbytex</span>   <span class="w">pointer</span> <span class="w">to</span> <span class="w">bytes</span> <span class="s">(</span><span class="w">PV</span><span class="s">)</span></li><li>    <span class="w">POPn</span>	<span class="w">double</span> <span class="s">(</span><span class="w">NV</span><span class="s">)</span></li><li>    <span class="w">POPi</span>	<span class="w">integer</span> <span class="s">(</span><span class="w">IV</span><span class="s">)</span></li><li>    <span class="w">POPu</span>        <span class="w">unsigned</span> <span class="w">integer</span> <span class="s">(</span><span class="w">UV</span><span class="s">)</span></li><li>    <span class="w">POPl</span>	<span class="w">long</span></li><li>    <span class="w">POPul</span>       <span class="w">unsigned</span> <span class="w">long</span></li></ol></pre><p>Since these macros have side-effects don't use them as arguments to
macros that may evaluate their argument several times, for example:</p>
<pre class="verbatim"><ol><li>  <span class="q">/* Bad idea, don&#39;t do this */</span></li><li>  <span class="w">STRLEN</span> <span class="w">len</span><span class="sc">;</span></li><li>  <span class="w">const</span> <span class="w">char</span> *<span class="q">s = SvPV(POPs, len);</span></li></ol></pre><p>Instead, use a temporary:</p>
<pre class="verbatim"><ol><li>  <span class="w">STRLEN</span> <span class="w">len</span><span class="sc">;</span></li><li>  <span class="w">SV</span> *<span class="w">sv</span> = <span class="w">POPs</span><span class="sc">;</span></li><li>  <span class="w">const</span> <span class="w">char</span> *<span class="q">s = SvPV(sv, len);</span></li></ol></pre><p>or a macro that guarantees it will evaluate its arguments only once:</p>
<pre class="verbatim"><ol><li>  <span class="w">STRLEN</span> <span class="w">len</span><span class="sc">;</span></li><li>  <span class="w">const</span> <span class="w">char</span> *<span class="q">s = SvPVx(POPs, len);</span></li></ol></pre></dd>
<dt>5.</dt><dd>
<p>The final <code class="inline"><span class="w">PUTBACK</span></code>
 is used to leave the Perl stack in a consistent
state before exiting the function.  This is necessary because when we
popped the return value from the stack with <code class="inline"><span class="w">POPi</span></code>
 it updated only our
local copy of the stack pointer.  Remember, <code class="inline"><span class="w">PUTBACK</span></code>
 sets the global
stack pointer to be the same as our local copy.</p>
</dd>
</dl>
<a name="Returning-a-List-of-Values"></a><h2>Returning a List of Values</h2>
<p>Now, let's extend the previous example to return both the sum of the
parameters and the difference.</p>
<p>Here is the Perl subroutine</p>
<pre class="verbatim"><ol><li><a name="AddSubtract"></a>    sub <span class="m">AddSubtract</span></li><li>    <span class="s">{</span></li><li>       <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$a</span><span class="cm">,</span> <span class="i">$b</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>       <span class="s">(</span><span class="i">$a</span>+<span class="i">$b</span><span class="cm">,</span> <span class="i">$a</span>-<span class="i">$b</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>and this is the C function</p>
<pre class="verbatim"><ol><li>    <span class="w">static</span> <span class="w">void</span></li><li>    <span class="i">call_AddSubtract</span><span class="s">(</span><span class="w">a</span><span class="cm">,</span> <span class="w">b</span><span class="s">)</span></li><li>    <a class="l_k" href="functions/int.html">int</a> <span class="w">a</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/int.html">int</a> <span class="w">b</span><span class="sc">;</span></li><li>    <span class="s">{</span></li><li>        <span class="w">dSP</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/int.html">int</a> <span class="w">count</span><span class="sc">;</span></li><li></li><li>        <span class="w">ENTER</span><span class="sc">;</span></li><li>        <span class="w">SAVETMPS</span><span class="sc">;</span></li><li></li><li>        <span class="i">PUSHMARK</span><span class="s">(</span><span class="w">SP</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">EXTEND</span><span class="s">(</span><span class="w">SP</span><span class="cm">,</span> <span class="n">2</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">a</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">b</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="w">PUTBACK</span><span class="sc">;</span></li><li></li><li>        <span class="w">count</span> = <span class="i">call_pv</span><span class="s">(</span><span class="q">&quot;AddSubtract&quot;</span><span class="cm">,</span> <span class="w">G_ARRAY</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <span class="w">SPAGAIN</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="w">count</span> != <span class="n">2</span><span class="s">)</span></li><li>            <span class="i">croak</span><span class="s">(</span><span class="q">&quot;Big trouble\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;%d - %d = %d\n&quot;</span><span class="cm">,</span> <span class="w">a</span><span class="cm">,</span> <span class="w">b</span><span class="cm">,</span> <span class="w">POPi</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;%d + %d = %d\n&quot;</span><span class="cm">,</span> <span class="w">a</span><span class="cm">,</span> <span class="w">b</span><span class="cm">,</span> <span class="w">POPi</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <span class="w">PUTBACK</span><span class="sc">;</span></li><li>        <span class="w">FREETMPS</span><span class="sc">;</span></li><li>        <span class="w">LEAVE</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>If <i>call_AddSubtract</i> is called like this</p>
<pre class="verbatim"><ol><li>    <span class="i">call_AddSubtract</span><span class="s">(</span><span class="n">7</span><span class="cm">,</span> <span class="n">4</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>then here is the output</p>
<pre class="verbatim"><ol><li>    7 - 4 = 3</li><li>    7 + 4 = 11</li></ol></pre><p>Notes</p>
<dl>
<dt>1.</dt><dd>
<p>We wanted list context, so G_ARRAY was used.</p>
</dd>
<dt>2.</dt><dd>
<p>Not surprisingly <code class="inline"><span class="w">POPi</span></code>
 is used twice this time because we were
retrieving 2 values from the stack. The important thing to note is that
when using the <code class="inline"><span class="w">POP</span>*</code>
 macros they come off the stack in <i>reverse</i>
order.</p>
</dd>
</dl>
<a name="Returning-a-List-in-Scalar-Context"></a><h2>Returning a List in Scalar Context</h2>
<p>Say the Perl subroutine in the previous section was called in a scalar
context, like this</p>
<pre class="verbatim"><ol><li>    <span class="w">static</span> <span class="w">void</span></li><li>    <span class="i">call_AddSubScalar</span><span class="s">(</span><span class="w">a</span><span class="cm">,</span> <span class="w">b</span><span class="s">)</span></li><li>    <a class="l_k" href="functions/int.html">int</a> <span class="w">a</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/int.html">int</a> <span class="w">b</span><span class="sc">;</span></li><li>    <span class="s">{</span></li><li>        <span class="w">dSP</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/int.html">int</a> <span class="w">count</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></li><li>        <span class="w">ENTER</span><span class="sc">;</span></li><li>        <span class="w">SAVETMPS</span><span class="sc">;</span></li><li></li><li>        <span class="i">PUSHMARK</span><span class="s">(</span><span class="w">SP</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">EXTEND</span><span class="s">(</span><span class="w">SP</span><span class="cm">,</span> <span class="n">2</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">a</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">b</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="w">PUTBACK</span><span class="sc">;</span></li><li></li><li>        <span class="w">count</span> = <span class="i">call_pv</span><span class="s">(</span><span class="q">&quot;AddSubtract&quot;</span><span class="cm">,</span> <span class="w">G_SCALAR</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <span class="w">SPAGAIN</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;Items Returned = %d\n&quot;</span><span class="cm">,</span> <span class="w">count</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/for.html">for</a> <span class="s">(</span><span class="w">i</span> = <span class="n">1</span><span class="sc">;</span> <span class="w">i</span> &lt;= <span class="w">count</span><span class="sc">;</span> ++<span class="w">i</span><span class="s">)</span></li><li>            <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;Value %d = %d\n&quot;</span><span class="cm">,</span> <span class="w">i</span><span class="cm">,</span> <span class="w">POPi</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <span class="w">PUTBACK</span><span class="sc">;</span></li><li>        <span class="w">FREETMPS</span><span class="sc">;</span></li><li>        <span class="w">LEAVE</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>The other modification made is that <i>call_AddSubScalar</i> will print the
number of items returned from the Perl subroutine and their value (for
simplicity it assumes that they are integer).  So if
<i>call_AddSubScalar</i> is called</p>
<pre class="verbatim"><ol><li>    <span class="i">call_AddSubScalar</span><span class="s">(</span><span class="n">7</span><span class="cm">,</span> <span class="n">4</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>then the output will be</p>
<pre class="verbatim"><ol><li>    Items Returned = 1</li><li>    Value 1 = 3</li></ol></pre><p>In this case the main point to note is that only the last item in the
list is returned from the subroutine. <i>AddSubtract</i> actually made it back to
<i>call_AddSubScalar</i>.</p>
<a name="Returning-Data-from-Perl-via-the-Parameter-List"></a><h2>Returning Data from Perl via the Parameter List</h2>
<p>It is also possible to return values directly via the parameter
list--whether it is actually desirable to do it is another matter entirely.</p>
<p>The Perl subroutine, <i>Inc</i>, below takes 2 parameters and increments
each directly.</p>
<pre class="verbatim"><ol><li><a name="Inc"></a>    sub <span class="m">Inc</span></li><li>    <span class="s">{</span></li><li>        ++ <span class="i">$_</span>[<span class="n">0</span>]<span class="sc">;</span></li><li>        ++ <span class="i">$_</span>[<span class="n">1</span>]<span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>and here is a C function to call it.</p>
<pre class="verbatim"><ol><li>    <span class="w">static</span> <span class="w">void</span></li><li>    <span class="i">call_Inc</span><span class="s">(</span><span class="w">a</span><span class="cm">,</span> <span class="w">b</span><span class="s">)</span></li><li>    <a class="l_k" href="functions/int.html">int</a> <span class="w">a</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/int.html">int</a> <span class="w">b</span><span class="sc">;</span></li><li>    <span class="s">{</span></li><li>        <span class="w">dSP</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/int.html">int</a> <span class="w">count</span><span class="sc">;</span></li><li>        <span class="w">SV</span> * <span class="w">sva</span><span class="sc">;</span></li><li>        <span class="w">SV</span> * <span class="w">svb</span><span class="sc">;</span></li><li></li><li>        <span class="w">ENTER</span><span class="sc">;</span></li><li>        <span class="w">SAVETMPS</span><span class="sc">;</span></li><li></li><li>        <span class="w">sva</span> = <span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">a</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="w">svb</span> = <span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">b</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <span class="i">PUSHMARK</span><span class="s">(</span><span class="w">SP</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">EXTEND</span><span class="s">(</span><span class="w">SP</span><span class="cm">,</span> <span class="n">2</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="w">sva</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="w">svb</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="w">PUTBACK</span><span class="sc">;</span></li><li></li><li>        <span class="w">count</span> = <span class="i">call_pv</span><span class="s">(</span><span class="q">&quot;Inc&quot;</span><span class="cm">,</span> <span class="w">G_DISCARD</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="w">count</span> != <span class="n">0</span><span class="s">)</span></li><li>            <span class="w">croak</span> <span class="s">(</span><span class="q">&quot;call_Inc: expected 0 values from &#39;Inc&#39;, got %d\n&quot;</span><span class="cm">,</span></li><li>                   <span class="w">count</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;%d + 1 = %d\n&quot;</span><span class="cm">,</span> <span class="w">a</span><span class="cm">,</span> <span class="i">SvIV</span><span class="s">(</span><span class="w">sva</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;%d + 1 = %d\n&quot;</span><span class="cm">,</span> <span class="w">b</span><span class="cm">,</span> <span class="i">SvIV</span><span class="s">(</span><span class="w">svb</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>	<span class="w">FREETMPS</span><span class="sc">;</span></li><li>	<span class="w">LEAVE</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>To be able to access the two parameters that were pushed onto the stack
after they return from <i>call_pv</i> it is necessary to make a note
of their addresses--thus the two variables <code class="inline"><span class="w">sva</span></code>
 and <code class="inline"><span class="w">svb</span></code>
.</p>
<p>The reason this is necessary is that the area of the Perl stack which
held them will very likely have been overwritten by something else by
the time control returns from <i>call_pv</i>.</p>
<a name="Using-G_EVAL"></a><h2>Using G_EVAL</h2>
<p>Now an example using G_EVAL. Below is a Perl subroutine which computes
the difference of its 2 parameters. If this would result in a negative
result, the subroutine calls <i>die</i>.</p>
<pre class="verbatim"><ol><li><a name="Subtract"></a>    sub <span class="m">Subtract</span></li><li>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$a</span><span class="cm">,</span> <span class="i">$b</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;death can be fatal\n&quot;</span> if <span class="i">$a</span> &lt; <span class="i">$b</span><span class="sc">;</span></li><li></li><li>        <span class="i">$a</span> - <span class="i">$b</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>and some C to call it</p>
<pre class="verbatim"><ol><li> <span class="w">static</span> <span class="w">void</span></li><li> <span class="i">call_Subtract</span><span class="s">(</span><span class="w">a</span><span class="cm">,</span> <span class="w">b</span><span class="s">)</span></li><li> <a class="l_k" href="functions/int.html">int</a> <span class="w">a</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/int.html">int</a> <span class="w">b</span><span class="sc">;</span></li><li> <span class="s">{</span></li><li>     <span class="w">dSP</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/int.html">int</a> <span class="w">count</span><span class="sc">;</span></li><li>     <span class="w">SV</span> *<span class="w">err_tmp</span><span class="sc">;</span></li><li></li><li>     <span class="w">ENTER</span><span class="sc">;</span></li><li>     <span class="w">SAVETMPS</span><span class="sc">;</span></li><li></li><li>     <span class="i">PUSHMARK</span><span class="s">(</span><span class="w">SP</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">EXTEND</span><span class="s">(</span><span class="w">SP</span><span class="cm">,</span> <span class="n">2</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">a</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">b</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="w">PUTBACK</span><span class="sc">;</span></li><li></li><li>     <span class="w">count</span> = <span class="i">call_pv</span><span class="s">(</span><span class="q">&quot;Subtract&quot;</span><span class="cm">,</span> <span class="w">G_EVAL</span>|<span class="w">G_SCALAR</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>     <span class="w">SPAGAIN</span><span class="sc">;</span></li><li></li><li>     <span class="q">/* Check the eval first */</span></li><li>     <span class="w">err_tmp</span> = <span class="w">ERRSV</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="i">SvTRUE</span><span class="s">(</span><span class="w">err_tmp</span><span class="s">)</span><span class="s">)</span></li><li>     <span class="s">{</span></li><li>         <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;Uh oh - %s\n&quot;</span><span class="cm">,</span> <span class="i">SvPV_nolen</span><span class="s">(</span><span class="w">err_tmp</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>         <span class="w">POPs</span><span class="sc">;</span></li><li>     <span class="s">}</span></li><li>     <a class="l_k" href="functions/else.html">else</a></li><li>     <span class="s">{</span></li><li>       <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="w">count</span> != <span class="n">1</span><span class="s">)</span></li><li>        <span class="i">croak</span><span class="s">(</span><span class="q">&quot;call_Subtract: wanted 1 value from &#39;Subtract&#39;, got %d\n&quot;</span><span class="cm">,</span></li><li>              <span class="w">count</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>         <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;%d - %d = %d\n&quot;</span><span class="cm">,</span> <span class="w">a</span><span class="cm">,</span> <span class="w">b</span><span class="cm">,</span> <span class="w">POPi</span><span class="s">)</span><span class="sc">;</span></li><li>     <span class="s">}</span></li><li></li><li>     <span class="w">PUTBACK</span><span class="sc">;</span></li><li>     <span class="w">FREETMPS</span><span class="sc">;</span></li><li>     <span class="w">LEAVE</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>If <i>call_Subtract</i> is called thus</p>
<pre class="verbatim"><ol><li>    <span class="i">call_Subtract</span><span class="s">(</span><span class="n">4</span><span class="cm">,</span> <span class="n">5</span><span class="s">)</span></li></ol></pre><p>the following will be printed</p>
<pre class="verbatim"><ol><li>    <span class="w">Uh</span> <span class="w">oh</span> - <span class="w">death</span> <span class="w">can</span> <span class="w">be</span> <span class="w">fatal</span></li></ol></pre><p>Notes</p>
<dl>
<dt>1.</dt><dd>
<p>We want to be able to catch the <i>die</i> so we have used the G_EVAL
flag.  Not specifying this flag would mean that the program would
terminate immediately at the <i>die</i> statement in the subroutine
<i>Subtract</i>.</p>
</dd>
<dt>2.</dt><dd>
<p>The code</p>
<pre class="verbatim"><ol><li>    <span class="w">err_tmp</span> = <span class="w">ERRSV</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="i">SvTRUE</span><span class="s">(</span><span class="w">err_tmp</span><span class="s">)</span><span class="s">)</span></li><li>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;Uh oh - %s\n&quot;</span><span class="cm">,</span> <span class="i">SvPV_nolen</span><span class="s">(</span><span class="w">err_tmp</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="w">POPs</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>is the direct equivalent of this bit of Perl</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Uh oh - $@\n&quot;</span> if <span class="i">$@</span><span class="sc">;</span></li></ol></pre><p><code class="inline"><span class="w">PL_errgv</span></code>
 is a perl global of type <code class="inline"><span class="w">GV</span> *</code>
 that points to the symbol
table entry containing the error.  <code class="inline"><span class="w">ERRSV</span></code>
 therefore refers to the C
equivalent of <code class="inline"><span class="i">$@</span></code>
.  We use a local temporary, <code class="inline"><span class="w">err_tmp</span></code>
, since
<code class="inline"><span class="w">ERRSV</span></code>
 is a macro that calls a function, and <code class="inline"><span class="i">SvTRUE</span><span class="s">(</span><span class="w">ERRSV</span><span class="s">)</span></code>
 would
end up calling that function multiple times.</p>
</dd>
<dt>3.</dt><dd>
<p>Note that the stack is popped using <code class="inline"><span class="w">POPs</span></code>
 in the block where
<code class="inline"><span class="i">SvTRUE</span><span class="s">(</span><span class="w">err_tmp</span><span class="s">)</span></code>
 is true.  This is necessary because whenever a
<i>call_*</i> function invoked with G_EVAL|G_SCALAR returns an error,
the top of the stack holds the value <i>undef</i>. Because we want the
program to continue after detecting this error, it is essential that
the stack be tidied up by removing the <i>undef</i>.</p>
</dd>
</dl>
<a name="Using-G_KEEPERR"></a><h2>Using G_KEEPERR</h2>
<p>Consider this rather facetious example, where we have used an XS
version of the call_Subtract example above inside a destructor:</p>
<pre class="verbatim"><ol><li><a name="package-Foo"></a>    package <span class="i">Foo</span><span class="sc">;</span></li><li><a name="new"></a>    sub <span class="m">new</span> <span class="s">{</span> <a class="l_k" href="functions/bless.html">bless</a> <span class="s">{</span><span class="s">}</span><span class="cm">,</span> <span class="i">$_</span>[<span class="n">0</span>] <span class="s">}</span></li><li><a name="Subtract"></a>    sub <span class="m">Subtract</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$a</span><span class="cm">,</span><span class="i">$b</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;death can be fatal&quot;</span> if <span class="i">$a</span> &lt; <span class="i">$b</span><span class="sc">;</span></li><li>        <span class="i">$a</span> - <span class="i">$b</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li><a name="DESTROY"></a>    sub <span class="m">DESTROY</span> <span class="s">{</span> <span class="i">call_Subtract</span><span class="s">(</span><span class="n">5</span><span class="cm">,</span> <span class="n">4</span><span class="s">)</span><span class="sc">;</span> <span class="s">}</span></li><li><a name="foo"></a>    sub <span class="m">foo</span> <span class="s">{</span> <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;foo dies&quot;</span><span class="sc">;</span> <span class="s">}</span></li><li></li><li><a name="package-main"></a>    package <span class="i">main</span><span class="sc">;</span></li><li>    <span class="s">{</span></li><li>	<a class="l_k" href="functions/my.html">my</a> <span class="i">$foo</span> = <span class="w">Foo</span><span class="w">-&gt;new</span><span class="sc">;</span></li><li>	<a class="l_k" href="functions/eval.html">eval</a> <span class="s">{</span> <span class="i">$foo</span><span class="i">-&gt;foo</span> <span class="s">}</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Saw: $@&quot;</span> if <span class="i">$@</span><span class="sc">;</span>             <span class="c"># should be, but isn&#39;t</span></li></ol></pre><p>This example will fail to recognize that an error occurred inside the
<code class="inline"><a class="l_k" href="functions/eval.html">eval</a> <span class="s">{</span><span class="s">}</span></code>
.  Here's why: the call_Subtract code got executed while perl
was cleaning up temporaries when exiting the outer braced block, and because
call_Subtract is implemented with <i>call_pv</i> using the G_EVAL
flag, it promptly reset <code class="inline"><span class="i">$@</span></code>
.  This results in the failure of the
outermost test for <code class="inline"><span class="i">$@</span></code>
, and thereby the failure of the error trap.</p>
<p>Appending the G_KEEPERR flag, so that the <i>call_pv</i> call in
call_Subtract reads:</p>
<pre class="verbatim"><ol><li>        <span class="w">count</span> = <span class="i">call_pv</span><span class="s">(</span><span class="q">&quot;Subtract&quot;</span><span class="cm">,</span> <span class="w">G_EVAL</span>|<span class="w">G_SCALAR</span>|<span class="w">G_KEEPERR</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>will preserve the error and restore reliable error handling.</p>
<a name="Using-call_sv"></a><h2>Using call_sv</h2>
<p>In all the previous examples I have 'hard-wired' the name of the Perl
subroutine to be called from C.  Most of the time though, it is more
convenient to be able to specify the name of the Perl subroutine from
within the Perl script, and you'll want to use
<a href="perlapi.html#call_sv">call_sv</a>.</p>
<p>Consider the Perl code below</p>
<pre class="verbatim"><ol><li><a name="fred"></a>    sub <span class="m">fred</span></li><li>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Hello there\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li></li><li>    <span class="i">CallSubPV</span><span class="s">(</span><span class="q">&quot;fred&quot;</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Here is a snippet of XSUB which defines <i>CallSubPV</i>.</p>
<pre class="verbatim"><ol><li>    void</li><li>    CallSubPV(name)</li><li>    	char *	name</li><li>    	CODE:</li><li>	PUSHMARK(SP);</li><li>	call_pv(name, G_DISCARD|G_NOARGS);</li></ol></pre><p>That is fine as far as it goes. The thing is, the Perl subroutine
can be specified as only a string, however, Perl allows references
to subroutines and anonymous subroutines.
This is where <i>call_sv</i> is useful.</p>
<p>The code below for <i>CallSubSV</i> is identical to <i>CallSubPV</i> except
that the <code class="inline"><span class="w">name</span></code>
 parameter is now defined as an SV* and we use
<i>call_sv</i> instead of <i>call_pv</i>.</p>
<pre class="verbatim"><ol><li>    void</li><li>    CallSubSV(name)</li><li>    	SV *	name</li><li>    	CODE:</li><li>	PUSHMARK(SP);</li><li>	call_sv(name, G_DISCARD|G_NOARGS);</li></ol></pre><p>Because we are using an SV to call <i>fred</i> the following can all be used:</p>
<pre class="verbatim"><ol><li>    <span class="i">CallSubSV</span><span class="s">(</span><span class="q">&quot;fred&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">CallSubSV</span><span class="s">(</span>\<span class="i">&amp;fred</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$ref</span> = \<span class="i">&amp;fred</span><span class="sc">;</span></li><li>    <span class="i">CallSubSV</span><span class="s">(</span><span class="i">$ref</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">CallSubSV</span><span class="s">(</span> <a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Hello there\n&quot;</span> <span class="s">}</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>As you can see, <i>call_sv</i> gives you much greater flexibility in
how you can specify the Perl subroutine.</p>
<p>You should note that, if it is necessary to store the SV (<code class="inline"><span class="w">name</span></code>
 in the
example above) which corresponds to the Perl subroutine so that it can
be used later in the program, it not enough just to store a copy of the
pointer to the SV. Say the code above had been like this:</p>
<pre class="verbatim"><ol><li>    static SV * rememberSub;</li><li></li><li>    void</li><li>    SaveSub1(name)</li><li>    	SV *	name</li><li>    	CODE:</li><li>	rememberSub = name;</li><li></li><li>    void</li><li>    CallSavedSub1()</li><li>    	CODE:</li><li>	PUSHMARK(SP);</li><li>	call_sv(rememberSub, G_DISCARD|G_NOARGS);</li></ol></pre><p>The reason this is wrong is that, by the time you come to use the
pointer <code class="inline"><span class="w">rememberSub</span></code>
 in <code class="inline"><span class="w">CallSavedSub1</span></code>
, it may or may not still refer
to the Perl subroutine that was recorded in <code class="inline"><span class="w">SaveSub1</span></code>
.  This is
particularly true for these cases:</p>
<pre class="verbatim"><ol><li>    <span class="i">SaveSub1</span><span class="s">(</span>\<span class="i">&amp;fred</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">CallSavedSub1</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="i">SaveSub1</span><span class="s">(</span> <a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Hello there\n&quot;</span> <span class="s">}</span> <span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">CallSavedSub1</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>By the time each of the <code class="inline"><span class="w">SaveSub1</span></code>
 statements above has been executed,
the SV*s which corresponded to the parameters will no longer exist.
Expect an error message from Perl of the form</p>
<pre class="verbatim"><ol><li>    <span class="w">Can&#39;t</span> <a class="l_k" href="functions/use.html">use</a> <span class="w">an</span> <span class="w">undefined</span> <span class="w">value</span> <span class="w">as</span> <span class="w">a</span> <span class="w">subroutine</span> <span class="w">reference</span> <span class="w">at</span> ...</li></ol></pre><p>for each of the <code class="inline"><span class="w">CallSavedSub1</span></code>
 lines.</p>
<p>Similarly, with this code</p>
<pre class="verbatim"><ol><li>    <span class="i">$ref</span> = \<span class="i">&amp;fred</span><span class="sc">;</span></li><li>    <span class="i">SaveSub1</span><span class="s">(</span><span class="i">$ref</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$ref</span> = <span class="n">47</span><span class="sc">;</span></li><li>    <span class="i">CallSavedSub1</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>you can expect one of these messages (which you actually get is dependent on
the version of Perl you are using)</p>
<pre class="verbatim"><ol><li>    Not a CODE reference at ...</li><li>    Undefined subroutine &amp;main::47 called ...</li></ol></pre><p>The variable $ref may have referred to the subroutine <code class="inline"><span class="w">fred</span></code>

whenever the call to <code class="inline"><span class="w">SaveSub1</span></code>
 was made but by the time
<code class="inline"><span class="w">CallSavedSub1</span></code>
 gets called it now holds the number <code class="inline"><span class="n">47</span></code>
. Because we
saved only a pointer to the original SV in <code class="inline"><span class="w">SaveSub1</span></code>
, any changes to
$ref will be tracked by the pointer <code class="inline"><span class="w">rememberSub</span></code>
. This means that
whenever <code class="inline"><span class="w">CallSavedSub1</span></code>
 gets called, it will attempt to execute the
code which is referenced by the SV* <code class="inline"><span class="w">rememberSub</span></code>
.  In this case
though, it now refers to the integer <code class="inline"><span class="n">47</span></code>
, so expect Perl to complain
loudly.</p>
<p>A similar but more subtle problem is illustrated with this code:</p>
<pre class="verbatim"><ol><li>    <span class="i">$ref</span> = \<span class="i">&amp;fred</span><span class="sc">;</span></li><li>    <span class="i">SaveSub1</span><span class="s">(</span><span class="i">$ref</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$ref</span> = \<span class="i">&amp;joe</span><span class="sc">;</span></li><li>    <span class="i">CallSavedSub1</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>This time whenever <code class="inline"><span class="w">CallSavedSub1</span></code>
 gets called it will execute the Perl
subroutine <code class="inline"><span class="w">joe</span></code>
 (assuming it exists) rather than <code class="inline"><span class="w">fred</span></code>
 as was
originally requested in the call to <code class="inline"><span class="w">SaveSub1</span></code>
.</p>
<p>To get around these problems it is necessary to take a full copy of the
SV.  The code below shows <code class="inline"><span class="w">SaveSub2</span></code>
 modified to do that.</p>
<pre class="verbatim"><ol><li>    <span class="q">/* this isn&#39;t thread-safe */</span></li><li>    <span class="w">static</span> <span class="w">SV</span> * <span class="w">keepSub</span> = <span class="s">(</span><span class="w">SV</span>*<span class="s">)</span><span class="w">NULL</span><span class="sc">;</span></li><li></li><li>    <span class="w">void</span></li><li>    <span class="i">SaveSub2</span><span class="s">(</span><span class="w">name</span><span class="s">)</span></li><li>        <span class="w">SV</span> *	<span class="w">name</span></li><li>    	<span class="w">CODE</span><span class="co">:</span></li><li>     	<span class="q">/* Take a copy of the callback */</span></li><li>    	<a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="w">keepSub</span> == <span class="s">(</span><span class="w">SV</span>*<span class="s">)</span><span class="w">NULL</span><span class="s">)</span></li><li>    	    /<span class="i">* First</span> <a class="l_k" href="functions/time.html">time</a><span class="cm">,</span> <span class="w">so</span> <span class="w">create</span> <span class="w">a</span> <span class="w">new</span> <span class="w">SV</span> *<span class="q">/</span></li><li>	    <span class="q">	    keepSub = newSVsv(name);</span></li><li>    	<span class="q">    	else</span></li><li>    	    <span class="q">    	    /</span>* <span class="w">Been</span> <span class="w">here</span> <span class="w">before</span><span class="cm">,</span> <span class="w">so</span> <span class="w">overwrite</span> *<span class="q">/</span></li><li>	    <span class="q">	    SvSetSV(keepSub, name);</span></li><li></li><li>    <span class="q">    void</span></li><li>    <span class="q">    CallSavedSub2()</span></li><li>    	<span class="q">    	CODE:</span></li><li>	<span class="q">	PUSHMARK(SP);</span></li><li>	<span class="q">	call_sv(keepSub, G_DISCARD|G_NOARGS);</span></li></ol></pre><p>To avoid creating a new SV every time <code class="inline"><span class="w">SaveSub2</span></code>
 is called,
the function first checks to see if it has been called before.  If not,
then space for a new SV is allocated and the reference to the Perl
subroutine <code class="inline"><span class="w">name</span></code>
 is copied to the variable <code class="inline"><span class="w">keepSub</span></code>
 in one
operation using <code class="inline"><span class="w">newSVsv</span></code>
.  Thereafter, whenever <code class="inline"><span class="w">SaveSub2</span></code>
 is called,
the existing SV, <code class="inline"><span class="w">keepSub</span></code>
, is overwritten with the new value using
<code class="inline"><span class="w">SvSetSV</span></code>
.</p>
<p>Note: using a static or global variable to store the SV isn't
thread-safe.  You can either use the <code class="inline"><span class="w">MY_CXT</span></code>
 mechanism documented in
<a href="perlxs.html#Safely-Storing-Static-Data-in-XS">Safely Storing Static Data in XS in perlxs</a> which is fast, or store the
values in perl global variables, using get_sv(), which is much slower.</p>
<a name="Using-call_argv"></a><h2>Using call_argv</h2>
<p>Here is a Perl subroutine which prints whatever parameters are passed
to it.</p>
<pre class="verbatim"><ol><li><a name="PrintList"></a>    sub <span class="m">PrintList</span></li><li>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">@list</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li></li><li>        foreach <span class="s">(</span><span class="i">@list</span><span class="s">)</span> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;$_\n&quot;</span> <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><p>And here is an example of <i>call_argv</i> which will call
<i>PrintList</i>.</p>
<pre class="verbatim"><ol><li>    <span class="w">static</span> <span class="w">char</span> * <span class="w">words</span><span class="s">[</span><span class="s">]</span> = <span class="s">{</span><span class="q">&quot;alpha&quot;</span><span class="cm">,</span> <span class="q">&quot;beta&quot;</span><span class="cm">,</span> <span class="q">&quot;gamma&quot;</span><span class="cm">,</span> <span class="q">&quot;delta&quot;</span><span class="cm">,</span> <span class="w">NULL</span><span class="s">}</span><span class="sc">;</span></li><li></li><li>    <span class="w">static</span> <span class="w">void</span></li><li>    <span class="i">call_PrintList</span><span class="s">(</span><span class="s">)</span></li><li>    <span class="s">{</span></li><li>        <span class="i">call_argv</span><span class="s">(</span><span class="q">&quot;PrintList&quot;</span><span class="cm">,</span> <span class="w">G_DISCARD</span><span class="cm">,</span> <span class="w">words</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>Note that it is not necessary to call <code class="inline"><span class="w">PUSHMARK</span></code>
 in this instance.
This is because <i>call_argv</i> will do it for you.</p>
<a name="Using-call_method"></a><h2>Using call_method</h2>
<p>Consider the following Perl code:</p>
<pre class="verbatim"><ol><li>    <span class="s">{</span></li><li><a name="package-Mine"></a>        package <span class="i">Mine</span><span class="sc">;</span></li><li></li><li><a name="new"></a>        sub <span class="m">new</span></li><li>        <span class="s">{</span></li><li>            <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$type</span><span class="s">)</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="sc">;</span></li><li>            <a class="l_k" href="functions/bless.html">bless</a> <span class="s">[</span><span class="i">@_</span><span class="s">]</span></li><li>        <span class="s">}</span></li><li></li><li><a name="Display"></a>        sub <span class="m">Display</span></li><li>        <span class="s">{</span></li><li>            <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$self</span><span class="cm">,</span> <span class="i">$index</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;$index: $$self[$index]\n&quot;</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li></li><li><a name="PrintID"></a>        sub <span class="m">PrintID</span></li><li>        <span class="s">{</span></li><li>            <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$class</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;This is Class $class version 1.0\n&quot;</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li><a name="package-main"></a>    <span class="s">}</span></li></ol></pre><p>It implements just a very simple class to manage an array.  Apart from
the constructor, <code class="inline"><span class="w">new</span></code>
, it declares methods, one static and one
virtual. The static method, <code class="inline"><span class="w">PrintID</span></code>
, prints out simply the class
name and a version number. The virtual method, <code class="inline"><span class="w">Display</span></code>
, prints out a
single element of the array.  Here is an all-Perl example of using it.</p>
<pre class="verbatim"><ol><li>    <span class="i">$a</span> = <span class="w">Mine</span><span class="w">-&gt;new</span><span class="s">(</span><span class="q">&#39;red&#39;</span><span class="cm">,</span> <span class="q">&#39;green&#39;</span><span class="cm">,</span> <span class="q">&#39;blue&#39;</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$a</span><span class="i">-&gt;Display</span><span class="s">(</span><span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="w">Mine</span><span class="w">-&gt;PrintID</span><span class="sc">;</span></li></ol></pre><p>will print</p>
<pre class="verbatim"><ol><li>    1: green</li><li>    This is Class Mine version 1.0</li></ol></pre><p>Calling a Perl method from C is fairly straightforward. The following
things are required:</p>
<ul>
<li>
<p>A reference to the object for a virtual method or the name of the class
for a static method</p>
</li>
<li>
<p>The name of the method</p>
</li>
<li>
<p>Any other parameters specific to the method</p>
</li>
</ul>
<p>Here is a simple XSUB which illustrates the mechanics of calling both
the <code class="inline"><span class="w">PrintID</span></code>
 and <code class="inline"><span class="w">Display</span></code>
 methods from C.</p>
<pre class="verbatim"><ol><li>    <span class="w">void</span></li><li>    <span class="i">call_Method</span><span class="s">(</span><a class="l_k" href="functions/ref.html">ref</a><span class="cm">,</span> <span class="w">method</span><span class="cm">,</span> <a class="l_k" href="functions/index.html">index</a><span class="s">)</span></li><li>        <span class="w">SV</span> *	<a class="l_k" href="functions/ref.html">ref</a></li><li>        <span class="w">char</span> *	<span class="w">method</span></li><li>        <a class="l_k" href="functions/int.html">int</a>		<a class="l_k" href="functions/index.html">index</a></li><li>        <span class="w">CODE</span><span class="co">:</span></li><li>        <span class="i">PUSHMARK</span><span class="s">(</span><span class="w">SP</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">EXTEND</span><span class="s">(</span><span class="w">SP</span><span class="cm">,</span> <span class="n">2</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><a class="l_k" href="functions/ref.html">ref</a><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><a class="l_k" href="functions/index.html">index</a><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="w">PUTBACK</span><span class="sc">;</span></li><li></li><li>        <span class="i">call_method</span><span class="s">(</span><span class="w">method</span><span class="cm">,</span> <span class="w">G_DISCARD</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="w">void</span></li><li>    <span class="i">call_PrintID</span><span class="s">(</span><span class="w">class</span><span class="cm">,</span> <span class="w">method</span><span class="s">)</span></li><li>        <span class="w">char</span> *	<span class="w">class</span></li><li>        <span class="w">char</span> *	<span class="w">method</span></li><li>        <span class="w">CODE</span><span class="co">:</span></li><li>        <span class="i">PUSHMARK</span><span class="s">(</span><span class="w">SP</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">XPUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSVpv</span><span class="s">(</span><span class="w">class</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="w">PUTBACK</span><span class="sc">;</span></li><li></li><li>        <span class="i">call_method</span><span class="s">(</span><span class="w">method</span><span class="cm">,</span> <span class="w">G_DISCARD</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>So the methods <code class="inline"><span class="w">PrintID</span></code>
 and <code class="inline"><span class="w">Display</span></code>
 can be invoked like this:</p>
<pre class="verbatim"><ol><li>    <span class="i">$a</span> = <span class="w">Mine</span><span class="w">-&gt;new</span><span class="s">(</span><span class="q">&#39;red&#39;</span><span class="cm">,</span> <span class="q">&#39;green&#39;</span><span class="cm">,</span> <span class="q">&#39;blue&#39;</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">call_Method</span><span class="s">(</span><span class="i">$a</span><span class="cm">,</span> <span class="q">&#39;Display&#39;</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">call_PrintID</span><span class="s">(</span><span class="q">&#39;Mine&#39;</span><span class="cm">,</span> <span class="q">&#39;PrintID&#39;</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The only thing to note is that, in both the static and virtual methods,
the method name is not passed via the stack--it is used as the first
parameter to <i>call_method</i>.</p>
<a name="Using-GIMME_V"></a><h2>Using GIMME_V</h2>
<p>Here is a trivial XSUB which prints the context in which it is
currently executing.</p>
<pre class="verbatim"><ol><li>    <span class="w">void</span></li><li>    <span class="i">PrintContext</span><span class="s">(</span><span class="s">)</span></li><li>        <span class="w">CODE</span><span class="co">:</span></li><li>        <span class="w">U8</span> <span class="w">gimme</span> = <span class="w">GIMME_V</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="w">gimme</span> == <span class="w">G_VOID</span><span class="s">)</span></li><li>            <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;Context is Void\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>        <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">gimme</span> == <span class="w">G_SCALAR</span><span class="s">)</span></li><li>            <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;Context is Scalar\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/else.html">else</a></li><li>            <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;Context is Array\n&quot;</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>And here is some Perl to test it.</p>
<pre class="verbatim"><ol><li>    <span class="w">PrintContext</span><span class="sc">;</span></li><li>    <span class="i">$a</span> = <span class="w">PrintContext</span><span class="sc">;</span></li><li>    <span class="i">@a</span> = <span class="w">PrintContext</span><span class="sc">;</span></li></ol></pre><p>The output from that will be</p>
<pre class="verbatim"><ol><li>    <span class="w">Context</span> <span class="w">is</span> <span class="w">Void</span></li><li>    <span class="w">Context</span> <span class="w">is</span> <span class="w">Scalar</span></li><li>    <span class="w">Context</span> <span class="w">is</span> <span class="w">Array</span></li></ol></pre><a name="Using-Perl-to-Dispose-of-Temporaries"></a><h2>Using Perl to Dispose of Temporaries</h2>
<p>In the examples given to date, any temporaries created in the callback
(i.e., parameters passed on the stack to the <i>call_*</i> function or
values returned via the stack) have been freed by one of these methods:</p>
<ul>
<li>
<p>Specifying the G_DISCARD flag with <i>call_*</i></p>
</li>
<li>
<p>Explicitly using the <code class="inline"><span class="w">ENTER</span></code>
/<code class="inline"><span class="w">SAVETMPS</span></code>
--<code class="inline"><span class="w">FREETMPS</span></code>
/<code class="inline"><span class="w">LEAVE</span></code>
 pairing</p>
</li>
</ul>
<p>There is another method which can be used, namely letting Perl do it
for you automatically whenever it regains control after the callback
has terminated.  This is done by simply not using the</p>
<pre class="verbatim"><ol><li>    <span class="w">ENTER</span><span class="sc">;</span></li><li>    <span class="w">SAVETMPS</span><span class="sc">;</span></li><li>    ...</li><li>    <span class="w">FREETMPS</span><span class="sc">;</span></li><li>    <span class="w">LEAVE</span><span class="sc">;</span></li></ol></pre><p>sequence in the callback (and not, of course, specifying the G_DISCARD
flag).</p>
<p>If you are going to use this method you have to be aware of a possible
memory leak which can arise under very specific circumstances.  To
explain these circumstances you need to know a bit about the flow of
control between Perl and the callback routine.</p>
<p>The examples given at the start of the document (an error handler and
an event driven program) are typical of the two main sorts of flow
control that you are likely to encounter with callbacks.  There is a
very important distinction between them, so pay attention.</p>
<p>In the first example, an error handler, the flow of control could be as
follows.  You have created an interface to an external library.
Control can reach the external library like this</p>
<pre class="verbatim"><ol><li>    <span class="w">perl</span> --&gt; <span class="w">XSUB</span> --&gt; <span class="w">external</span> <span class="w">library</span></li></ol></pre><p>Whilst control is in the library, an error condition occurs. You have
previously set up a Perl callback to handle this situation, so it will
get executed. Once the callback has finished, control will drop back to
Perl again.  Here is what the flow of control will be like in that
situation</p>
<pre class="verbatim"><ol><li>    perl --&gt; XSUB --&gt; external library</li><li>                      ...</li><li>                      error occurs</li><li>                      ...</li><li>                      external library --&gt; call_* --&gt; perl</li><li>                                                          |</li><li>    perl &lt;-- XSUB &lt;-- external library &lt;-- call_* &lt;----+</li></ol></pre><p>After processing of the error using <i>call_*</i> is completed,
control reverts back to Perl more or less immediately.</p>
<p>In the diagram, the further right you go the more deeply nested the
scope is.  It is only when control is back with perl on the extreme
left of the diagram that you will have dropped back to the enclosing
scope and any temporaries you have left hanging around will be freed.</p>
<p>In the second example, an event driven program, the flow of control
will be more like this</p>
<pre class="verbatim"><ol><li>    perl --&gt; XSUB --&gt; event handler</li><li>                      ...</li><li>                      event handler --&gt; call_* --&gt; perl</li><li>                                                       |</li><li>                      event handler &lt;-- call_* &lt;----+</li><li>                      ...</li><li>                      event handler --&gt; call_* --&gt; perl</li><li>                                                       |</li><li>                      event handler &lt;-- call_* &lt;----+</li><li>                      ...</li><li>                      event handler --&gt; call_* --&gt; perl</li><li>                                                       |</li><li>                      event handler &lt;-- call_* &lt;----+</li></ol></pre><p>In this case the flow of control can consist of only the repeated
sequence</p>
<pre class="verbatim"><ol><li>    event handler --&gt; call_* --&gt; perl</li></ol></pre><p>for practically the complete duration of the program.  This means that
control may <i>never</i> drop back to the surrounding scope in Perl at the
extreme left.</p>
<p>So what is the big problem? Well, if you are expecting Perl to tidy up
those temporaries for you, you might be in for a long wait.  For Perl
to dispose of your temporaries, control must drop back to the
enclosing scope at some stage.  In the event driven scenario that may
never happen.  This means that, as time goes on, your program will
create more and more temporaries, none of which will ever be freed. As
each of these temporaries consumes some memory your program will
eventually consume all the available memory in your system--kapow!</p>
<p>So here is the bottom line--if you are sure that control will revert
back to the enclosing Perl scope fairly quickly after the end of your
callback, then it isn't absolutely necessary to dispose explicitly of
any temporaries you may have created. Mind you, if you are at all
uncertain about what to do, it doesn't do any harm to tidy up anyway.</p>
<a name="Strategies-for-Storing-Callback-Context-Information"></a><h2>Strategies for Storing Callback Context Information</h2>
<p>Potentially one of the trickiest problems to overcome when designing a
callback interface can be figuring out how to store the mapping between
the C callback function and the Perl equivalent.</p>
<p>To help understand why this can be a real problem first consider how a
callback is set up in an all C environment.  Typically a C API will
provide a function to register a callback.  This will expect a pointer
to a function as one of its parameters.  Below is a call to a
hypothetical function <code class="inline"><span class="w">register_fatal</span></code>
 which registers the C function
to get called when a fatal error occurs.</p>
<pre class="verbatim"><ol><li>    <span class="i">register_fatal</span><span class="s">(</span><span class="w">cb1</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The single parameter <code class="inline"><span class="w">cb1</span></code>
 is a pointer to a function, so you must
have defined <code class="inline"><span class="w">cb1</span></code>
 in your code, say something like this</p>
<pre class="verbatim"><ol><li>    static void</li><li>    cb1()</li><li>    {</li><li>        printf ("Fatal Error\n");</li><li>        exit(1);</li><li>    }</li></ol></pre><p>Now change that to call a Perl subroutine instead</p>
<pre class="verbatim"><ol><li>    static SV * callback = (SV*)NULL;</li><li></li><li>    static void</li><li>    cb1()</li><li>    {</li><li>        dSP;</li><li></li><li>        PUSHMARK(SP);</li><li></li><li>        /* Call the Perl sub to process the callback */</li><li>        call_sv(callback, G_DISCARD);</li><li>    }</li><li></li><li></li><li>    void</li><li>    register_fatal(fn)</li><li>        SV *	fn</li><li>        CODE:</li><li>        /* Remember the Perl sub */</li><li>        if (callback == (SV*)NULL)</li><li>            callback = newSVsv(fn);</li><li>        else</li><li>            SvSetSV(callback, fn);</li><li></li><li>        /* register the callback with the external library */</li><li>        register_fatal(cb1);</li></ol></pre><p>where the Perl equivalent of <code class="inline"><span class="w">register_fatal</span></code>
 and the callback it
registers, <code class="inline"><span class="w">pcb1</span></code>
, might look like this</p>
<pre class="verbatim"><ol><li>    <span class="c"># Register the sub pcb1</span></li><li>    <span class="i">register_fatal</span><span class="s">(</span>\<span class="i">&amp;pcb1</span><span class="s">)</span><span class="sc">;</span></li><li></li><li><a name="pcb1"></a>    sub <span class="m">pcb1</span></li><li>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/die.html">die</a> <span class="q">&quot;I&#39;m dying...\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>The mapping between the C callback and the Perl equivalent is stored in
the global variable <code class="inline"><span class="w">callback</span></code>
.</p>
<p>This will be adequate if you ever need to have only one callback
registered at any time. An example could be an error handler like the
code sketched out above. Remember though, repeated calls to
<code class="inline"><span class="w">register_fatal</span></code>
 will replace the previously registered callback
function with the new one.</p>
<p>Say for example you want to interface to a library which allows asynchronous
file i/o.  In this case you may be able to register a callback whenever
a read operation has completed. To be of any use we want to be able to
call separate Perl subroutines for each file that is opened.  As it
stands, the error handler example above would not be adequate as it
allows only a single callback to be defined at any time. What we
require is a means of storing the mapping between the opened file and
the Perl subroutine we want to be called for that file.</p>
<p>Say the i/o library has a function <code class="inline"><span class="w">asynch_read</span></code>
 which associates a C
function <code class="inline"><span class="w">ProcessRead</span></code>
 with a file handle <code class="inline"><span class="w">fh</span></code>
--this assumes that it
has also provided some routine to open the file and so obtain the file
handle.</p>
<pre class="verbatim"><ol><li>    <span class="i">asynch_read</span><span class="s">(</span><span class="w">fh</span><span class="cm">,</span> <span class="w">ProcessRead</span><span class="s">)</span></li></ol></pre><p>This may expect the C <i>ProcessRead</i> function of this form</p>
<pre class="verbatim"><ol><li>    <span class="w">void</span></li><li>    <span class="i">ProcessRead</span><span class="s">(</span><span class="w">fh</span><span class="cm">,</span> <span class="w">buffer</span><span class="s">)</span></li><li>    <a class="l_k" href="functions/int.html">int</a>	<span class="w">fh</span><span class="sc">;</span></li><li>    <span class="w">char</span> *	<span class="w">buffer</span><span class="sc">;</span></li><li>    <span class="s">{</span></li><li>         ...</li><li>    <span class="s">}</span></li></ol></pre><p>To provide a Perl interface to this library we need to be able to map
between the <code class="inline"><span class="w">fh</span></code>
 parameter and the Perl subroutine we want called.  A
hash is a convenient mechanism for storing this mapping.  The code
below shows a possible implementation</p>
<pre class="verbatim"><ol><li>    static HV * Mapping = (HV*)NULL;</li><li></li><li>    void</li><li>    asynch_read(fh, callback)</li><li>        int	fh</li><li>        SV *	callback</li><li>        CODE:</li><li>        /* If the hash doesn't already exist, create it */</li><li>        if (Mapping == (HV*)NULL)</li><li>            Mapping = newHV();</li><li></li><li>        /* Save the fh -&gt; callback mapping */</li><li>        hv_store(Mapping, (char*)&amp;fh, sizeof(fh), newSVsv(callback), 0);</li><li></li><li>        /* Register with the C Library */</li><li>        asynch_read(fh, asynch_read_if);</li></ol></pre><p>and <code class="inline"><span class="w">asynch_read_if</span></code>
 could look like this</p>
<pre class="verbatim"><ol><li>    <span class="w">static</span> <span class="w">void</span></li><li>    <span class="i">asynch_read_if</span><span class="s">(</span><span class="w">fh</span><span class="cm">,</span> <span class="w">buffer</span><span class="s">)</span></li><li>    <a class="l_k" href="functions/int.html">int</a>	<span class="w">fh</span><span class="sc">;</span></li><li>    <span class="w">char</span> *	<span class="w">buffer</span><span class="sc">;</span></li><li>    <span class="s">{</span></li><li>        <span class="w">dSP</span><span class="sc">;</span></li><li>        <span class="w">SV</span> ** <span class="w">sv</span><span class="sc">;</span></li><li></li><li>        <span class="q">/* Get the callback associated with fh */</span></li><li>        <span class="w">sv</span> =  <span class="i">hv_fetch</span><span class="s">(</span><span class="w">Mapping</span><span class="cm">,</span> <span class="s">(</span><span class="w">char</span>*<span class="s">)</span>&amp;<span class="w">fh</span> <span class="cm">,</span> <span class="i">sizeof</span><span class="s">(</span><span class="w">fh</span><span class="s">)</span><span class="cm">,</span> <span class="w">FALSE</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">sv</span> == <span class="s">(</span><span class="w">SV</span>**<span class="s">)</span><span class="w">NULL</span><span class="s">)</span></li><li>            <span class="i">croak</span><span class="s">(</span><span class="q">&quot;Internal error...\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <span class="i">PUSHMARK</span><span class="s">(</span><span class="w">SP</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">EXTEND</span><span class="s">(</span><span class="w">SP</span><span class="cm">,</span> <span class="n">2</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">fh</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSVpv</span><span class="s">(</span><span class="w">buffer</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="w">PUTBACK</span><span class="sc">;</span></li><li></li><li>        <span class="q">/* Call the Perl sub */</span></li><li>        <span class="i">call_sv</span><span class="s">(</span><span class="i">*sv</span><span class="cm">,</span> <span class="w">G_DISCARD</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>For completeness, here is <code class="inline"><span class="w">asynch_close</span></code>
.  This shows how to remove
the entry from the hash <code class="inline"><span class="w">Mapping</span></code>
.</p>
<pre class="verbatim"><ol><li>    void</li><li>    asynch_close(fh)</li><li>        int	fh</li><li>        CODE:</li><li>        /* Remove the entry from the hash */</li><li>        (void) hv_delete(Mapping, (char*)&amp;fh, sizeof(fh), G_DISCARD);</li><li></li><li>        /* Now call the real asynch_close */</li><li>        asynch_close(fh);</li></ol></pre><p>So the Perl interface would look like this</p>
<pre class="verbatim"><ol><li><a name="callback1"></a>    sub <span class="m">callback1</span></li><li>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$handle</span><span class="cm">,</span> <span class="i">$buffer</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li></li><li>    <span class="c"># Register the Perl callback</span></li><li>    <span class="i">asynch_read</span><span class="s">(</span><span class="i">$fh</span><span class="cm">,</span> \<span class="i">&amp;callback1</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="i">asynch_close</span><span class="s">(</span><span class="i">$fh</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The mapping between the C callback and Perl is stored in the global
hash <code class="inline"><span class="w">Mapping</span></code>
 this time. Using a hash has the distinct advantage that
it allows an unlimited number of callbacks to be registered.</p>
<p>What if the interface provided by the C callback doesn't contain a
parameter which allows the file handle to Perl subroutine mapping?  Say
in the asynchronous i/o package, the callback function gets passed only
the <code class="inline"><span class="w">buffer</span></code>
 parameter like this</p>
<pre class="verbatim"><ol><li>    void</li><li>    ProcessRead(buffer)</li><li>    char *	buffer;</li><li>    {</li><li>        ...</li><li>    }</li></ol></pre><p>Without the file handle there is no straightforward way to map from the
C callback to the Perl subroutine.</p>
<p>In this case a possible way around this problem is to predefine a
series of C functions to act as the interface to Perl, thus</p>
<pre class="verbatim"><ol><li>    #define MAX_CB		3</li><li>    #define NULL_HANDLE	-1</li><li>    typedef void (*FnMap)();</li><li></li><li>    struct MapStruct {</li><li>        FnMap    Function;</li><li>        SV *     PerlSub;</li><li>        int      Handle;</li><li>      };</li><li></li><li>    static void  fn1();</li><li>    static void  fn2();</li><li>    static void  fn3();</li><li></li><li>    static struct MapStruct Map [MAX_CB] =</li><li>        {</li><li>            { fn1, NULL, NULL_HANDLE },</li><li>            { fn2, NULL, NULL_HANDLE },</li><li>            { fn3, NULL, NULL_HANDLE }</li><li>        };</li><li></li><li>    static void</li><li>    Pcb(index, buffer)</li><li>    int index;</li><li>    char * buffer;</li><li>    {</li><li>        dSP;</li><li></li><li>        PUSHMARK(SP);</li><li>        XPUSHs(sv_2mortal(newSVpv(buffer, 0)));</li><li>        PUTBACK;</li><li></li><li>        /* Call the Perl sub */</li><li>        call_sv(Map[index].PerlSub, G_DISCARD);</li><li>    }</li><li></li><li>    static void</li><li>    fn1(buffer)</li><li>    char * buffer;</li><li>    {</li><li>        Pcb(0, buffer);</li><li>    }</li><li></li><li>    static void</li><li>    fn2(buffer)</li><li>    char * buffer;</li><li>    {</li><li>        Pcb(1, buffer);</li><li>    }</li><li></li><li>    static void</li><li>    fn3(buffer)</li><li>    char * buffer;</li><li>    {</li><li>        Pcb(2, buffer);</li><li>    }</li><li></li><li>    void</li><li>    array_asynch_read(fh, callback)</li><li>        int		fh</li><li>        SV *	callback</li><li>        CODE:</li><li>        int index;</li><li>        int null_index = MAX_CB;</li><li></li><li>        /* Find the same handle or an empty entry */</li><li>        for (index = 0; index &lt; MAX_CB; ++index)</li><li>        {</li><li>            if (Map[index].Handle == fh)</li><li>                break;</li><li></li><li>            if (Map[index].Handle == NULL_HANDLE)</li><li>                null_index = index;</li><li>        }</li><li></li><li>        if (index == MAX_CB &amp;&amp; null_index == MAX_CB)</li><li>            croak ("Too many callback functions registered\n");</li><li></li><li>        if (index == MAX_CB)</li><li>            index = null_index;</li><li></li><li>        /* Save the file handle */</li><li>        Map[index].Handle = fh;</li><li></li><li>        /* Remember the Perl sub */</li><li>        if (Map[index].PerlSub == (SV*)NULL)</li><li>            Map[index].PerlSub = newSVsv(callback);</li><li>        else</li><li>            SvSetSV(Map[index].PerlSub, callback);</li><li></li><li>        asynch_read(fh, Map[index].Function);</li><li></li><li>    void</li><li>    array_asynch_close(fh)</li><li>        int	fh</li><li>        CODE:</li><li>        int index;</li><li></li><li>        /* Find the file handle */</li><li>        for (index = 0; index &lt; MAX_CB; ++ index)</li><li>            if (Map[index].Handle == fh)</li><li>                break;</li><li></li><li>        if (index == MAX_CB)</li><li>            croak ("could not close fh %d\n", fh);</li><li></li><li>        Map[index].Handle = NULL_HANDLE;</li><li>        SvREFCNT_dec(Map[index].PerlSub);</li><li>        Map[index].PerlSub = (SV*)NULL;</li><li></li><li>        asynch_close(fh);</li></ol></pre><p>In this case the functions <code class="inline"><span class="w">fn1</span></code>
, <code class="inline"><span class="w">fn2</span></code>
, and <code class="inline"><span class="w">fn3</span></code>
 are used to
remember the Perl subroutine to be called. Each of the functions holds
a separate hard-wired index which is used in the function <code class="inline"><span class="w">Pcb</span></code>
 to
access the <code class="inline"><span class="w">Map</span></code>
 array and actually call the Perl subroutine.</p>
<p>There are some obvious disadvantages with this technique.</p>
<p>Firstly, the code is considerably more complex than with the previous
example.</p>
<p>Secondly, there is a hard-wired limit (in this case 3) to the number of
callbacks that can exist simultaneously. The only way to increase the
limit is by modifying the code to add more functions and then
recompiling.  None the less, as long as the number of functions is
chosen with some care, it is still a workable solution and in some
cases is the only one available.</p>
<p>To summarize, here are a number of possible methods for you to consider
for storing the mapping between C and the Perl callback</p>
<dl>
<dt>1. </dt><dd><a name="1.-Ignore-the-problem---Allow-only-1-callback"></a><b>Ignore the problem - Allow only 1 callback</b>
<p>For a lot of situations, like interfacing to an error handler, this may
be a perfectly adequate solution.</p>
</dd>
<dt>2. </dt><dd><a name="2.-Create-a-sequence-of-callbacks---hard-wired-limit"></a><b>Create a sequence of callbacks - hard wired limit</b>
<p>If it is impossible to tell from the parameters passed back from the C
callback what the context is, then you may need to create a sequence of C
callback interface functions, and store pointers to each in an array.</p>
</dd>
<dt>3. </dt><dd><a name="3.-Use-a-parameter-to-map-to-the-Perl-callback"></a><b>Use a parameter to map to the Perl callback</b>
<p>A hash is an ideal mechanism to store the mapping between C and Perl.</p>
</dd>
</dl>
<a name="Alternate-Stack-Manipulation"></a><h2>Alternate Stack Manipulation</h2>
<p>Although I have made use of only the <code class="inline"><span class="w">POP</span>*</code>
 macros to access values
returned from Perl subroutines, it is also possible to bypass these
macros and read the stack using the <code class="inline"><span class="w">ST</span></code>
 macro (See <a href="perlxs.html">perlxs</a> for a
full description of the <code class="inline"><span class="w">ST</span></code>
 macro).</p>
<p>Most of the time the <code class="inline"><span class="w">POP</span>*</code>
 macros should be adequate; the main
problem with them is that they force you to process the returned values
in sequence. This may not be the most suitable way to process the
values in some cases. What we want is to be able to access the stack in
a random order. The <code class="inline"><span class="w">ST</span></code>
 macro as used when coding an XSUB is ideal
for this purpose.</p>
<p>The code below is the example given in the section <a href="#Returning-a-List-of-Values">Returning a List of Values</a> recoded to use <code class="inline"><span class="w">ST</span></code>
 instead of <code class="inline"><span class="w">POP</span>*</code>
.</p>
<pre class="verbatim"><ol><li>    <span class="w">static</span> <span class="w">void</span></li><li>    <span class="i">call_AddSubtract2</span><span class="s">(</span><span class="w">a</span><span class="cm">,</span> <span class="w">b</span><span class="s">)</span></li><li>    <a class="l_k" href="functions/int.html">int</a> <span class="w">a</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/int.html">int</a> <span class="w">b</span><span class="sc">;</span></li><li>    <span class="s">{</span></li><li>        <span class="w">dSP</span><span class="sc">;</span></li><li>        <span class="w">I32</span> <span class="w">ax</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/int.html">int</a> <span class="w">count</span><span class="sc">;</span></li><li></li><li>        <span class="w">ENTER</span><span class="sc">;</span></li><li>        <span class="w">SAVETMPS</span><span class="sc">;</span></li><li></li><li>        <span class="i">PUSHMARK</span><span class="s">(</span><span class="w">SP</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">EXTEND</span><span class="s">(</span><span class="w">SP</span><span class="cm">,</span> <span class="n">2</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">a</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">PUSHs</span><span class="s">(</span><span class="i">sv_2mortal</span><span class="s">(</span><span class="i">newSViv</span><span class="s">(</span><span class="w">b</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="w">PUTBACK</span><span class="sc">;</span></li><li></li><li>        <span class="w">count</span> = <span class="i">call_pv</span><span class="s">(</span><span class="q">&quot;AddSubtract&quot;</span><span class="cm">,</span> <span class="w">G_ARRAY</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <span class="w">SPAGAIN</span><span class="sc">;</span></li><li>        <span class="w">SP</span> -= <span class="w">count</span><span class="sc">;</span></li><li>        <span class="w">ax</span> = <span class="s">(</span><span class="w">SP</span> - <span class="w">PL_stack_base</span><span class="s">)</span> + <span class="n">1</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="w">count</span> != <span class="n">2</span><span class="s">)</span></li><li>            <span class="i">croak</span><span class="s">(</span><span class="q">&quot;Big trouble\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;%d + %d = %d\n&quot;</span><span class="cm">,</span> <span class="w">a</span><span class="cm">,</span> <span class="w">b</span><span class="cm">,</span> <span class="i">SvIV</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="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/printf.html">printf</a> <span class="s">(</span><span class="q">&quot;%d - %d = %d\n&quot;</span><span class="cm">,</span> <span class="w">a</span><span class="cm">,</span> <span class="w">b</span><span class="cm">,</span> <span class="i">SvIV</span><span class="s">(</span><span class="i">ST</span><span class="s">(</span><span class="n">1</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>        <span class="w">PUTBACK</span><span class="sc">;</span></li><li>        <span class="w">FREETMPS</span><span class="sc">;</span></li><li>        <span class="w">LEAVE</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>Notes</p>
<dl>
<dt>1.</dt><dd>
<p>Notice that it was necessary to define the variable <code class="inline"><span class="w">ax</span></code>
.  This is
because the <code class="inline"><span class="w">ST</span></code>
 macro expects it to exist.  If we were in an XSUB it
would not be necessary to define <code class="inline"><span class="w">ax</span></code>
 as it is already defined for
us.</p>
</dd>
<dt>2.</dt><dd>
<p>The code</p>
<pre class="verbatim"><ol><li>        <span class="w">SPAGAIN</span><span class="sc">;</span></li><li>        <span class="w">SP</span> -= <span class="w">count</span><span class="sc">;</span></li><li>        <span class="w">ax</span> = <span class="s">(</span><span class="w">SP</span> - <span class="w">PL_stack_base</span><span class="s">)</span> + <span class="n">1</span><span class="sc">;</span></li></ol></pre><p>sets the stack up so that we can use the <code class="inline"><span class="w">ST</span></code>
 macro.</p>
</dd>
<dt>3.</dt><dd>
<p>Unlike the original coding of this example, the returned
values are not accessed in reverse order.  So <code class="inline"><span class="i">ST</span><span class="s">(</span><span class="n">0</span><span class="s">)</span></code>
 refers to the
first value returned by the Perl subroutine and <code class="inline"><span class="i">ST</span><span class="s">(</span><span class="w">count</span>-<span class="n">1</span><span class="s">)</span></code>

refers to the last.</p>
</dd>
</dl>
<a name="Creating-and-Calling-an-Anonymous-Subroutine-in-C"></a><h2>Creating and Calling an Anonymous Subroutine in C</h2>
<p>As we've already shown, <code class="inline"><span class="w">call_sv</span></code>
 can be used to invoke an
anonymous subroutine.  However, our example showed a Perl script
invoking an XSUB to perform this operation.  Let's see how it can be
done inside our C code:</p>
<pre class="verbatim"><ol><li> ...</li><li></li><li> <span class="w">SV</span> *<span class="w">cvrv</span></li><li>    = <span class="i">eval_pv</span><span class="s">(</span><span class="q">&quot;sub {</span></li><li>                <span class="q">                print &#39;You will not find me cluttering any namespace!&#39;</span></li><li>               <span class="q">               }&quot;</span><span class="cm">,</span> <span class="w">TRUE</span><span class="s">)</span><span class="sc">;</span></li><li></li><li> ...</li><li></li><li> <span class="i">call_sv</span><span class="s">(</span><span class="w">cvrv</span><span class="cm">,</span> <span class="w">G_VOID</span>|<span class="w">G_NOARGS</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p><code class="inline"><span class="w">eval_pv</span></code>
 is used to compile the anonymous subroutine, which
will be the return value as well (read more about <code class="inline"><span class="w">eval_pv</span></code>
 in
<a href="perlapi.html#eval_pv">eval_pv in perlapi</a>).  Once this code reference is in hand, it
can be mixed in with all the previous examples we've shown.</p>
<a name="LIGHTWEIGHT-CALLBACKS"></a><h1>LIGHTWEIGHT CALLBACKS</h1>
<p>Sometimes you need to invoke the same subroutine repeatedly.
This usually happens with a function that acts on a list of
values, such as Perl's built-in sort(). You can pass a
comparison function to sort(), which will then be invoked
for every pair of values that needs to be compared. The first()
and reduce() functions from <a href="List/Util.html">List::Util</a> follow a similar
pattern.</p>
<p>In this case it is possible to speed up the routine (often
quite substantially) by using the lightweight callback API.
The idea is that the calling context only needs to be
created and destroyed once, and the sub can be called
arbitrarily many times in between.</p>
<p>It is usual to pass parameters using global variables (typically
$_ for one parameter, or $a and $b for two parameters) rather
than via @_. (It is possible to use the @_ mechanism if you know
what you're doing, though there is as yet no supported API for
it. It's also inherently slower.)</p>
<p>The pattern of macro calls is like this:</p>
<pre class="verbatim"><ol><li>    <span class="w">dMULTICALL</span><span class="sc">;</span>			<span class="q">/* Declare local variables */</span></li><li>    <span class="w">U8</span> <span class="w">gimme</span> = <span class="w">G_SCALAR</span><span class="sc">;</span>	<span class="q">/* context of the call: G_SCALAR,</span></li><li>				 <span class="q">				 * G_ARRAY, or G_VOID */</span></li><li></li><li>    <span class="i">PUSH_MULTICALL</span><span class="s">(</span><span class="w">cv</span><span class="s">)</span><span class="sc">;</span>		<span class="q">/* Set up the context for calling cv,</span></li><li>				   <span class="q">				   and set local vars appropriately */</span></li><li></li><li>    /<span class="i">* loop</span> *<span class="q">/ {</span></li><li>        <span class="q">        /</span>* <span class="w">set</span> <span class="w">the</span> <span class="i">value</span><span class="s">(</span><span class="q">s) af your parameter variables */</span></li><li>        <span class="q">        MULTICALL;		/* Make the actual call */</span></li><li>    <span class="q">    } /* end of loop */</span></li><li></li><li>    <span class="q">    POP_MULTICALL;		/* Tear down the calling context */</span></li></ol></pre><p>For some concrete examples, see the implementation of the
first() and reduce() functions of List::Util 1.18. There you
will also find a header file that emulates the multicall API
on older versions of perl.</p>
<a name="SEE-ALSO"></a><h1>SEE ALSO</h1>
<p><a href="perlxs.html">perlxs</a>, <a href="perlguts.html">perlguts</a>, <a href="perlembed.html">perlembed</a></p>
<a name="AUTHOR"></a><h1>AUTHOR</h1>
<p>Paul Marquess</p>
<p>Special thanks to the following people who assisted in the creation of
the document.</p>
<p>Jeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem, Gurusamy Sarathy
and Larry Wall.</p>
<a name="DATE"></a><h1>DATE</h1>
<p>Last updated for perl 5.23.1.</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="#THE-CALL_-FUNCTIONS">THE CALL_ FUNCTIONS</a><li><a href="#FLAG-VALUES">FLAG VALUES</a><ul><li><a href="#G_VOID">G_VOID</a><li><a href="#G_SCALAR">G_SCALAR</a><li><a href="#G_ARRAY">G_ARRAY</a><li><a href="#G_DISCARD">G_DISCARD</a><li><a href="#G_NOARGS">G_NOARGS</a><li><a href="#G_EVAL">G_EVAL</a><li><a href="#G_KEEPERR">G_KEEPERR</a><li><a href="#Determining-the-Context">Determining the Context</a></ul><li><a href="#EXAMPLES">EXAMPLES</a><ul><li><a href="#No-Parameters%2c-Nothing-Returned">No Parameters, Nothing Returned</a><li><a href="#Passing-Parameters">Passing Parameters</a><li><a href="#Returning-a-Scalar">Returning a Scalar</a><li><a href="#Returning-a-List-of-Values">Returning a List of Values</a><li><a href="#Returning-a-List-in-Scalar-Context">Returning a List in Scalar Context</a><li><a href="#Returning-Data-from-Perl-via-the-Parameter-List">Returning Data from Perl via the Parameter List</a><li><a href="#Using-G_EVAL">Using G_EVAL</a><li><a href="#Using-G_KEEPERR">Using G_KEEPERR</a><li><a href="#Using-call_sv">Using call_sv</a><li><a href="#Using-call_argv">Using call_argv</a><li><a href="#Using-call_method">Using call_method</a><li><a href="#Using-GIMME_V">Using GIMME_V</a><li><a href="#Using-Perl-to-Dispose-of-Temporaries">Using Perl to Dispose of Temporaries</a><li><a href="#Strategies-for-Storing-Callback-Context-Information">Strategies for Storing Callback Context Information</a><li><a href="#Alternate-Stack-Manipulation">Alternate Stack Manipulation</a><li><a href="#Creating-and-Calling-an-Anonymous-Subroutine-in-C">Creating and Calling an Anonymous Subroutine in C</a></ul><li><a href="#LIGHTWEIGHT-CALLBACKS">LIGHTWEIGHT CALLBACKS</a><li><a href="#SEE-ALSO">SEE ALSO</a><li><a href="#AUTHOR">AUTHOR</a><li><a href="#DATE">DATE</a></ul>
    </div>
    <div id="page_index_footer" class="hud_footer">
      <div id="page_index_bottomleft" class="hud_bottomleft"></div>
      <div id="page_index_bottom" class="hud_bottom"><span class="hud_span_bottom"></span></div>
      <div id="page_index_resize" class="hud_resize"></div>
    </div>
  </div>


	    &nbsp;
          </div>
          <div id="content_footer">
          </div>
        </div>
        <div class="clear"></div>
      </div>
      
    <div id="footer">
      <div id="footer_content">
        <div id="footer_strapline">
          perldoc.perl.org - Official documentation for the Perl programming language
        </div>
        <div id="footer_links">
          <div id="address">
            <p class="name">Contact details</p>
            <p class="address">
	      Site maintained by <a href="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    = 'perlcall';
  perldoc.pageAddress = 'perlcall.html';
  perldoc.contentPage = 1;
  explorePerl.render();
  explorePerl.addEvents('explore_anchor');
</script>
    
  </body>
</html>