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