This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
This is my patch patch.1m for perl5.001.
[perl5.git] / pod / perlapi.pod
CommitLineData
a0d0e21e
LW
1=head1 NAME
2
3perlapi - Perl 5 application programming interface for C extensions
4
5=head1 DESCRIPTION
6
7=head2 Introduction
8
9XS is a language used to create an extension interface
10between Perl and some C library which one wishes to use with
11Perl. The XS interface is combined with the library to
12create a new library which can be linked to Perl. An B<XSUB>
13is a function in the XS language and is the core component
14of the Perl application interface.
15
16The XS compiler is called B<xsubpp>. This compiler will embed
17the constructs necessary to let an XSUB, which is really a C
18function in disguise, manipulate Perl values and creates the
19glue necessary to let Perl access the XSUB. The compiler
20uses B<typemaps> to determine how to map C function parameters
21and variables to Perl values. The default typemap handles
22many common C types. A supplement typemap must be created
23to handle special structures and types for the library being
24linked.
25
26Many of the examples which follow will concentrate on creating an
27interface between Perl and the ONC+RPC bind library functions.
28Specifically, the rpcb_gettime() function will be used to demonstrate many
29features of the XS language. This function has two parameters; the first
30is an input parameter and the second is an output parameter. The function
31also returns a status value.
32
33 bool_t rpcb_gettime(const char *host, time_t *timep);
34
35From C this function will be called with the following
36statements.
37
38 #include <rpc/rpc.h>
39 bool_t status;
40 time_t timep;
41 status = rpcb_gettime( "localhost", &timep );
42
43If an XSUB is created to offer a direct translation between this function
44and Perl, then this XSUB will be used from Perl with the following code.
45The $status and $timep variables will contain the output of the function.
46
47 use RPC;
48 $status = rpcb_gettime( "localhost", $timep );
49
50The following XS file shows an XS subroutine, or XSUB, which
51demonstrates one possible interface to the rpcb_gettime()
52function. This XSUB represents a direct translation between
53C and Perl and so preserves the interface even from Perl.
54This XSUB will be invoked from Perl with the usage shown
55above. Note that the first three #include statements, for
56C<EXTERN.h>, C<perl.h>, and C<XSUB.h>, will always be present at the
57beginning of an XS file. This approach and others will be
58expanded later in this document.
59
60 #include "EXTERN.h"
61 #include "perl.h"
62 #include "XSUB.h"
63 #include <rpc/rpc.h>
64
65 MODULE = RPC PACKAGE = RPC
66
67 bool_t
68 rpcb_gettime(host,timep)
69 char * host
70 time_t &timep
71 OUTPUT:
72 timep
73
74Any extension to Perl, including those containing XSUBs,
75should have a Perl module to serve as the bootstrap which
76pulls the extension into Perl. This module will export the
77extension's functions and variables to the Perl program and
78will cause the extension's XSUBs to be linked into Perl.
79The following module will be used for most of the examples
80in this document and should be used from Perl with the C<use>
81command as shown earlier. Perl modules are explained in
82more detail later in this document.
83
84 package RPC;
85
86 require Exporter;
87 require DynaLoader;
88 @ISA = qw(Exporter DynaLoader);
89 @EXPORT = qw( rpcb_gettime );
90
91 bootstrap RPC;
92 1;
93
94Throughout this document a variety of interfaces to the rpcb_gettime()
95XSUB will be explored. The XSUBs will take their parameters in different
96orders or will take different numbers of parameters. In each case the
97XSUB is an abstraction between Perl and the real C rpcb_gettime()
98function, and the XSUB must always ensure that the real rpcb_gettime()
99function is called with the correct parameters. This abstraction will
100allow the programmer to create a more Perl-like interface to the C
101function.
102
d1b91892
AD
103It is recommended that the B<h2xs> tool be used when creating new
104extensions. This tool will generate template source files and Makefiles.
105This is discussed in more detail in the section titled "Creating A New
106Extension" and in the B<h2xs> manpage.
107
a0d0e21e
LW
108=head2 The Anatomy of an XSUB
109
110The following XSUB allows a Perl program to access a C library function called sin(). The XSUB will imitate the C
111function which takes a single argument and returns a single
112value.
113
114 double
115 sin(x)
116 double<tab>x
117
118The compiler expects a tab between the parameter name and its type, and
119any or no whitespace before the type. When using C pointers the
120indirection operator C<*> should be considered part of the type and the
121address operator C<&> should be considered part of the variable, as is
122demonstrated in the rpcb_gettime() function above. See the section on
123typemaps for more about handling qualifiers and unary operators in C
124types.
125
126The parameter list of a function must not have whitespace
127after the open-parenthesis or before the close-parenthesis.
128
129 INCORRECT CORRECT
130
131 double double
132 sin( x ) sin(x)
133 double x double x
134
135The function name and the return type must be placed on
136separate lines.
137
138 INCORRECT CORRECT
139
140 double sin(x) double
141 double x sin(x)
142 double x
143
144=head2 The Argument Stack
145
146The argument stack is used to store the values which are
147sent as parameters to the XSUB and to store the XSUB's
148return value. In reality all Perl functions keep their
149values on this stack at the same time, each limited to its
150own range of positions on the stack. In this document the
151first position on that stack which belongs to the active
152function will be referred to as position 0 for that function.
153
154XSUBs refer to their stack arguments with the macro B<ST(x)>, where I<x> refers
155to a position in this XSUB's part of the stack. Position 0 for that
156function would be known to the XSUB as ST(0). The XSUB's incoming
157parameters and outgoing return values always begin at ST(0). For many
158simple cases the B<xsubpp> compiler will generate the code necessary to
159handle the argument stack by embedding code fragments found in the
160typemaps. In more complex cases the programmer must supply the code.
161
162=head2 The RETVAL Variable
163
164The RETVAL variable is a magic variable which always matches
165the return type of the C library function. The B<xsubpp> compiler will
166supply this variable in each XSUB and by default will use it to hold the
167return value of the C library function being called. In simple cases the
168value of RETVAL will be placed in ST(0) of the argument stack where it can
169be received by Perl as the return value of the XSUB.
170
171If the XSUB has a return type of C<void> then the compiler will
172not supply a RETVAL variable for that function. When using
173the PPCODE: directive the RETVAL variable may not be needed.
174
175=head2 The MODULE Keyword
176
177The MODULE keyword is used to start the XS code and to
178specify the package of the functions which are being
179defined. All text preceding the first MODULE keyword is
180considered C code and is passed through to the output
181untouched. Every XS module will have a bootstrap function
182which is used to hook the XSUBs into Perl. The package name
183of this bootstrap function will match the value of the last
184MODULE statement in the XS source files. The value of
185MODULE should always remain constant within the same XS
186file, though this is not required.
187
188The following example will start the XS code and will place
189all functions in a package named RPC.
190
191 MODULE = RPC
192
193=head2 The PACKAGE Keyword
194
195When functions within an XS source file must be separated into packages
196the PACKAGE keyword should be used. This keyword is used with the MODULE
197keyword and must follow immediately after it when used.
198
199 MODULE = RPC PACKAGE = RPC
200
201 [ XS code in package RPC ]
202
203 MODULE = RPC PACKAGE = RPCB
204
205 [ XS code in package RPCB ]
206
207 MODULE = RPC PACKAGE = RPC
208
209 [ XS code in package RPC ]
210
211Although this keyword is optional and in some cases provides redundant
212information it should always be used. This keyword will ensure that the
213XSUBs appear in the desired package.
214
215=head2 The PREFIX Keyword
216
217The PREFIX keyword designates prefixes which should be
218removed from the Perl function names. If the C function is
219C<rpcb_gettime()> and the PREFIX value is C<rpcb_> then Perl will
220see this function as C<gettime()>.
221
222This keyword should follow the PACKAGE keyword when used.
223If PACKAGE is not used then PREFIX should follow the MODULE
224keyword.
225
226 MODULE = RPC PREFIX = rpc_
227
228 MODULE = RPC PACKAGE = RPCB PREFIX = rpcb_
229
230=head2 The OUTPUT: Keyword
231
232The OUTPUT: keyword indicates that certain function parameters should be
233updated (new values made visible to Perl) when the XSUB terminates or that
234certain values should be returned to the calling Perl function. For
235simple functions, such as the sin() function above, the RETVAL variable is
236automatically designated as an output value. In more complex functions
237the B<xsubpp> compiler will need help to determine which variables are output
238variables.
239
240This keyword will normally be used to complement the CODE: keyword.
241The RETVAL variable is not recognized as an output variable when the
242CODE: keyword is present. The OUTPUT: keyword is used in this
243situation to tell the compiler that RETVAL really is an output
244variable.
245
246The OUTPUT: keyword can also be used to indicate that function parameters
247are output variables. This may be necessary when a parameter has been
248modified within the function and the programmer would like the update to
249be seen by Perl. If function parameters are listed under OUTPUT: along
250with the RETVAL variable then the RETVAL variable must be the last one
251listed.
252
253 bool_t
254 rpcb_gettime(host,timep)
255 char * host
256 time_t &timep
257 OUTPUT:
258 timep
259
260The OUTPUT: keyword will also allow an output parameter to
261be mapped to a matching piece of code rather than to a
262typemap.
263
264 bool_t
265 rpcb_gettime(host,timep)
266 char * host
267 time_t &timep
268 OUTPUT:
269 timep<tab>sv_setnv(ST(1), (double)timep);
270
271=head2 The CODE: Keyword
272
273This keyword is used in more complicated XSUBs which require
274special handling for the C function. The RETVAL variable is
275available but will not be returned unless it is specified
276under the OUTPUT: keyword.
277
278The following XSUB is for a C function which requires special handling of
279its parameters. The Perl usage is given first.
280
281 $status = rpcb_gettime( "localhost", $timep );
282
283The XSUB follows.
284
d1b91892
AD
285 bool_t
286 rpcb_gettime(host,timep)
a0d0e21e
LW
287 char * host
288 time_t timep
289 CODE:
290 RETVAL = rpcb_gettime( host, &timep );
291 OUTPUT:
292 timep
293 RETVAL
294
295In many of the examples shown here the CODE: block (and
296other blocks) will often be contained within braces ( C<{> and
297C<}> ). This protects the CODE: block from complex INPUT
298typemaps and ensures the resulting C code is legal.
299
300=head2 The NO_INIT Keyword
301
302The NO_INIT keyword is used to indicate that a function
d1b91892 303parameter is being used as only an output value. The B<xsubpp>
a0d0e21e
LW
304compiler will normally generate code to read the values of
305all function parameters from the argument stack and assign
306them to C variables upon entry to the function. NO_INIT
307will tell the compiler that some parameters will be used for
308output rather than for input and that they will be handled
309before the function terminates.
310
311The following example shows a variation of the rpcb_gettime() function.
d1b91892 312This function uses the timep variable as only an output variable and does
a0d0e21e
LW
313not care about its initial contents.
314
315 bool_t
316 rpcb_gettime(host,timep)
317 char * host
318 time_t &timep = NO_INIT
319 OUTPUT:
320 timep
321
322=head2 Initializing Function Parameters
323
324Function parameters are normally initialized with their
325values from the argument stack. The typemaps contain the
326code segments which are used to transfer the Perl values to
327the C parameters. The programmer, however, is allowed to
328override the typemaps and supply alternate initialization
329code.
330
331The following code demonstrates how to supply initialization code for
332function parameters. The initialization code is eval'd by the compiler
333before it is added to the output so anything which should be interpreted
334literally, such as double quotes, must be protected with backslashes.
335
336 bool_t
337 rpcb_gettime(host,timep)
338 char * host = (char *)SvPV(ST(0),na);
339 time_t &timep = 0;
340 OUTPUT:
341 timep
342
343This should not be used to supply default values for parameters. One
344would normally use this when a function parameter must be processed by
345another library function before it can be used. Default parameters are
346covered in the next section.
347
348=head2 Default Parameter Values
349
350Default values can be specified for function parameters by
351placing an assignment statement in the parameter list. The
352default value may be a number or a string. Defaults should
353always be used on the right-most parameters only.
354
355To allow the XSUB for rpcb_gettime() to have a default host
356value the parameters to the XSUB could be rearranged. The
357XSUB will then call the real rpcb_gettime() function with
358the parameters in the correct order. Perl will call this
359XSUB with either of the following statements.
360
361 $status = rpcb_gettime( $timep, $host );
362
363 $status = rpcb_gettime( $timep );
364
365The XSUB will look like the code which follows. A CODE:
366block is used to call the real rpcb_gettime() function with
367the parameters in the correct order for that function.
368
369 bool_t
370 rpcb_gettime(timep,host="localhost")
371 char * host
372 time_t timep = NO_INIT
373 CODE:
374 RETVAL = rpcb_gettime( host, &timep );
375 OUTPUT:
376 timep
377 RETVAL
378
379=head2 Variable-length Parameter Lists
380
381XSUBs can have variable-length parameter lists by specifying an ellipsis
382C<(...)> in the parameter list. This use of the ellipsis is similar to that
383found in ANSI C. The programmer is able to determine the number of
384arguments passed to the XSUB by examining the C<items> variable which the
385B<xsubpp> compiler supplies for all XSUBs. By using this mechanism one can
386create an XSUB which accepts a list of parameters of unknown length.
387
388The I<host> parameter for the rpcb_gettime() XSUB can be
389optional so the ellipsis can be used to indicate that the
390XSUB will take a variable number of parameters. Perl should
d1b91892 391be able to call this XSUB with either of the following statements.
a0d0e21e
LW
392
393 $status = rpcb_gettime( $timep, $host );
394
395 $status = rpcb_gettime( $timep );
396
397The XS code, with ellipsis, follows.
398
399 bool_t
400 rpcb_gettime(timep, ...)
401 time_t timep = NO_INIT
402 CODE:
403 {
404 char *host = "localhost";
405
406 if( items > 1 )
407 host = (char *)SvPV(ST(1), na);
408 RETVAL = rpcb_gettime( host, &timep );
409 }
410 OUTPUT:
411 timep
412 RETVAL
413
414=head2 The PPCODE: Keyword
415
416The PPCODE: keyword is an alternate form of the CODE: keyword and is used
417to tell the B<xsubpp> compiler that the programmer is supplying the code to
d1b91892 418control the argument stack for the XSUBs return values. Occasionally one
a0d0e21e
LW
419will want an XSUB to return a list of values rather than a single value.
420In these cases one must use PPCODE: and then explicitly push the list of
421values on the stack. The PPCODE: and CODE: keywords are not used
422together within the same XSUB.
423
424The following XSUB will call the C rpcb_gettime() function
425and will return its two output values, timep and status, to
426Perl as a single list.
427
d1b91892
AD
428 void
429 rpcb_gettime(host)
a0d0e21e
LW
430 char * host
431 PPCODE:
432 {
433 time_t timep;
434 bool_t status;
435 status = rpcb_gettime( host, &timep );
436 EXTEND(sp, 2);
437 PUSHs(sv_2mortal(newSVnv(status)));
438 PUSHs(sv_2mortal(newSVnv(timep)));
439 }
440
441Notice that the programmer must supply the C code necessary
442to have the real rpcb_gettime() function called and to have
443the return values properly placed on the argument stack.
444
445The C<void> return type for this function tells the B<xsubpp> compiler that
446the RETVAL variable is not needed or used and that it should not be created.
447In most scenarios the void return type should be used with the PPCODE:
448directive.
449
450The EXTEND() macro is used to make room on the argument
451stack for 2 return values. The PPCODE: directive causes the
452B<xsubpp> compiler to create a stack pointer called C<sp>, and it
453is this pointer which is being used in the EXTEND() macro.
454The values are then pushed onto the stack with the PUSHs()
455macro.
456
457Now the rpcb_gettime() function can be used from Perl with
458the following statement.
459
460 ($status, $timep) = rpcb_gettime("localhost");
461
462=head2 Returning Undef And Empty Lists
463
d1b91892 464Occasionally the programmer will want to simply return
a0d0e21e
LW
465C<undef> or an empty list if a function fails rather than a
466separate status value. The rpcb_gettime() function offers
467just this situation. If the function succeeds we would like
468to have it return the time and if it fails we would like to
469have undef returned. In the following Perl code the value
470of $timep will either be undef or it will be a valid time.
471
472 $timep = rpcb_gettime( "localhost" );
473
474The following XSUB uses the C<void> return type to disable the generation of
475the RETVAL variable and uses a CODE: block to indicate to the compiler
476that the programmer has supplied all the necessary code. The
477sv_newmortal() call will initialize the return value to undef, making that
478the default return value.
479
480 void
481 rpcb_gettime(host)
482 char * host
483 CODE:
484 {
485 time_t timep;
486 bool_t x;
487 ST(0) = sv_newmortal();
488 if( rpcb_gettime( host, &timep ) )
489 sv_setnv( ST(0), (double)timep);
490 }
491
492The next example demonstrates how one would place an explicit undef in the
493return value, should the need arise.
494
495 void
496 rpcb_gettime(host)
497 char * host
498 CODE:
499 {
500 time_t timep;
501 bool_t x;
502 ST(0) = sv_newmortal();
503 if( rpcb_gettime( host, &timep ) ){
504 sv_setnv( ST(0), (double)timep);
505 }
506 else{
507 ST(0) = &sv_undef;
508 }
509 }
510
511To return an empty list one must use a PPCODE: block and
512then not push return values on the stack.
513
514 void
515 rpcb_gettime(host)
516 char * host
517 PPCODE:
518 {
519 time_t timep;
520 if( rpcb_gettime( host, &timep ) )
521 PUSHs(sv_2mortal(newSVnv(timep)));
522 else{
523 /* Nothing pushed on stack, so an empty */
524 /* list is implicitly returned. */
525 }
526 }
527
528=head2 The CLEANUP: Keyword
529
530This keyword can be used when an XSUB requires special cleanup procedures
531before it terminates. When the CLEANUP: keyword is used it must follow
532any CODE:, PPCODE:, or OUTPUT: blocks which are present in the XSUB. The
533code specified for the cleanup block will be added as the last statements
534in the XSUB.
535
536=head2 The BOOT: Keyword
537
538The BOOT: keyword is used to add code to the extension's bootstrap
539function. The bootstrap function is generated by the B<xsubpp> compiler and
540normally holds the statements necessary to register any XSUBs with Perl.
541With the BOOT: keyword the programmer can tell the compiler to add extra
542statements to the bootstrap function.
543
544This keyword may be used any time after the first MODULE keyword and should
545appear on a line by itself. The first blank line after the keyword will
546terminate the code block.
547
548 BOOT:
549 # The following message will be printed when the
550 # bootstrap function executes.
551 printf("Hello from the bootstrap!\n");
552
553=head2 Inserting Comments and C Preprocessor Directives
554
555Comments and C preprocessor directives are allowed within
556CODE:, PPCODE:, BOOT:, and CLEANUP: blocks. The compiler
557will pass the preprocessor directives through untouched and
558will remove the commented lines. Comments can be added to
559XSUBs by placing a C<#> at the beginning of the line. Care
560should be taken to avoid making the comment look like a C
561preprocessor directive, lest it be interpreted as such.
562
563=head2 Using XS With C++
564
565If a function is defined as a C++ method then it will assume
566its first argument is an object pointer. The object pointer
567will be stored in a variable called THIS. The object should
568have been created by C++ with the new() function and should
569be blessed by Perl with the sv_setptrobj() macro. The
570blessing of the object by Perl can be handled by the
571T_PTROBJ typemap.
572
573If the method is defined as static it will call the C++
574function using the class::method() syntax. If the method is not static
575the function will be called using the THIS->method() syntax.
576
577=head2 Perl Variables
578
579The following demonstrates how the Perl variable $host can
580be accessed from an XSUB. The function B<perl_get_sv()> is
581used to obtain a pointer to the variable, known as an B<SV>
582(Scalar Variable) internally. The package name C<RPC> will be
583added to the name of the variable so perl_get_sv() will know
584in which package $host can be found. If the package name is
585not supplied then perl_get_sv() will search package C<main> for
586the variable. The macro B<SvPVX()> is then used to dereference
587the SV to obtain a C<char*> pointer to its contents.
588
589 void
590 rpcb_gettime()
591 PPCODE:
592 {
593 char *host;
594 SV *hostsv;
595 time_t timep;
596
597 hostsv = perl_get_sv( "RPC::host", FALSE );
598 if( hostsv != NULL ){
599 host = SvPVX( hostsv );
600 if( rpcb_gettime( host, &timep ) )
601 PUSHs(sv_2mortal(newSVnv(timep)));
602 }
603 }
604
605This Perl code can be used to call that XSUB.
606
607 $RPC::host = "localhost";
608 $timep = rpcb_gettime();
609
610In the above example the SV contained a C C<char*> but a Perl
611scalar variable may also contain numbers and references. If
612the SV is expected to have a C C<int> then the macro B<SvIVX()>
613should be used to dereference the SV. When the SV contains
614a C double then B<SvNVX()> should be used.
615
616The macro B<SvRV()> can be used to dereference an SV when it is a Perl
617reference. The result will be another SV which points to the actual Perl
618variable. This can then be dereferenced with SvPVX(), SvNVX(), or
619SvIVX(). The following XSUB will use SvRV().
620
d1b91892
AD
621 void
622 rpcb_gettime()
a0d0e21e
LW
623 PPCODE:
624 {
625 char *host;
626 SV *rv;
627 SV *hostsv;
628 time_t timep;
629
630 rv = perl_get_sv( "RPC::host", FALSE );
631 if( rv != NULL ){
632 hostsv = SvRV( rv );
633 host = SvPVX( hostsv );
634 if( rpcb_gettime( host, &timep ) )
635 PUSHs(sv_2mortal(newSVnv(timep)));
636 }
637 }
638
639This Perl code will create a variable $RPC::host which is a
640reference to $MY::host. The variable $MY::host contains the
641hostname which will be used.
642
643 $MY::host = "localhost";
644 $RPC::host = \$MY::host;
645 $timep = rpcb_gettime();
646
647The second argument to perl_get_sv() will normally be B<FALSE>
648as shown in the above examples. An argument of B<TRUE> will
649cause variables to be created if they do not already exist.
650One should not use TRUE unless steps are taken to deal with
651a possibly empty SV.
652
653XSUBs may use B<perl_get_av()>, B<perl_get_hv()>, and B<perl_get_cv()> to
654access Perl arrays, hashes, and code values.
655
d1b91892 656=head2 Interface Strategy
a0d0e21e
LW
657
658When designing an interface between Perl and a C library a straight
659translation from C to XS is often sufficient. The interface will often be
660very C-like and occasionally nonintuitive, especially when the C function
661modifies one of its parameters. In cases where the programmer wishes to
662create a more Perl-like interface the following strategy may help to
663identify the more critical parts of the interface.
664
665Identify the C functions which modify their parameters. The XSUBs for
666these functions may be able to return lists to Perl, or may be
667candidates to return undef or an empty list in case of failure.
668
d1b91892 669Identify which values are used by only the C and XSUB functions
a0d0e21e
LW
670themselves. If Perl does not need to access the contents of the value
671then it may not be necessary to provide a translation for that value
672from C to Perl.
673
674Identify the pointers in the C function parameter lists and return
675values. Some pointers can be handled in XS with the & unary operator on
676the variable name while others will require the use of the * operator on
677the type name. In general it is easier to work with the & operator.
678
679Identify the structures used by the C functions. In many
680cases it may be helpful to use the T_PTROBJ typemap for
681these structures so they can be manipulated by Perl as
682blessed objects.
683
684=head2 The Perl Module
685
686The Perl module is the link between the extension library,
687which was generated from XS code, and the Perl interpreter.
688The module is used to tell Perl what the extension library
689contains. The name and package of the module should match
690the name of the library.
691
692The following is a Perl module for an extension containing
693some ONC+ RPC bind library functions.
694
695 package RPC;
696
697 require Exporter;
698 require DynaLoader;
699 @ISA = qw(Exporter DynaLoader);
700 @EXPORT = qw( rpcb_gettime rpcb_getmaps rpcb_getaddr
701 rpcb_rmtcall rpcb_set rpcb_unset );
702
703 bootstrap RPC;
704 1;
705
706The RPC extension contains the functions found in the
707@EXPORT list. By using the C<Exporter> module the RPC module
708can make these function names visible to the rest of the
709Perl program. The C<DynaLoader> module will allow the RPC
710module to bootstrap the extension library. To load this
711extension and make the functions available, the following
712Perl statement should be used.
713
714 use RPC;
715
716For more information about the DynaLoader consult its documentation in the
717ext/DynaLoader directory in the Perl source.
718
719=head2 Perl Objects And C Structures
720
721When dealing with C structures one should select either
722B<T_PTROBJ> or B<T_PTRREF> for the XS type. Both types are
723designed to handle pointers to complex objects. The
724T_PTRREF type will allow the Perl object to be unblessed
725while the T_PTROBJ type requires that the object be blessed.
726By using T_PTROBJ one can achieve a form of type-checking
d1b91892 727because the XSUB will attempt to verify that the Perl object
a0d0e21e
LW
728is of the expected type.
729
730The following XS code shows the getnetconfigent() function which is used
731with ONC TIRPC. The getnetconfigent() function will return a pointer to a
732C structure and has the C prototype shown below. The example will
733demonstrate how the C pointer will become a Perl reference. Perl will
734consider this reference to be a pointer to a blessed object and will
735attempt to call a destructor for the object. A destructor will be
736provided in the XS source to free the memory used by getnetconfigent().
737Destructors in XS can be created by specifying an XSUB function whose name
738ends with the word B<DESTROY>. XS destructors can be used to free memory
739which may have been malloc'd by another XSUB.
740
741 struct netconfig *getnetconfigent(const char *netid);
742
743A C<typedef> will be created for C<struct netconfig>. The Perl
744object will be blessed in a class matching the name of the C
745type, with the tag C<Ptr> appended, and the name should not
746have embedded spaces if it will be a Perl package name. The
747destructor will be placed in a class corresponding to the
748class of the object and the PREFIX keyword will be used to
749trim the name to the word DESTROY as Perl will expect.
750
751 typedef struct netconfig Netconfig;
752
753 MODULE = RPC PACKAGE = RPC
754
755 Netconfig *
756 getnetconfigent(netid)
757 char * netid
758
759 MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
760
761 void
762 rpcb_DESTROY(netconf)
763 Netconfig * netconf
764 CODE:
765 printf("Now in NetconfigPtr::DESTROY\n");
766 free( netconf );
767
768This example requires the following typemap entry. Consult the typemap
769section for more information about adding new typemaps for an extension.
770
771 TYPEMAP
772 Netconfig * T_PTROBJ
773
774This example will be used with the following Perl statements.
775
776 use RPC;
777 $netconf = getnetconfigent("udp");
778
779When Perl destroys the object referenced by $netconf it will send the
780object to the supplied XSUB DESTROY function. Perl cannot determine, and
781does not care, that this object is a C struct and not a Perl object. In
782this sense, there is no difference between the object created by the
783getnetconfigent() XSUB and an object created by a normal Perl subroutine.
784
785=head2 C Headers and Perl
786
787The B<h2xs> compiler is designed to convert C header files in
788/usr/include into Perl extensions. This compiler will
789create a directory under the C<ext> directory of the Perl
790source and will populate it with a Makefile, a Perl Module,
791an XS source file, and a MANIFEST file.
792
793The following command will create an extension called C<Rusers>
794from the <rpcsvc/rusers.h> header.
795
796 h2xs rpcsvc/rusers
797
798When the Rusers extension has been compiled and installed
799Perl can use it to retrieve any C<#define> statements which
800were in the C header.
801
802 use Rusers;
803 print "RPC program number for rusers service: ";
804 print &RUSERSPROG, "\n";
805
806=head2 Creating A New Extension
807
808The B<h2xs> compiler can generate template source files and
809Makefiles. These templates offer a suitable starting point
810for most extensions. The following example demonstrates how
811one might use B<h2xs> to create an extension containing the RPC
812functions in this document.
813
814The extension will not use autoloaded functions and will not define
815constants, so the B<-A> option will be given to B<h2xs>. When run from the
816Perl source directory, the B<h2xs> compiler will create the directory
817ext/RPC and will populate it with files called RPC.xs, RPC.pm, Makefile.PL,
818and MANIFEST. The XS code for the RPC functions should be added to the
819RPC.xs file. The @EXPORT list in RPC.pm should be updated to include the
820functions from RPC.xs.
821
822 h2xs -An RPC
823
824To compile the extension for dynamic loading the following
825command should be executed from the ext/RPC directory.
826
827 make dynamic
828
829If the extension will be statically linked into the Perl
830binary then the makefile (use C<makefile>, not C<Makefile>) in the
831Perl source directory should be edited to add C<ext/RPC/RPC.a>
832to the C<static_ext> variable. Before making this change Perl
833should have already been built. After the makefile has been
834updated the following command should be executed from the
835Perl source directory.
836
837 make
838
839Perl's B<Configure> script can also be used to add extensions. The extension
840should be placed in the C<ext> directory under the Perl source before Perl
841has been built and prior to running Configure. When Configure is run it
842will find the extension along with the other extensions in the C<ext>
843directory and will add it to the list of extensions to be built. When make
844is run the extension will be built along with the other extensions.
845
846Configure recognizes extensions if they have an XS source
847file which matches the name of the extension directory. If
848the extension directory includes a MANIFEST file Configure
849will search that file for any B<.SH> files and extract them
850after it extracts all the other .SH files listed in the main
851MANIFEST. The main Perl Makefile will then run B<make> in the
852extension's directory if it finds an XS file matching the
853name of the extension's directory.
854
855=head2 The Typemap
856
857The typemap is a collection of code fragments which are used by the B<xsubpp>
858compiler to map C function parameters and values to Perl values. The
859typemap file may consist of three sections labeled C<TYPEMAP>, C<INPUT>, and
860C<OUTPUT>. The INPUT section tells the compiler how to translate Perl values
861into variables of certain C types. The OUTPUT section tells the compiler
862how to translate the values from certain C types into values Perl can
863understand. The TYPEMAP section tells the compiler which of the INPUT and
864OUTPUT code fragments should be used to map a given C type to a Perl value.
865Each of the sections of the typemap must be preceded by one of the TYPEMAP,
866INPUT, or OUTPUT keywords.
867
868The default typemap in the C<ext> directory of the Perl source contains many
869useful types which can be used by Perl extensions. Some extensions define
870additional typemaps which they keep in their own directory. These
871additional typemaps may reference INPUT and OUTPUT maps in the main
872typemap. The B<xsubpp> compiler will allow the extension's own typemap to
873override any mappings which are in the default typemap.
874
875Most extensions which require a custom typemap will need only the TYPEMAP
876section of the typemap file. The custom typemap used in the
877getnetconfigent() example shown earlier demonstrates what may be the typical
878use of extension typemaps. That typemap is used to equate a C structure
879with the T_PTROBJ typemap. The typemap used by getnetconfigent() is shown
880here. Note that the C type is separated from the XS type with a tab and
881that the C unary operator C<*> is considered to be a part of the C type name.
882
883 TYPEMAP
884 Netconfig *<tab>T_PTROBJ
885
886=head1 EXAMPLES
887
888File C<RPC.xs>: Interface to some ONC+ RPC bind library functions.
889
890 #include "EXTERN.h"
891 #include "perl.h"
892 #include "XSUB.h"
893
894 #include <rpc/rpc.h>
895
896 typedef struct netconfig Netconfig;
897
898 MODULE = RPC PACKAGE = RPC
899
900 void
901 rpcb_gettime(host="localhost")
902 char * host
903 CODE:
904 {
905 time_t timep;
906 ST(0) = sv_newmortal();
907 if( rpcb_gettime( host, &timep ) )
908 sv_setnv( ST(0), (double)timep );
909 }
910
911 Netconfig *
912 getnetconfigent(netid="udp")
913 char * netid
914
915 MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
916
917 void
918 rpcb_DESTROY(netconf)
919 Netconfig * netconf
920 CODE:
921 printf("NetconfigPtr::DESTROY\n");
922 free( netconf );
923
924File C<typemap>: Custom typemap for RPC.xs.
925
926 TYPEMAP
927 Netconfig * T_PTROBJ
928
929File C<RPC.pm>: Perl module for the RPC extension.
930
931 package RPC;
932
933 require Exporter;
934 require DynaLoader;
935 @ISA = qw(Exporter DynaLoader);
936 @EXPORT = qw(rpcb_gettime getnetconfigent);
937
938 bootstrap RPC;
939 1;
940
941File C<rpctest.pl>: Perl test program for the RPC extension.
942
943 use RPC;
944
945 $netconf = getnetconfigent();
946 $a = rpcb_gettime();
947 print "time = $a\n";
948 print "netconf = $netconf\n";
949
950 $netconf = getnetconfigent("tcp");
951 $a = rpcb_gettime("poplar");
952 print "time = $a\n";
953 print "netconf = $netconf\n";
954
955
956=head1 AUTHOR
957
d1b91892
AD
958Dean Roehrich F<E<lt>roehrich@cray.comE<gt>>
959May 3, 1995