.\" Automatically generated by Pod::Man 2.28 (Pod::Simple 3.28) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{ . if \nF \{ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLXS 1" .TH PERLXS 1 "2014-12-27" "perl v5.20.2" "Perl Programmers Reference Guide" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" perlxs \- XS language reference manual .SH "DESCRIPTION" .IX Header "DESCRIPTION" .SS "Introduction" .IX Subsection "Introduction" \&\s-1XS\s0 is an interface description file format used to create an extension interface between Perl and C code (or a C library) which one wishes to use with Perl. The \s-1XS\s0 interface is combined with the library to create a new library which can then be either dynamically loaded or statically linked into perl. The \s-1XS\s0 interface description is written in the \s-1XS\s0 language and is the core component of the Perl extension interface. .PP Before writing \s-1XS,\s0 read the \*(L"\s-1CAVEATS\*(R"\s0 section below. .PP An \fB\s-1XSUB\s0\fR forms the basic unit of the \s-1XS\s0 interface. After compilation by the \fBxsubpp\fR compiler, each \s-1XSUB\s0 amounts to a C function definition which will provide the glue between Perl calling conventions and C calling conventions. .PP The glue code pulls the arguments from the Perl stack, converts these Perl values to the formats expected by a C function, call this C function, transfers the return values of the C function back to Perl. Return values here may be a conventional C return value or any C function arguments that may serve as output parameters. These return values may be passed back to Perl either by putting them on the Perl stack, or by modifying the arguments supplied from the Perl side. .PP The above is a somewhat simplified view of what really happens. Since Perl allows more flexible calling conventions than C, XSUBs may do much more in practice, such as checking input parameters for validity, throwing exceptions (or returning undef/empty list) if the return value from the C function indicates failure, calling different C functions based on numbers and types of the arguments, providing an object-oriented interface, etc. .PP Of course, one could write such glue code directly in C. However, this would be a tedious task, especially if one needs to write glue for multiple C functions, and/or one is not familiar enough with the Perl stack discipline and other such arcana. \s-1XS\s0 comes to the rescue here: instead of writing this glue C code in long-hand, one can write a more concise short-hand \fIdescription\fR of what should be done by the glue, and let the \s-1XS\s0 compiler \fBxsubpp\fR handle the rest. .PP The \s-1XS\s0 language allows one to describe the mapping between how the C routine is used, and how the corresponding Perl routine is used. It also allows creation of Perl routines which are directly translated to C code and which are not related to a pre-existing C function. In cases when the C interface coincides with the Perl interface, the \s-1XSUB\s0 declaration is almost identical to a declaration of a C function (in K&R style). In such circumstances, there is another tool called \f(CW\*(C`h2xs\*(C'\fR that is able to translate an entire C header file into a corresponding \&\s-1XS\s0 file that will provide glue to the functions/macros described in the header file. .PP The \s-1XS\s0 compiler is called \fBxsubpp\fR. This compiler creates the constructs necessary to let an \s-1XSUB\s0 manipulate Perl values, and creates the glue necessary to let Perl call the \s-1XSUB. \s0 The compiler uses \fBtypemaps\fR to determine how to map C function parameters and output values to Perl values and back. The default typemap (which comes with Perl) handles many common C types. A supplementary typemap may also be needed to handle any special structures and types for the library being linked. For more information on typemaps, see perlxstypemap. .PP A file in \s-1XS\s0 format starts with a C language section which goes until the first \f(CW\*(C`MODULE =\*(C'\fR directive. Other \s-1XS\s0 directives and \s-1XSUB\s0 definitions may follow this line. The \*(L"language\*(R" used in this part of the file is usually referred to as the \s-1XS\s0 language. \fBxsubpp\fR recognizes and skips \s-1POD \s0(see perlpod) in both the C and \s-1XS\s0 language sections, which allows the \s-1XS\s0 file to contain embedded documentation. .PP See perlxstut for a tutorial on the whole extension creation process. .PP Note: For some extensions, Dave Beazley's \s-1SWIG\s0 system may provide a significantly more convenient mechanism for creating the extension glue code. See for more information. .SS "On The Road" .IX Subsection "On The Road" Many of the examples which follow will concentrate on creating an interface between Perl and the \s-1ONC+ RPC\s0 bind library functions. The \fIrpcb_gettime()\fR function is used to demonstrate many features of the \s-1XS\s0 language. This function has two parameters; the first is an input parameter and the second is an output parameter. The function also returns a status value. .PP .Vb 1 \& bool_t rpcb_gettime(const char *host, time_t *timep); .Ve .PP From C this function will be called with the following statements. .PP .Vb 4 \& #include \& bool_t status; \& time_t timep; \& status = rpcb_gettime( "localhost", &timep ); .Ve .PP If an \s-1XSUB\s0 is created to offer a direct translation between this function and Perl, then this \s-1XSUB\s0 will be used from Perl with the following code. The \f(CW$status\fR and \f(CW$timep\fR variables will contain the output of the function. .PP .Vb 2 \& use RPC; \& $status = rpcb_gettime( "localhost", $timep ); .Ve .PP The following \s-1XS\s0 file shows an \s-1XS\s0 subroutine, or \s-1XSUB,\s0 which demonstrates one possible interface to the \fIrpcb_gettime()\fR function. This \s-1XSUB\s0 represents a direct translation between C and Perl and so preserves the interface even from Perl. This \s-1XSUB\s0 will be invoked from Perl with the usage shown above. Note that the first three #include statements, for \&\f(CW\*(C`EXTERN.h\*(C'\fR, \f(CW\*(C`perl.h\*(C'\fR, and \f(CW\*(C`XSUB.h\*(C'\fR, will always be present at the beginning of an \s-1XS\s0 file. This approach and others will be expanded later in this document. A #define for \f(CW\*(C`PERL_NO_GET_CONTEXT\*(C'\fR should be present to fetch the interpreter context more efficiently, see perlguts for details. .PP .Vb 5 \& #define PERL_NO_GET_CONTEXT \& #include "EXTERN.h" \& #include "perl.h" \& #include "XSUB.h" \& #include \& \& MODULE = RPC PACKAGE = RPC \& \& bool_t \& rpcb_gettime(host,timep) \& char *host \& time_t &timep \& OUTPUT: \& timep .Ve .PP Any extension to Perl, including those containing XSUBs, should have a Perl module to serve as the bootstrap which pulls the extension into Perl. This module will export the extension's functions and variables to the Perl program and will cause the extension's XSUBs to be linked into Perl. The following module will be used for most of the examples in this document and should be used from Perl with the \f(CW\*(C`use\*(C'\fR command as shown earlier. Perl modules are explained in more detail later in this document. .PP .Vb 1 \& package RPC; \& \& require Exporter; \& require DynaLoader; \& @ISA = qw(Exporter DynaLoader); \& @EXPORT = qw( rpcb_gettime ); \& \& bootstrap RPC; \& 1; .Ve .PP Throughout this document a variety of interfaces to the \fIrpcb_gettime()\fR \&\s-1XSUB\s0 will be explored. The XSUBs will take their parameters in different orders or will take different numbers of parameters. In each case the \&\s-1XSUB\s0 is an abstraction between Perl and the real C \fIrpcb_gettime()\fR function, and the \s-1XSUB\s0 must always ensure that the real \fIrpcb_gettime()\fR function is called with the correct parameters. This abstraction will allow the programmer to create a more Perl-like interface to the C function. .SS "The Anatomy of an \s-1XSUB\s0" .IX Subsection "The Anatomy of an XSUB" The simplest XSUBs consist of 3 parts: a description of the return value, the name of the \s-1XSUB\s0 routine and the names of its arguments, and a description of types or formats of the arguments. .PP The following \s-1XSUB\s0 allows a Perl program to access a C library function called \fIsin()\fR. The \s-1XSUB\s0 will imitate the C function which takes a single argument and returns a single value. .PP .Vb 3 \& double \& sin(x) \& double x .Ve .PP Optionally, one can merge the description of types and the list of argument names, rewriting this as .PP .Vb 2 \& double \& sin(double x) .Ve .PP This makes this \s-1XSUB\s0 look similar to an \s-1ANSI C\s0 declaration. An optional semicolon is allowed after the argument list, as in .PP .Vb 2 \& double \& sin(double x); .Ve .PP Parameters with C pointer types can have different semantic: C functions with similar declarations .PP .Vb 2 \& bool string_looks_as_a_number(char *s); \& bool make_char_uppercase(char *c); .Ve .PP are used in absolutely incompatible manner. Parameters to these functions could be described \fBxsubpp\fR like this: .PP .Vb 2 \& char * s \& char &c .Ve .PP Both these \s-1XS\s0 declarations correspond to the \f(CW\*(C`char*\*(C'\fR C type, but they have different semantics, see \*(L"The & Unary Operator\*(R". .PP It is convenient to think that the indirection operator \&\f(CW\*(C`*\*(C'\fR should be considered as a part of the type and the address operator \f(CW\*(C`&\*(C'\fR should be considered part of the variable. See perlxstypemap for more info about handling qualifiers and unary operators in C types. .PP The function name and the return type must be placed on separate lines and should be flush left-adjusted. .PP .Vb 1 \& INCORRECT CORRECT \& \& double sin(x) double \& double x sin(x) \& double x .Ve .PP The rest of the function description may be indented or left-adjusted. The following example shows a function with its body left-adjusted. Most examples in this document will indent the body for better readability. .PP .Vb 1 \& CORRECT \& \& double \& sin(x) \& double x .Ve .PP More complicated XSUBs may contain many other sections. Each section of an \s-1XSUB\s0 starts with the corresponding keyword, such as \s-1INIT:\s0 or \s-1CLEANUP:.\s0 However, the first two lines of an \s-1XSUB\s0 always contain the same data: descriptions of the return type and the names of the function and its parameters. Whatever immediately follows these is considered to be an \s-1INPUT:\s0 section unless explicitly marked with another keyword. (See \*(L"The \s-1INPUT:\s0 Keyword\*(R".) .PP An \s-1XSUB\s0 section continues until another section-start keyword is found. .SS "The Argument Stack" .IX Subsection "The Argument Stack" The Perl argument stack is used to store the values which are sent as parameters to the \s-1XSUB\s0 and to store the \s-1XSUB\s0's return value(s). In reality all Perl functions (including non-XSUB ones) keep their values on this stack all the same time, each limited to its own range of positions on the stack. In this document the first position on that stack which belongs to the active function will be referred to as position 0 for that function. .PP XSUBs refer to their stack arguments with the macro \fB\s-1ST\s0(x)\fR, where \fIx\fR refers to a position in this \s-1XSUB\s0's part of the stack. Position 0 for that function would be known to the \s-1XSUB\s0 as \s-1\fIST\s0\fR\|(0). The \s-1XSUB\s0's incoming parameters and outgoing return values always begin at \s-1\fIST\s0\fR\|(0). For many simple cases the \fBxsubpp\fR compiler will generate the code necessary to handle the argument stack by embedding code fragments found in the typemaps. In more complex cases the programmer must supply the code. .SS "The \s-1RETVAL\s0 Variable" .IX Subsection "The RETVAL Variable" The \s-1RETVAL\s0 variable is a special C variable that is declared automatically for you. The C type of \s-1RETVAL\s0 matches the return type of the C library function. The \fBxsubpp\fR compiler will declare this variable in each \s-1XSUB\s0 with non\-\f(CW\*(C`void\*(C'\fR return type. By default the generated C function will use \s-1RETVAL\s0 to hold the return value of the C library function being called. In simple cases the value of \s-1RETVAL\s0 will be placed in \s-1\fIST\s0\fR\|(0) of the argument stack where it can be received by Perl as the return value of the \s-1XSUB.\s0 .PP If the \s-1XSUB\s0 has a return type of \f(CW\*(C`void\*(C'\fR then the compiler will not declare a \s-1RETVAL\s0 variable for that function. When using a \s-1PPCODE:\s0 section no manipulation of the \s-1RETVAL\s0 variable is required, the section may use direct stack manipulation to place output values on the stack. .PP If \s-1PPCODE:\s0 directive is not used, \f(CW\*(C`void\*(C'\fR return value should be used only for subroutines which do not return a value, \fIeven if\fR \s-1CODE:\s0 directive is used which sets \s-1\fIST\s0\fR\|(0) explicitly. .PP Older versions of this document recommended to use \f(CW\*(C`void\*(C'\fR return value in such cases. It was discovered that this could lead to segfaults in cases when \s-1XSUB\s0 was \fItruly\fR \f(CW\*(C`void\*(C'\fR. This practice is now deprecated, and may be not supported at some future version. Use the return value \f(CW\*(C`SV *\*(C'\fR in such cases. (Currently \f(CW\*(C`xsubpp\*(C'\fR contains some heuristic code which tries to disambiguate between \*(L"truly-void\*(R" and \*(L"old-practice-declared-as-void\*(R" functions. Hence your code is at mercy of this heuristics unless you use \f(CW\*(C`SV *\*(C'\fR as return value.) .SS "Returning SVs, AVs and HVs through \s-1RETVAL\s0" .IX Subsection "Returning SVs, AVs and HVs through RETVAL" When you're using \s-1RETVAL\s0 to return an \f(CW\*(C`SV *\*(C'\fR, there's some magic going on behind the scenes that should be mentioned. When you're manipulating the argument stack using the \s-1ST\s0(x) macro, for example, you usually have to pay special attention to reference counts. (For more about reference counts, see perlguts.) To make your life easier, the typemap file automatically makes \f(CW\*(C`RETVAL\*(C'\fR mortal when you're returning an \f(CW\*(C`SV *\*(C'\fR. Thus, the following two XSUBs are more or less equivalent: .PP .Vb 6 \& void \& alpha() \& PPCODE: \& ST(0) = newSVpv("Hello World",0); \& sv_2mortal(ST(0)); \& XSRETURN(1); \& \& SV * \& beta() \& CODE: \& RETVAL = newSVpv("Hello World",0); \& OUTPUT: \& RETVAL .Ve .PP This is quite useful as it usually improves readability. While this works fine for an \f(CW\*(C`SV *\*(C'\fR, it's unfortunately not as easy to have \f(CW\*(C`AV *\*(C'\fR or \f(CW\*(C`HV *\*(C'\fR as a return value. You \fIshould\fR be able to write: .PP .Vb 7 \& AV * \& array() \& CODE: \& RETVAL = newAV(); \& /* do something with RETVAL */ \& OUTPUT: \& RETVAL .Ve .PP But due to an unfixable bug (fixing it would break lots of existing \&\s-1CPAN\s0 modules) in the typemap file, the reference count of the \f(CW\*(C`AV *\*(C'\fR is not properly decremented. Thus, the above \s-1XSUB\s0 would leak memory whenever it is being called. The same problem exists for \f(CW\*(C`HV *\*(C'\fR, \&\f(CW\*(C`CV *\*(C'\fR, and \f(CW\*(C`SVREF\*(C'\fR (which indicates a scalar reference, not a general \f(CW\*(C`SV *\*(C'\fR). In \s-1XS\s0 code on perls starting with perl 5.16, you can override the typemaps for any of these types with a version that has proper handling of refcounts. In your \f(CW\*(C`TYPEMAP\*(C'\fR section, do .PP .Vb 1 \& AV* T_AVREF_REFCOUNT_FIXED .Ve .PP to get the repaired variant. For backward compatibility with older versions of perl, you can instead decrement the reference count manually when you're returning one of the aforementioned types using \f(CW\*(C`sv_2mortal\*(C'\fR: .PP .Vb 8 \& AV * \& array() \& CODE: \& RETVAL = newAV(); \& sv_2mortal((SV*)RETVAL); \& /* do something with RETVAL */ \& OUTPUT: \& RETVAL .Ve .PP Remember that you don't have to do this for an \f(CW\*(C`SV *\*(C'\fR. The reference documentation for all core typemaps can be found in perlxstypemap. .SS "The \s-1MODULE\s0 Keyword" .IX Subsection "The MODULE Keyword" The \s-1MODULE\s0 keyword is used to start the \s-1XS\s0 code and to specify the package of the functions which are being defined. All text preceding the first \&\s-1MODULE\s0 keyword is considered C code and is passed through to the output with \&\s-1POD\s0 stripped, but otherwise untouched. Every \s-1XS\s0 module will have a bootstrap function which is used to hook the XSUBs into Perl. The package name of this bootstrap function will match the value of the last \s-1MODULE\s0 statement in the \s-1XS\s0 source files. The value of \s-1MODULE\s0 should always remain constant within the same \s-1XS\s0 file, though this is not required. .PP The following example will start the \s-1XS\s0 code and will place all functions in a package named \s-1RPC.\s0 .PP .Vb 1 \& MODULE = RPC .Ve .SS "The \s-1PACKAGE\s0 Keyword" .IX Subsection "The PACKAGE Keyword" When functions within an \s-1XS\s0 source file must be separated into packages the \s-1PACKAGE\s0 keyword should be used. This keyword is used with the \s-1MODULE\s0 keyword and must follow immediately after it when used. .PP .Vb 1 \& MODULE = RPC PACKAGE = RPC \& \& [ XS code in package RPC ] \& \& MODULE = RPC PACKAGE = RPCB \& \& [ XS code in package RPCB ] \& \& MODULE = RPC PACKAGE = RPC \& \& [ XS code in package RPC ] .Ve .PP The same package name can be used more than once, allowing for non-contiguous code. This is useful if you have a stronger ordering principle than package names. .PP Although this keyword is optional and in some cases provides redundant information it should always be used. This keyword will ensure that the XSUBs appear in the desired package. .SS "The \s-1PREFIX\s0 Keyword" .IX Subsection "The PREFIX Keyword" The \s-1PREFIX\s0 keyword designates prefixes which should be removed from the Perl function names. If the C function is \&\f(CW\*(C`rpcb_gettime()\*(C'\fR and the \s-1PREFIX\s0 value is \f(CW\*(C`rpcb_\*(C'\fR then Perl will see this function as \f(CW\*(C`gettime()\*(C'\fR. .PP This keyword should follow the \s-1PACKAGE\s0 keyword when used. If \s-1PACKAGE\s0 is not used then \s-1PREFIX\s0 should follow the \s-1MODULE\s0 keyword. .PP .Vb 1 \& MODULE = RPC PREFIX = rpc_ \& \& MODULE = RPC PACKAGE = RPCB PREFIX = rpcb_ .Ve .SS "The \s-1OUTPUT:\s0 Keyword" .IX Subsection "The OUTPUT: Keyword" The \s-1OUTPUT:\s0 keyword indicates that certain function parameters should be updated (new values made visible to Perl) when the \s-1XSUB\s0 terminates or that certain values should be returned to the calling Perl function. For simple functions which have no \s-1CODE:\s0 or \s-1PPCODE:\s0 section, such as the \fIsin()\fR function above, the \s-1RETVAL\s0 variable is automatically designated as an output value. For more complex functions the \fBxsubpp\fR compiler will need help to determine which variables are output variables. .PP This keyword will normally be used to complement the \s-1CODE: \s0 keyword. The \s-1RETVAL\s0 variable is not recognized as an output variable when the \&\s-1CODE:\s0 keyword is present. The \s-1OUTPUT: \s0 keyword is used in this situation to tell the compiler that \s-1RETVAL\s0 really is an output variable. .PP The \s-1OUTPUT:\s0 keyword can also be used to indicate that function parameters are output variables. This may be necessary when a parameter has been modified within the function and the programmer would like the update to be seen by Perl. .PP .Vb 6 \& bool_t \& rpcb_gettime(host,timep) \& char *host \& time_t &timep \& OUTPUT: \& timep .Ve .PP The \s-1OUTPUT:\s0 keyword will also allow an output parameter to be mapped to a matching piece of code rather than to a typemap. .PP .Vb 6 \& bool_t \& rpcb_gettime(host,timep) \& char *host \& time_t &timep \& OUTPUT: \& timep sv_setnv(ST(1), (double)timep); .Ve .PP \&\fBxsubpp\fR emits an automatic \f(CW\*(C`SvSETMAGIC()\*(C'\fR for all parameters in the \&\s-1OUTPUT\s0 section of the \s-1XSUB,\s0 except \s-1RETVAL. \s0 This is the usually desired behavior, as it takes care of properly invoking 'set' magic on output parameters (needed for hash or array element parameters that must be created if they didn't exist). If for some reason, this behavior is not desired, the \s-1OUTPUT\s0 section may contain a \f(CW\*(C`SETMAGIC: DISABLE\*(C'\fR line to disable it for the remainder of the parameters in the \s-1OUTPUT\s0 section. Likewise, \f(CW\*(C`SETMAGIC: ENABLE\*(C'\fR can be used to reenable it for the remainder of the \s-1OUTPUT\s0 section. See perlguts for more details about 'set' magic. .SS "The \s-1NO_OUTPUT\s0 Keyword" .IX Subsection "The NO_OUTPUT Keyword" The \s-1NO_OUTPUT\s0 can be placed as the first token of the \s-1XSUB. \s0 This keyword indicates that while the C subroutine we provide an interface to has a non\-\f(CW\*(C`void\*(C'\fR return type, the return value of this C subroutine should not be returned from the generated Perl subroutine. .PP With this keyword present \*(L"The \s-1RETVAL\s0 Variable\*(R" is created, and in the generated call to the subroutine this variable is assigned to, but the value of this variable is not going to be used in the auto-generated code. .PP This keyword makes sense only if \f(CW\*(C`RETVAL\*(C'\fR is going to be accessed by the user-supplied code. It is especially useful to make a function interface more Perl-like, especially when the C return value is just an error condition indicator. For example, .PP .Vb 5 \& NO_OUTPUT int \& delete_file(char *name) \& POSTCALL: \& if (RETVAL != 0) \& croak("Error %d while deleting file \*(Aq%s\*(Aq", RETVAL, name); .Ve .PP Here the generated \s-1XS\s0 function returns nothing on success, and will \fIdie()\fR with a meaningful error message on error. .SS "The \s-1CODE:\s0 Keyword" .IX Subsection "The CODE: Keyword" This keyword is used in more complicated XSUBs which require special handling for the C function. The \s-1RETVAL\s0 variable is still declared, but it will not be returned unless it is specified in the \s-1OUTPUT:\s0 section. .PP The following \s-1XSUB\s0 is for a C function which requires special handling of its parameters. The Perl usage is given first. .PP .Vb 1 \& $status = rpcb_gettime( "localhost", $timep ); .Ve .PP The \s-1XSUB\s0 follows. .PP .Vb 9 \& bool_t \& rpcb_gettime(host,timep) \& char *host \& time_t timep \& CODE: \& RETVAL = rpcb_gettime( host, &timep ); \& OUTPUT: \& timep \& RETVAL .Ve .SS "The \s-1INIT:\s0 Keyword" .IX Subsection "The INIT: Keyword" The \s-1INIT:\s0 keyword allows initialization to be inserted into the \s-1XSUB\s0 before the compiler generates the call to the C function. Unlike the \s-1CODE:\s0 keyword above, this keyword does not affect the way the compiler handles \s-1RETVAL.\s0 .PP .Vb 8 \& bool_t \& rpcb_gettime(host,timep) \& char *host \& time_t &timep \& INIT: \& printf("# Host is %s\en", host ); \& OUTPUT: \& timep .Ve .PP Another use for the \s-1INIT:\s0 section is to check for preconditions before making a call to the C function: .PP .Vb 9 \& long long \& lldiv(a,b) \& long long a \& long long b \& INIT: \& if (a == 0 && b == 0) \& XSRETURN_UNDEF; \& if (b == 0) \& croak("lldiv: cannot divide by 0"); .Ve .SS "The \s-1NO_INIT\s0 Keyword" .IX Subsection "The NO_INIT Keyword" The \s-1NO_INIT\s0 keyword is used to indicate that a function parameter is being used only as an output value. The \fBxsubpp\fR compiler will normally generate code to read the values of all function parameters from the argument stack and assign them to C variables upon entry to the function. \s-1NO_INIT\s0 will tell the compiler that some parameters will be used for output rather than for input and that they will be handled before the function terminates. .PP The following example shows a variation of the \fIrpcb_gettime()\fR function. This function uses the timep variable only as an output variable and does not care about its initial contents. .PP .Vb 6 \& bool_t \& rpcb_gettime(host,timep) \& char *host \& time_t &timep = NO_INIT \& OUTPUT: \& timep .Ve .SS "The \s-1TYPEMAP:\s0 Keyword" .IX Subsection "The TYPEMAP: Keyword" Starting with Perl 5.16, you can embed typemaps into your \s-1XS\s0 code instead of or in addition to typemaps in a separate file. Multiple such embedded typemaps will be processed in order of appearance in the \s-1XS\s0 code and like local typemap files take precedence over the default typemap, the embedded typemaps may overwrite previous definitions of \s-1TYPEMAP, INPUT,\s0 and \s-1OUTPUT\s0 stanzas. The syntax for embedded typemaps is .PP .Vb 3 \& TYPEMAP: < 1 ) \& host = (char *)SvPV_nolen(ST(1)); \& RETVAL = rpcb_gettime( host, &timep ); \& OUTPUT: \& timep \& RETVAL .Ve .SS "The C_ARGS: Keyword" .IX Subsection "The C_ARGS: Keyword" The C_ARGS: keyword allows creating of \s-1XSUBS\s0 which have different calling sequence from Perl than from C, without a need to write \&\s-1CODE:\s0 or \s-1PPCODE:\s0 section. The contents of the C_ARGS: paragraph is put as the argument to the called C function without any change. .PP For example, suppose that a C function is declared as .PP .Vb 1 \& symbolic nth_derivative(int n, symbolic function, int flags); .Ve .PP and that the default flags are kept in a global C variable \&\f(CW\*(C`default_flags\*(C'\fR. Suppose that you want to create an interface which is called as .PP .Vb 1 \& $second_deriv = $function\->nth_derivative(2); .Ve .PP To do this, declare the \s-1XSUB\s0 as .PP .Vb 6 \& symbolic \& nth_derivative(function, n) \& symbolic function \& int n \& C_ARGS: \& n, function, default_flags .Ve .SS "The \s-1PPCODE:\s0 Keyword" .IX Subsection "The PPCODE: Keyword" The \s-1PPCODE:\s0 keyword is an alternate form of the \s-1CODE:\s0 keyword and is used to tell the \fBxsubpp\fR compiler that the programmer is supplying the code to control the argument stack for the XSUBs return values. Occasionally one will want an \s-1XSUB\s0 to return a list of values rather than a single value. In these cases one must use \s-1PPCODE:\s0 and then explicitly push the list of values on the stack. The \s-1PPCODE:\s0 and \s-1CODE: \s0 keywords should not be used together within the same \s-1XSUB.\s0 .PP The actual difference between \s-1PPCODE:\s0 and \s-1CODE:\s0 sections is in the initialization of \f(CW\*(C`SP\*(C'\fR macro (which stands for the \fIcurrent\fR Perl stack pointer), and in the handling of data on the stack when returning from an \s-1XSUB. \s0 In \s-1CODE:\s0 sections \s-1SP\s0 preserves the value which was on entry to the \s-1XSUB: SP\s0 is on the function pointer (which follows the last parameter). In \s-1PPCODE:\s0 sections \s-1SP\s0 is moved backward to the beginning of the parameter list, which allows \f(CW\*(C`PUSH*()\*(C'\fR macros to place output values in the place Perl expects them to be when the \s-1XSUB\s0 returns back to Perl. .PP The generated trailer for a \s-1CODE:\s0 section ensures that the number of return values Perl will see is either 0 or 1 (depending on the \f(CW\*(C`void\*(C'\fRness of the return value of the C function, and heuristics mentioned in \&\*(L"The \s-1RETVAL\s0 Variable\*(R"). The trailer generated for a \s-1PPCODE:\s0 section is based on the number of return values and on the number of times \&\f(CW\*(C`SP\*(C'\fR was updated by \f(CW\*(C`[X]PUSH*()\*(C'\fR macros. .PP Note that macros \f(CWST(i)\fR, \f(CW\*(C`XST_m*()\*(C'\fR and \f(CW\*(C`XSRETURN*()\*(C'\fR work equally well in \s-1CODE:\s0 sections and \s-1PPCODE:\s0 sections. .PP The following \s-1XSUB\s0 will call the C \fIrpcb_gettime()\fR function and will return its two output values, timep and status, to Perl as a single list. .PP .Vb 11 \& void \& rpcb_gettime(host) \& char *host \& PREINIT: \& time_t timep; \& bool_t status; \& PPCODE: \& status = rpcb_gettime( host, &timep ); \& EXTEND(SP, 2); \& PUSHs(sv_2mortal(newSViv(status))); \& PUSHs(sv_2mortal(newSViv(timep))); .Ve .PP Notice that the programmer must supply the C code necessary to have the real \fIrpcb_gettime()\fR function called and to have the return values properly placed on the argument stack. .PP The \f(CW\*(C`void\*(C'\fR return type for this function tells the \fBxsubpp\fR compiler that the \s-1RETVAL\s0 variable is not needed or used and that it should not be created. In most scenarios the void return type should be used with the \s-1PPCODE:\s0 directive. .PP The \s-1\fIEXTEND\s0()\fR macro is used to make room on the argument stack for 2 return values. The \s-1PPCODE:\s0 directive causes the \&\fBxsubpp\fR compiler to create a stack pointer available as \f(CW\*(C`SP\*(C'\fR, and it is this pointer which is being used in the \s-1\fIEXTEND\s0()\fR macro. The values are then pushed onto the stack with the \fIPUSHs()\fR macro. .PP Now the \fIrpcb_gettime()\fR function can be used from Perl with the following statement. .PP .Vb 1 \& ($status, $timep) = rpcb_gettime("localhost"); .Ve .PP When handling output parameters with a \s-1PPCODE\s0 section, be sure to handle \&'set' magic properly. See perlguts for details about 'set' magic. .SS "Returning Undef And Empty Lists" .IX Subsection "Returning Undef And Empty Lists" Occasionally the programmer will want to return simply \&\f(CW\*(C`undef\*(C'\fR or an empty list if a function fails rather than a separate status value. The \fIrpcb_gettime()\fR function offers just this situation. If the function succeeds we would like to have it return the time and if it fails we would like to have undef returned. In the following Perl code the value of \f(CW$timep\fR will either be undef or it will be a valid time. .PP .Vb 1 \& $timep = rpcb_gettime( "localhost" ); .Ve .PP The following \s-1XSUB\s0 uses the \f(CW\*(C`SV *\*(C'\fR return type as a mnemonic only, and uses a \s-1CODE:\s0 block to indicate to the compiler that the programmer has supplied all the necessary code. The \&\fIsv_newmortal()\fR call will initialize the return value to undef, making that the default return value. .PP .Vb 10 \& SV * \& rpcb_gettime(host) \& char * host \& PREINIT: \& time_t timep; \& bool_t x; \& CODE: \& ST(0) = sv_newmortal(); \& if( rpcb_gettime( host, &timep ) ) \& sv_setnv( ST(0), (double)timep); .Ve .PP The next example demonstrates how one would place an explicit undef in the return value, should the need arise. .PP .Vb 10 \& SV * \& rpcb_gettime(host) \& char * host \& PREINIT: \& time_t timep; \& bool_t x; \& CODE: \& if( rpcb_gettime( host, &timep ) ){ \& ST(0) = sv_newmortal(); \& sv_setnv( ST(0), (double)timep); \& } \& else{ \& ST(0) = &PL_sv_undef; \& } .Ve .PP To return an empty list one must use a \s-1PPCODE:\s0 block and then not push return values on the stack. .PP .Vb 12 \& void \& rpcb_gettime(host) \& char *host \& PREINIT: \& time_t timep; \& PPCODE: \& if( rpcb_gettime( host, &timep ) ) \& PUSHs(sv_2mortal(newSViv(timep))); \& else{ \& /* Nothing pushed on stack, so an empty \& * list is implicitly returned. */ \& } .Ve .PP Some people may be inclined to include an explicit \f(CW\*(C`return\*(C'\fR in the above \&\s-1XSUB,\s0 rather than letting control fall through to the end. In those situations \f(CW\*(C`XSRETURN_EMPTY\*(C'\fR should be used, instead. This will ensure that the \s-1XSUB\s0 stack is properly adjusted. Consult perlapi for other \&\f(CW\*(C`XSRETURN\*(C'\fR macros. .PP Since \f(CW\*(C`XSRETURN_*\*(C'\fR macros can be used with \s-1CODE\s0 blocks as well, one can rewrite this example as: .PP .Vb 11 \& int \& rpcb_gettime(host) \& char *host \& PREINIT: \& time_t timep; \& CODE: \& RETVAL = rpcb_gettime( host, &timep ); \& if (RETVAL == 0) \& XSRETURN_UNDEF; \& OUTPUT: \& RETVAL .Ve .PP In fact, one can put this check into a \s-1POSTCALL:\s0 section as well. Together with \s-1PREINIT:\s0 simplifications, this leads to: .PP .Vb 7 \& int \& rpcb_gettime(host) \& char *host \& time_t timep; \& POSTCALL: \& if (RETVAL == 0) \& XSRETURN_UNDEF; .Ve .SS "The \s-1REQUIRE:\s0 Keyword" .IX Subsection "The REQUIRE: Keyword" The \s-1REQUIRE:\s0 keyword is used to indicate the minimum version of the \&\fBxsubpp\fR compiler needed to compile the \s-1XS\s0 module. An \s-1XS\s0 module which contains the following statement will compile with only \fBxsubpp\fR version 1.922 or greater: .PP .Vb 1 \& REQUIRE: 1.922 .Ve .SS "The \s-1CLEANUP:\s0 Keyword" .IX Subsection "The CLEANUP: Keyword" This keyword can be used when an \s-1XSUB\s0 requires special cleanup procedures before it terminates. When the \s-1CLEANUP: \s0 keyword is used it must follow any \s-1CODE:, PPCODE:,\s0 or \s-1OUTPUT:\s0 blocks which are present in the \s-1XSUB. \s0 The code specified for the cleanup block will be added as the last statements in the \s-1XSUB.\s0 .SS "The \s-1POSTCALL:\s0 Keyword" .IX Subsection "The POSTCALL: Keyword" This keyword can be used when an \s-1XSUB\s0 requires special procedures executed after the C subroutine call is performed. When the \s-1POSTCALL:\s0 keyword is used it must precede \s-1OUTPUT:\s0 and \s-1CLEANUP:\s0 blocks which are present in the \s-1XSUB.\s0 .PP See examples in \*(L"The \s-1NO_OUTPUT\s0 Keyword\*(R" and \*(L"Returning Undef And Empty Lists\*(R". .PP The \s-1POSTCALL:\s0 block does not make a lot of sense when the C subroutine call is supplied by user by providing either \s-1CODE:\s0 or \s-1PPCODE:\s0 section. .SS "The \s-1BOOT:\s0 Keyword" .IX Subsection "The BOOT: Keyword" The \s-1BOOT:\s0 keyword is used to add code to the extension's bootstrap function. The bootstrap function is generated by the \fBxsubpp\fR compiler and normally holds the statements necessary to register any XSUBs with Perl. With the \s-1BOOT:\s0 keyword the programmer can tell the compiler to add extra statements to the bootstrap function. .PP This keyword may be used any time after the first \s-1MODULE\s0 keyword and should appear on a line by itself. The first blank line after the keyword will terminate the code block. .PP .Vb 4 \& BOOT: \& # The following message will be printed when the \& # bootstrap function executes. \& printf("Hello from the bootstrap!\en"); .Ve .SS "The \s-1VERSIONCHECK:\s0 Keyword" .IX Subsection "The VERSIONCHECK: Keyword" The \s-1VERSIONCHECK:\s0 keyword corresponds to \fBxsubpp\fR's \f(CW\*(C`\-versioncheck\*(C'\fR and \&\f(CW\*(C`\-noversioncheck\*(C'\fR options. This keyword overrides the command line options. Version checking is enabled by default. When version checking is enabled the \s-1XS\s0 module will attempt to verify that its version matches the version of the \s-1PM\s0 module. .PP To enable version checking: .PP .Vb 1 \& VERSIONCHECK: ENABLE .Ve .PP To disable version checking: .PP .Vb 1 \& VERSIONCHECK: DISABLE .Ve .PP Note that if the version of the \s-1PM\s0 module is an \s-1NV \s0(a floating point number), it will be stringified with a possible loss of precision (currently chopping to nine decimal places) so that it may not match the version of the \s-1XS\s0 module anymore. Quoting the \f(CW$VERSION\fR declaration to make it a string is recommended if long version numbers are used. .SS "The \s-1PROTOTYPES:\s0 Keyword" .IX Subsection "The PROTOTYPES: Keyword" The \s-1PROTOTYPES:\s0 keyword corresponds to \fBxsubpp\fR's \f(CW\*(C`\-prototypes\*(C'\fR and \&\f(CW\*(C`\-noprototypes\*(C'\fR options. This keyword overrides the command line options. Prototypes are enabled by default. When prototypes are enabled XSUBs will be given Perl prototypes. This keyword may be used multiple times in an \s-1XS\s0 module to enable and disable prototypes for different parts of the module. .PP To enable prototypes: .PP .Vb 1 \& PROTOTYPES: ENABLE .Ve .PP To disable prototypes: .PP .Vb 1 \& PROTOTYPES: DISABLE .Ve .SS "The \s-1PROTOTYPE:\s0 Keyword" .IX Subsection "The PROTOTYPE: Keyword" This keyword is similar to the \s-1PROTOTYPES:\s0 keyword above but can be used to force \fBxsubpp\fR to use a specific prototype for the \s-1XSUB. \s0 This keyword overrides all other prototype options and keywords but affects only the current \s-1XSUB. \s0 Consult \*(L"Prototypes\*(R" in perlsub for information about Perl prototypes. .PP .Vb 10 \& bool_t \& rpcb_gettime(timep, ...) \& time_t timep = NO_INIT \& PROTOTYPE: $;$ \& PREINIT: \& char *host = "localhost"; \& CODE: \& if( items > 1 ) \& host = (char *)SvPV_nolen(ST(1)); \& RETVAL = rpcb_gettime( host, &timep ); \& OUTPUT: \& timep \& RETVAL .Ve .PP If the prototypes are enabled, you can disable it locally for a given \&\s-1XSUB\s0 as in the following example: .PP .Vb 4 \& void \& rpcb_gettime_noproto() \& PROTOTYPE: DISABLE \& ... .Ve .SS "The \s-1ALIAS:\s0 Keyword" .IX Subsection "The ALIAS: Keyword" The \s-1ALIAS:\s0 keyword allows an \s-1XSUB\s0 to have two or more unique Perl names and to know which of those names was used when it was invoked. The Perl names may be fully-qualified with package names. Each alias is given an index. The compiler will setup a variable called \f(CW\*(C`ix\*(C'\fR which contain the index of the alias which was used. When the \s-1XSUB\s0 is called with its declared name \f(CW\*(C`ix\*(C'\fR will be 0. .PP The following example will create aliases \f(CW\*(C`FOO::gettime()\*(C'\fR and \&\f(CW\*(C`BAR::getit()\*(C'\fR for this function. .PP .Vb 11 \& bool_t \& rpcb_gettime(host,timep) \& char *host \& time_t &timep \& ALIAS: \& FOO::gettime = 1 \& BAR::getit = 2 \& INIT: \& printf("# ix = %d\en", ix ); \& OUTPUT: \& timep .Ve .SS "The \s-1OVERLOAD:\s0 Keyword" .IX Subsection "The OVERLOAD: Keyword" Instead of writing an overloaded interface using pure Perl, you can also use the \s-1OVERLOAD\s0 keyword to define additional Perl names for your functions (like the \s-1ALIAS:\s0 keyword above). However, the overloaded functions must be defined with three parameters (except for the \fInomethod()\fR function which needs four parameters). If any function has the \s-1OVERLOAD:\s0 keyword, several additional lines will be defined in the c file generated by xsubpp in order to register with the overload magic. .PP Since blessed objects are actually stored as \s-1RV\s0's, it is useful to use the typemap features to preprocess parameters and extract the actual \s-1SV\s0 stored within the blessed \s-1RV. \s0 See the sample for T_PTROBJ_SPECIAL below. .PP To use the \s-1OVERLOAD:\s0 keyword, create an \s-1XS\s0 function which takes three input parameters ( or use the c style '...' definition) like this: .PP .Vb 7 \& SV * \& cmp (lobj, robj, swap) \& My_Module_obj lobj \& My_Module_obj robj \& IV swap \& OVERLOAD: cmp <=> \& { /* function defined here */} .Ve .PP In this case, the function will overload both of the three way comparison operators. For all overload operations using non-alpha characters, you must type the parameter without quoting, separating multiple overloads with whitespace. Note that "\*(L" (the stringify overload) should be entered as \e\*(R"\e" (i.e. escaped). .SS "The \s-1FALLBACK:\s0 Keyword" .IX Subsection "The FALLBACK: Keyword" In addition to the \s-1OVERLOAD\s0 keyword, if you need to control how Perl autogenerates missing overloaded operators, you can set the \&\s-1FALLBACK\s0 keyword in the module header section, like this: .PP .Vb 1 \& MODULE = RPC PACKAGE = RPC \& \& FALLBACK: TRUE \& ... .Ve .PP where \s-1FALLBACK\s0 can take any of the three values \s-1TRUE, FALSE,\s0 or \&\s-1UNDEF. \s0 If you do not set any \s-1FALLBACK\s0 value when using \s-1OVERLOAD,\s0 it defaults to \s-1UNDEF. FALLBACK\s0 is not used except when one or more functions using \s-1OVERLOAD\s0 have been defined. Please see \&\*(L"fallback\*(R" in overload for more details. .SS "The \s-1INTERFACE:\s0 Keyword" .IX Subsection "The INTERFACE: Keyword" This keyword declares the current \s-1XSUB\s0 as a keeper of the given calling signature. If some text follows this keyword, it is considered as a list of functions which have this signature, and should be attached to the current \s-1XSUB.\s0 .PP For example, if you have 4 C functions \fImultiply()\fR, \fIdivide()\fR, \fIadd()\fR, \&\fIsubtract()\fR all having the signature: .PP .Vb 1 \& symbolic f(symbolic, symbolic); .Ve .PP you can make them all to use the same \s-1XSUB\s0 using this: .PP .Vb 7 \& symbolic \& interface_s_ss(arg1, arg2) \& symbolic arg1 \& symbolic arg2 \& INTERFACE: \& multiply divide \& add subtract .Ve .PP (This is the complete \s-1XSUB\s0 code for 4 Perl functions!) Four generated Perl function share names with corresponding C functions. .PP The advantage of this approach comparing to \s-1ALIAS:\s0 keyword is that there is no need to code a switch statement, each Perl function (which shares the same \s-1XSUB\s0) knows which C function it should call. Additionally, one can attach an extra function \fIremainder()\fR at runtime by using .PP .Vb 3 \& CV *mycv = newXSproto("Symbolic::remainder", \& XS_Symbolic_interface_s_ss, _\|_FILE_\|_, "$$"); \& XSINTERFACE_FUNC_SET(mycv, remainder); .Ve .PP say, from another \s-1XSUB. \s0(This example supposes that there was no \&\s-1INTERFACE_MACRO:\s0 section, otherwise one needs to use something else instead of \&\f(CW\*(C`XSINTERFACE_FUNC_SET\*(C'\fR, see the next section.) .SS "The \s-1INTERFACE_MACRO:\s0 Keyword" .IX Subsection "The INTERFACE_MACRO: Keyword" This keyword allows one to define an \s-1INTERFACE\s0 using a different way to extract a function pointer from an \s-1XSUB. \s0 The text which follows this keyword should give the name of macros which would extract/set a function pointer. The extractor macro is given return type, \f(CW\*(C`CV*\*(C'\fR, and \f(CW\*(C`XSANY.any_dptr\*(C'\fR for this \f(CW\*(C`CV*\*(C'\fR. The setter macro is given cv, and the function pointer. .PP The default value is \f(CW\*(C`XSINTERFACE_FUNC\*(C'\fR and \f(CW\*(C`XSINTERFACE_FUNC_SET\*(C'\fR. An \s-1INTERFACE\s0 keyword with an empty list of functions can be omitted if \&\s-1INTERFACE_MACRO\s0 keyword is used. .PP Suppose that in the previous example functions pointers for \&\fImultiply()\fR, \fIdivide()\fR, \fIadd()\fR, \fIsubtract()\fR are kept in a global C array \&\f(CW\*(C`fp[]\*(C'\fR with offsets being \f(CW\*(C`multiply_off\*(C'\fR, \f(CW\*(C`divide_off\*(C'\fR, \f(CW\*(C`add_off\*(C'\fR, \&\f(CW\*(C`subtract_off\*(C'\fR. Then one can use .PP .Vb 4 \& #define XSINTERFACE_FUNC_BYOFFSET(ret,cv,f) \e \& ((XSINTERFACE_CVT_ANON(ret))fp[CvXSUBANY(cv).any_i32]) \& #define XSINTERFACE_FUNC_BYOFFSET_set(cv,f) \e \& CvXSUBANY(cv).any_i32 = CAT2( f, _off ) .Ve .PP in C section, .PP .Vb 10 \& symbolic \& interface_s_ss(arg1, arg2) \& symbolic arg1 \& symbolic arg2 \& INTERFACE_MACRO: \& XSINTERFACE_FUNC_BYOFFSET \& XSINTERFACE_FUNC_BYOFFSET_set \& INTERFACE: \& multiply divide \& add subtract .Ve .PP in \s-1XSUB\s0 section. .SS "The \s-1INCLUDE:\s0 Keyword" .IX Subsection "The INCLUDE: Keyword" This keyword can be used to pull other files into the \s-1XS\s0 module. The other files may have \s-1XS\s0 code. \s-1INCLUDE:\s0 can also be used to run a command to generate the \s-1XS\s0 code to be pulled into the module. .PP The file \fIRpcb1.xsh\fR contains our \f(CW\*(C`rpcb_gettime()\*(C'\fR function: .PP .Vb 6 \& bool_t \& rpcb_gettime(host,timep) \& char *host \& time_t &timep \& OUTPUT: \& timep .Ve .PP The \s-1XS\s0 module can use \s-1INCLUDE:\s0 to pull that file into it. .PP .Vb 1 \& INCLUDE: Rpcb1.xsh .Ve .PP If the parameters to the \s-1INCLUDE:\s0 keyword are followed by a pipe (\f(CW\*(C`|\*(C'\fR) then the compiler will interpret the parameters as a command. This feature is mildly deprecated in favour of the \f(CW\*(C`INCLUDE_COMMAND:\*(C'\fR directive, as documented below. .PP .Vb 1 \& INCLUDE: cat Rpcb1.xsh | .Ve .PP Do not use this to run perl: \f(CW\*(C`INCLUDE: perl |\*(C'\fR will run the perl that happens to be the first in your path and not necessarily the same perl that is used to run \f(CW\*(C`xsubpp\*(C'\fR. See \*(L"The \s-1INCLUDE_COMMAND:\s0 Keyword\*(R". .SS "The \s-1INCLUDE_COMMAND:\s0 Keyword" .IX Subsection "The INCLUDE_COMMAND: Keyword" Runs the supplied command and includes its output into the current \s-1XS\s0 document. \f(CW\*(C`INCLUDE_COMMAND\*(C'\fR assigns special meaning to the \f(CW$^X\fR token in that it runs the same perl interpreter that is running \f(CW\*(C`xsubpp\*(C'\fR: .PP .Vb 1 \& INCLUDE_COMMAND: cat Rpcb1.xsh \& \& INCLUDE_COMMAND: $^X \-e ... .Ve .SS "The \s-1CASE:\s0 Keyword" .IX Subsection "The CASE: Keyword" The \s-1CASE:\s0 keyword allows an \s-1XSUB\s0 to have multiple distinct parts with each part acting as a virtual \s-1XSUB. CASE:\s0 is greedy and if it is used then all other \s-1XS\s0 keywords must be contained within a \s-1CASE:. \s0 This means nothing may precede the first \s-1CASE:\s0 in the \s-1XSUB\s0 and anything following the last \s-1CASE:\s0 is included in that case. .PP A \s-1CASE:\s0 might switch via a parameter of the \s-1XSUB,\s0 via the \f(CW\*(C`ix\*(C'\fR \s-1ALIAS:\s0 variable (see \*(L"The \s-1ALIAS:\s0 Keyword\*(R"), or maybe via the \f(CW\*(C`items\*(C'\fR variable (see \*(L"Variable-length Parameter Lists\*(R"). The last \s-1CASE:\s0 becomes the \&\fBdefault\fR case if it is not associated with a conditional. The following example shows \s-1CASE\s0 switched via \f(CW\*(C`ix\*(C'\fR with a function \f(CW\*(C`rpcb_gettime()\*(C'\fR having an alias \f(CW\*(C`x_gettime()\*(C'\fR. When the function is called as \&\f(CW\*(C`rpcb_gettime()\*(C'\fR its parameters are the usual \f(CW\*(C`(char *host, time_t *timep)\*(C'\fR, but when the function is called as \f(CW\*(C`x_gettime()\*(C'\fR its parameters are reversed, \f(CW\*(C`(time_t *timep, char *host)\*(C'\fR. .PP .Vb 10 \& long \& rpcb_gettime(a,b) \& CASE: ix == 1 \& ALIAS: \& x_gettime = 1 \& INPUT: \& # \*(Aqa\*(Aq is timep, \*(Aqb\*(Aq is host \& char *b \& time_t a = NO_INIT \& CODE: \& RETVAL = rpcb_gettime( b, &a ); \& OUTPUT: \& a \& RETVAL \& CASE: \& # \*(Aqa\*(Aq is host, \*(Aqb\*(Aq is timep \& char *a \& time_t &b = NO_INIT \& OUTPUT: \& b \& RETVAL .Ve .PP That function can be called with either of the following statements. Note the different argument lists. .PP .Vb 1 \& $status = rpcb_gettime( $host, $timep ); \& \& $status = x_gettime( $timep, $host ); .Ve .SS "The \s-1EXPORT_XSUB_SYMBOLS:\s0 Keyword" .IX Subsection "The EXPORT_XSUB_SYMBOLS: Keyword" The \s-1EXPORT_XSUB_SYMBOLS:\s0 keyword is likely something you will never need. In perl versions earlier than 5.16.0, this keyword does nothing. Starting with 5.16, \s-1XSUB\s0 symbols are no longer exported by default. That is, they are \f(CW\*(C`static\*(C'\fR functions. If you include .PP .Vb 1 \& EXPORT_XSUB_SYMBOLS: ENABLE .Ve .PP in your \s-1XS\s0 code, the XSUBs following this line will not be declared \f(CW\*(C`static\*(C'\fR. You can later disable this with .PP .Vb 1 \& EXPORT_XSUB_SYMBOLS: DISABLE .Ve .PP which, again, is the default that you should probably never change. You cannot use this keyword on versions of perl before 5.16 to make XSUBs \f(CW\*(C`static\*(C'\fR. .SS "The & Unary Operator" .IX Subsection "The & Unary Operator" The \f(CW\*(C`&\*(C'\fR unary operator in the \s-1INPUT:\s0 section is used to tell \fBxsubpp\fR that it should convert a Perl value to/from C using the C type to the left of \f(CW\*(C`&\*(C'\fR, but provide a pointer to this value when the C function is called. .PP This is useful to avoid a \s-1CODE:\s0 block for a C function which takes a parameter by reference. Typically, the parameter should be not a pointer type (an \&\f(CW\*(C`int\*(C'\fR or \f(CW\*(C`long\*(C'\fR but not an \f(CW\*(C`int*\*(C'\fR or \f(CW\*(C`long*\*(C'\fR). .PP The following \s-1XSUB\s0 will generate incorrect C code. The \fBxsubpp\fR compiler will turn this into code which calls \f(CW\*(C`rpcb_gettime()\*(C'\fR with parameters \f(CW\*(C`(char *host, time_t timep)\*(C'\fR, but the real \f(CW\*(C`rpcb_gettime()\*(C'\fR wants the \f(CW\*(C`timep\*(C'\fR parameter to be of type \f(CW\*(C`time_t*\*(C'\fR rather than \f(CW\*(C`time_t\*(C'\fR. .PP .Vb 6 \& bool_t \& rpcb_gettime(host,timep) \& char *host \& time_t timep \& OUTPUT: \& timep .Ve .PP That problem is corrected by using the \f(CW\*(C`&\*(C'\fR operator. The \fBxsubpp\fR compiler will now turn this into code which calls \f(CW\*(C`rpcb_gettime()\*(C'\fR correctly with parameters \f(CW\*(C`(char *host, time_t *timep)\*(C'\fR. It does this by carrying the \&\f(CW\*(C`&\*(C'\fR through, so the function call looks like \f(CW\*(C`rpcb_gettime(host, &timep)\*(C'\fR. .PP .Vb 6 \& bool_t \& rpcb_gettime(host,timep) \& char *host \& time_t &timep \& OUTPUT: \& timep .Ve .SS "Inserting \s-1POD,\s0 Comments and C Preprocessor Directives" .IX Subsection "Inserting POD, Comments and C Preprocessor Directives" C preprocessor directives are allowed within \s-1BOOT:, PREINIT: INIT:, CODE:, PPCODE:, POSTCALL:,\s0 and \s-1CLEANUP:\s0 blocks, as well as outside the functions. Comments are allowed anywhere after the \s-1MODULE\s0 keyword. The compiler will pass the preprocessor directives through untouched and will remove the commented lines. \s-1POD\s0 documentation is allowed at any point, both in the C and \s-1XS\s0 language sections. \s-1POD\s0 must be terminated with a \f(CW\*(C`=cut\*(C'\fR command; \&\f(CW\*(C`xsubpp\*(C'\fR will exit with an error if it does not. It is very unlikely that human generated C code will be mistaken for \s-1POD,\s0 as most indenting styles result in whitespace in front of any line starting with \f(CW\*(C`=\*(C'\fR. Machine generated \s-1XS\s0 files may fall into this trap unless care is taken to ensure that a space breaks the sequence \*(L"\en=\*(R". .PP Comments can be added to XSUBs by placing a \f(CW\*(C`#\*(C'\fR as the first non-whitespace of a line. Care should be taken to avoid making the comment look like a C preprocessor directive, lest it be interpreted as such. The simplest way to prevent this is to put whitespace in front of the \f(CW\*(C`#\*(C'\fR. .PP If you use preprocessor directives to choose one of two versions of a function, use .PP .Vb 3 \& #if ... version1 \& #else /* ... version2 */ \& #endif .Ve .PP and not .PP .Vb 4 \& #if ... version1 \& #endif \& #if ... version2 \& #endif .Ve .PP because otherwise \fBxsubpp\fR will believe that you made a duplicate definition of the function. Also, put a blank line before the #else/#endif so it will not be seen as part of the function body. .SS "Using \s-1XS\s0 With \*(C+" .IX Subsection "Using XS With " If an \s-1XSUB\s0 name contains \f(CW\*(C`::\*(C'\fR, it is considered to be a \*(C+ method. The generated Perl function will assume that its first argument is an object pointer. The object pointer will be stored in a variable called \s-1THIS. \s0 The object should have been created by \*(C+ with the \fInew()\fR function and should be blessed by Perl with the \fIsv_setref_pv()\fR macro. The blessing of the object by Perl can be handled by a typemap. An example typemap is shown at the end of this section. .PP If the return type of the \s-1XSUB\s0 includes \f(CW\*(C`static\*(C'\fR, the method is considered to be a static method. It will call the \*(C+ function using the \fIclass::method()\fR syntax. If the method is not static the function will be called using the \s-1THIS\-\s0>\fImethod()\fR syntax. .PP The next examples will use the following \*(C+ class. .PP .Vb 6 \& class color { \& public: \& color(); \& ~color(); \& int blue(); \& void set_blue( int ); \& \& private: \& int c_blue; \& }; .Ve .PP The XSUBs for the \fIblue()\fR and \fIset_blue()\fR methods are defined with the class name but the parameter for the object (\s-1THIS,\s0 or \*(L"self\*(R") is implicit and is not listed. .PP .Vb 2 \& int \& color::blue() \& \& void \& color::set_blue( val ) \& int val .Ve .PP Both Perl functions will expect an object as the first parameter. In the generated \*(C+ code the object is called \f(CW\*(C`THIS\*(C'\fR, and the method call will be performed on this object. So in the \*(C+ code the \fIblue()\fR and \fIset_blue()\fR methods will be called as this: .PP .Vb 1 \& RETVAL = THIS\->blue(); \& \& THIS\->set_blue( val ); .Ve .PP You could also write a single get/set method using an optional argument: .PP .Vb 10 \& int \& color::blue( val = NO_INIT ) \& int val \& PROTOTYPE $;$ \& CODE: \& if (items > 1) \& THIS\->set_blue( val ); \& RETVAL = THIS\->blue(); \& OUTPUT: \& RETVAL .Ve .PP If the function's name is \fB\s-1DESTROY\s0\fR then the \*(C+ \f(CW\*(C`delete\*(C'\fR function will be called and \f(CW\*(C`THIS\*(C'\fR will be given as its parameter. The generated \*(C+ code for .PP .Vb 2 \& void \& color::DESTROY() .Ve .PP will look like this: .PP .Vb 1 \& color *THIS = ...; // Initialized as in typemap \& \& delete THIS; .Ve .PP If the function's name is \fBnew\fR then the \*(C+ \f(CW\*(C`new\*(C'\fR function will be called to create a dynamic \*(C+ object. The \s-1XSUB\s0 will expect the class name, which will be kept in a variable called \f(CW\*(C`CLASS\*(C'\fR, to be given as the first argument. .PP .Vb 2 \& color * \& color::new() .Ve .PP The generated \*(C+ code will call \f(CW\*(C`new\*(C'\fR. .PP .Vb 1 \& RETVAL = new color(); .Ve .PP The following is an example of a typemap that could be used for this \*(C+ example. .PP .Vb 2 \& TYPEMAP \& color * O_OBJECT \& \& OUTPUT \& # The Perl object is blessed into \*(AqCLASS\*(Aq, which should be a \& # char* having the name of the package for the blessing. \& O_OBJECT \& sv_setref_pv( $arg, CLASS, (void*)$var ); \& \& INPUT \& O_OBJECT \& if( sv_isobject($arg) && (SvTYPE(SvRV($arg)) == SVt_PVMG) ) \& $var = ($type)SvIV((SV*)SvRV( $arg )); \& else{ \& warn("${Package}::$func_name() \-\- " . \& "$var is not a blessed SV reference"); \& XSRETURN_UNDEF; \& } .Ve .SS "Interface Strategy" .IX Subsection "Interface Strategy" When designing an interface between Perl and a C library a straight translation from C to \s-1XS \s0(such as created by \f(CW\*(C`h2xs \-x\*(C'\fR) is often sufficient. However, sometimes the interface will look very C\-like and occasionally nonintuitive, especially when the C function modifies one of its parameters, or returns failure inband (as in \*(L"negative return values mean failure\*(R"). In cases where the programmer wishes to create a more Perl-like interface the following strategy may help to identify the more critical parts of the interface. .PP Identify the C functions with input/output or output parameters. The XSUBs for these functions may be able to return lists to Perl. .PP Identify the C functions which use some inband info as an indication of failure. They may be candidates to return undef or an empty list in case of failure. If the failure may be detected without a call to the C function, you may want to use an \s-1INIT:\s0 section to report the failure. For failures detectable after the C function returns one may want to use a \s-1POSTCALL:\s0 section to process the failure. In more complicated cases use \s-1CODE:\s0 or \s-1PPCODE:\s0 sections. .PP If many functions use the same failure indication based on the return value, you may want to create a special typedef to handle this situation. Put .PP .Vb 1 \& typedef int negative_is_failure; .Ve .PP near the beginning of \s-1XS\s0 file, and create an \s-1OUTPUT\s0 typemap entry for \f(CW\*(C`negative_is_failure\*(C'\fR which converts negative values to \f(CW\*(C`undef\*(C'\fR, or maybe \fIcroak()\fRs. After this the return value of type \f(CW\*(C`negative_is_failure\*(C'\fR will create more Perl-like interface. .PP Identify which values are used by only the C and \s-1XSUB\s0 functions themselves, say, when a parameter to a function should be a contents of a global variable. If Perl does not need to access the contents of the value then it may not be necessary to provide a translation for that value from C to Perl. .PP Identify the pointers in the C function parameter lists and return values. Some pointers may be used to implement input/output or output parameters, they can be handled in \s-1XS\s0 with the \f(CW\*(C`&\*(C'\fR unary operator, and, possibly, using the \s-1NO_INIT\s0 keyword. Some others will require handling of types like \f(CW\*(C`int *\*(C'\fR, and one needs to decide what a useful Perl translation will do in such a case. When the semantic is clear, it is advisable to put the translation into a typemap file. .PP Identify the structures used by the C functions. In many cases it may be helpful to use the T_PTROBJ typemap for these structures so they can be manipulated by Perl as blessed objects. (This is handled automatically by \f(CW\*(C`h2xs \-x\*(C'\fR.) .PP If the same C type is used in several different contexts which require different translations, \f(CW\*(C`typedef\*(C'\fR several new types mapped to this C type, and create separate \fItypemap\fR entries for these new types. Use these types in declarations of return type and parameters to XSUBs. .SS "Perl Objects And C Structures" .IX Subsection "Perl Objects And C Structures" When dealing with C structures one should select either \&\fBT_PTROBJ\fR or \fBT_PTRREF\fR for the \s-1XS\s0 type. Both types are designed to handle pointers to complex objects. The T_PTRREF type will allow the Perl object to be unblessed while the T_PTROBJ type requires that the object be blessed. By using T_PTROBJ one can achieve a form of type-checking because the \s-1XSUB\s0 will attempt to verify that the Perl object is of the expected type. .PP The following \s-1XS\s0 code shows the \fIgetnetconfigent()\fR function which is used with \s-1ONC+ TIRPC. \s0 The \fIgetnetconfigent()\fR function will return a pointer to a C structure and has the C prototype shown below. The example will demonstrate how the C pointer will become a Perl reference. Perl will consider this reference to be a pointer to a blessed object and will attempt to call a destructor for the object. A destructor will be provided in the \s-1XS\s0 source to free the memory used by \fIgetnetconfigent()\fR. Destructors in \s-1XS\s0 can be created by specifying an \s-1XSUB\s0 function whose name ends with the word \fB\s-1DESTROY\s0\fR. \s-1XS\s0 destructors can be used to free memory which may have been malloc'd by another \s-1XSUB.\s0 .PP .Vb 1 \& struct netconfig *getnetconfigent(const char *netid); .Ve .PP A \f(CW\*(C`typedef\*(C'\fR will be created for \f(CW\*(C`struct netconfig\*(C'\fR. The Perl object will be blessed in a class matching the name of the C type, with the tag \f(CW\*(C`Ptr\*(C'\fR appended, and the name should not have embedded spaces if it will be a Perl package name. The destructor will be placed in a class corresponding to the class of the object and the \s-1PREFIX\s0 keyword will be used to trim the name to the word \s-1DESTROY\s0 as Perl will expect. .PP .Vb 1 \& typedef struct netconfig Netconfig; \& \& MODULE = RPC PACKAGE = RPC \& \& Netconfig * \& getnetconfigent(netid) \& char *netid \& \& MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_ \& \& void \& rpcb_DESTROY(netconf) \& Netconfig *netconf \& CODE: \& printf("Now in NetconfigPtr::DESTROY\en"); \& free( netconf ); .Ve .PP This example requires the following typemap entry. Consult perlxstypemap for more information about adding new typemaps for an extension. .PP .Vb 2 \& TYPEMAP \& Netconfig * T_PTROBJ .Ve .PP This example will be used with the following Perl statements. .PP .Vb 2 \& use RPC; \& $netconf = getnetconfigent("udp"); .Ve .PP When Perl destroys the object referenced by \f(CW$netconf\fR it will send the object to the supplied \s-1XSUB DESTROY\s0 function. Perl cannot determine, and does not care, that this object is a C struct and not a Perl object. In this sense, there is no difference between the object created by the \&\fIgetnetconfigent()\fR \s-1XSUB\s0 and an object created by a normal Perl subroutine. .SS "Safely Storing Static Data in \s-1XS\s0" .IX Subsection "Safely Storing Static Data in XS" Starting with Perl 5.8, a macro framework has been defined to allow static data to be safely stored in \s-1XS\s0 modules that will be accessed from a multi-threaded Perl. .PP Although primarily designed for use with multi-threaded Perl, the macros have been designed so that they will work with non-threaded Perl as well. .PP It is therefore strongly recommended that these macros be used by all \&\s-1XS\s0 modules that make use of static data. .PP The easiest way to get a template set of macros to use is by specifying the \f(CW\*(C`\-g\*(C'\fR (\f(CW\*(C`\-\-global\*(C'\fR) option with h2xs (see h2xs). .PP Below is an example module that makes use of the macros. .PP .Vb 4 \& #define PERL_NO_GET_CONTEXT \& #include "EXTERN.h" \& #include "perl.h" \& #include "XSUB.h" \& \& /* Global Data */ \& \& #define MY_CXT_KEY "BlindMice::_guts" XS_VERSION \& \& typedef struct { \& int count; \& char name[3][100]; \& } my_cxt_t; \& \& START_MY_CXT \& \& MODULE = BlindMice PACKAGE = BlindMice \& \& BOOT: \& { \& MY_CXT_INIT; \& MY_CXT.count = 0; \& strcpy(MY_CXT.name[0], "None"); \& strcpy(MY_CXT.name[1], "None"); \& strcpy(MY_CXT.name[2], "None"); \& } \& \& int \& newMouse(char * name) \& PREINIT: \& dMY_CXT; \& CODE: \& if (MY_CXT.count >= 3) { \& warn("Already have 3 blind mice"); \& RETVAL = 0; \& } \& else { \& RETVAL = ++ MY_CXT.count; \& strcpy(MY_CXT.name[MY_CXT.count \- 1], name); \& } \& OUTPUT: \& RETVAL \& \& char * \& get_mouse_name(index) \& int index \& PREINIT: \& dMY_CXT; \& CODE: \& if (index > MY_CXT.count) \& croak("There are only 3 blind mice."); \& else \& RETVAL = MY_CXT.name[index \- 1]; \& OUTPUT: \& RETVAL \& \& void \& CLONE(...) \& CODE: \& MY_CXT_CLONE; .Ve .PP \fI\s-1MY_CXT REFERENCE\s0\fR .IX Subsection "MY_CXT REFERENCE" .IP "\s-1MY_CXT_KEY\s0" 5 .IX Item "MY_CXT_KEY" This macro is used to define a unique key to refer to the static data for an \s-1XS\s0 module. The suggested naming scheme, as used by h2xs, is to use a string that consists of the module name, the string \*(L"::_guts\*(R" and the module version number. .Sp .Vb 1 \& #define MY_CXT_KEY "MyModule::_guts" XS_VERSION .Ve .IP "typedef my_cxt_t" 5 .IX Item "typedef my_cxt_t" This struct typedef \fImust\fR always be called \f(CW\*(C`my_cxt_t\*(C'\fR. The other \&\f(CW\*(C`CXT*\*(C'\fR macros assume the existence of the \f(CW\*(C`my_cxt_t\*(C'\fR typedef name. .Sp Declare a typedef named \f(CW\*(C`my_cxt_t\*(C'\fR that is a structure that contains all the data that needs to be interpreter-local. .Sp .Vb 3 \& typedef struct { \& int some_value; \& } my_cxt_t; .Ve .IP "\s-1START_MY_CXT\s0" 5 .IX Item "START_MY_CXT" Always place the \s-1START_MY_CXT\s0 macro directly after the declaration of \f(CW\*(C`my_cxt_t\*(C'\fR. .IP "\s-1MY_CXT_INIT\s0" 5 .IX Item "MY_CXT_INIT" The \s-1MY_CXT_INIT\s0 macro initializes storage for the \f(CW\*(C`my_cxt_t\*(C'\fR struct. .Sp It \fImust\fR be called exactly once, typically in a \s-1BOOT:\s0 section. If you are maintaining multiple interpreters, it should be called once in each interpreter instance, except for interpreters cloned from existing ones. (But see \*(L"\s-1MY_CXT_CLONE\*(R"\s0 below.) .IP "dMY_CXT" 5 .IX Item "dMY_CXT" Use the dMY_CXT macro (a declaration) in all the functions that access \&\s-1MY_CXT.\s0 .IP "\s-1MY_CXT\s0" 5 .IX Item "MY_CXT" Use the \s-1MY_CXT\s0 macro to access members of the \f(CW\*(C`my_cxt_t\*(C'\fR struct. For example, if \f(CW\*(C`my_cxt_t\*(C'\fR is .Sp .Vb 3 \& typedef struct { \& int index; \& } my_cxt_t; .Ve .Sp then use this to access the \f(CW\*(C`index\*(C'\fR member .Sp .Vb 2 \& dMY_CXT; \& MY_CXT.index = 2; .Ve .IP "aMY_CXT/pMY_CXT" 5 .IX Item "aMY_CXT/pMY_CXT" \&\f(CW\*(C`dMY_CXT\*(C'\fR may be quite expensive to calculate, and to avoid the overhead of invoking it in each function it is possible to pass the declaration onto other functions using the \f(CW\*(C`aMY_CXT\*(C'\fR/\f(CW\*(C`pMY_CXT\*(C'\fR macros, eg .Sp .Vb 5 \& void sub1() { \& dMY_CXT; \& MY_CXT.index = 1; \& sub2(aMY_CXT); \& } \& \& void sub2(pMY_CXT) { \& MY_CXT.index = 2; \& } .Ve .Sp Analogously to \f(CW\*(C`pTHX\*(C'\fR, there are equivalent forms for when the macro is the first or last in multiple arguments, where an underscore represents a comma, i.e. \f(CW\*(C`_aMY_CXT\*(C'\fR, \f(CW\*(C`aMY_CXT_\*(C'\fR, \f(CW\*(C`_pMY_CXT\*(C'\fR and \f(CW\*(C`pMY_CXT_\*(C'\fR. .IP "\s-1MY_CXT_CLONE\s0" 5 .IX Item "MY_CXT_CLONE" By default, when a new interpreter is created as a copy of an existing one (eg via \f(CW\*(C`threads\->create()\*(C'\fR), both interpreters share the same physical my_cxt_t structure. Calling \f(CW\*(C`MY_CXT_CLONE\*(C'\fR (typically via the package's \&\f(CW\*(C`CLONE()\*(C'\fR function), causes a byte-for-byte copy of the structure to be taken, and any future dMY_CXT will cause the copy to be accessed instead. .IP "\s-1MY_CXT_INIT_INTERP\s0(my_perl)" 5 .IX Item "MY_CXT_INIT_INTERP(my_perl)" .PD 0 .IP "dMY_CXT_INTERP(my_perl)" 5 .IX Item "dMY_CXT_INTERP(my_perl)" .PD These are versions of the macros which take an explicit interpreter as an argument. .PP Note that these macros will only work together within the \fIsame\fR source file; that is, a dMY_CTX in one source file will access a different structure than a dMY_CTX in another source file. .SS "Thread-aware system interfaces" .IX Subsection "Thread-aware system interfaces" Starting from Perl 5.8, in C/\*(C+ level Perl knows how to wrap system/library interfaces that have thread-aware versions (e.g. \fIgetpwent_r()\fR) into frontend macros (e.g. \fIgetpwent()\fR) that correctly handle the multithreaded interaction with the Perl interpreter. This will happen transparently, the only thing you need to do is to instantiate a Perl interpreter. .PP This wrapping happens always when compiling Perl core source (\s-1PERL_CORE\s0 is defined) or the Perl core extensions (\s-1PERL_EXT\s0 is defined). When compiling \s-1XS\s0 code outside of Perl core the wrapping does not take place. Note, however, that intermixing the _r\-forms (as Perl compiled for multithreaded operation will do) and the _r\-less forms is neither well-defined (inconsistent results, data corruption, or even crashes become more likely), nor is it very portable. .SH "EXAMPLES" .IX Header "EXAMPLES" File \f(CW\*(C`RPC.xs\*(C'\fR: Interface to some \s-1ONC+ RPC\s0 bind library functions. .PP .Vb 4 \& #define PERL_NO_GET_CONTEXT \& #include "EXTERN.h" \& #include "perl.h" \& #include "XSUB.h" \& \& #include \& \& typedef struct netconfig Netconfig; \& \& MODULE = RPC PACKAGE = RPC \& \& SV * \& rpcb_gettime(host="localhost") \& char *host \& PREINIT: \& time_t timep; \& CODE: \& ST(0) = sv_newmortal(); \& if( rpcb_gettime( host, &timep ) ) \& sv_setnv( ST(0), (double)timep ); \& \& Netconfig * \& getnetconfigent(netid="udp") \& char *netid \& \& MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_ \& \& void \& rpcb_DESTROY(netconf) \& Netconfig *netconf \& CODE: \& printf("NetconfigPtr::DESTROY\en"); \& free( netconf ); .Ve .PP File \f(CW\*(C`typemap\*(C'\fR: Custom typemap for \s-1RPC\s0.xs. (cf. perlxstypemap) .PP .Vb 2 \& TYPEMAP \& Netconfig * T_PTROBJ .Ve .PP File \f(CW\*(C`RPC.pm\*(C'\fR: Perl module for the \s-1RPC\s0 extension. .PP .Vb 1 \& package RPC; \& \& require Exporter; \& require DynaLoader; \& @ISA = qw(Exporter DynaLoader); \& @EXPORT = qw(rpcb_gettime getnetconfigent); \& \& bootstrap RPC; \& 1; .Ve .PP File \f(CW\*(C`rpctest.pl\*(C'\fR: Perl test program for the \s-1RPC\s0 extension. .PP .Vb 1 \& use RPC; \& \& $netconf = getnetconfigent(); \& $a = rpcb_gettime(); \& print "time = $a\en"; \& print "netconf = $netconf\en"; \& \& $netconf = getnetconfigent("tcp"); \& $a = rpcb_gettime("poplar"); \& print "time = $a\en"; \& print "netconf = $netconf\en"; .Ve .SH "CAVEATS" .IX Header "CAVEATS" \&\s-1XS\s0 code has full access to system calls including C library functions. It thus has the capability of interfering with things that the Perl core or other modules have set up, such as signal handlers or file handles. It could mess with the memory, or any number of harmful things. Don't. .PP Some modules have an event loop, waiting for user-input. It is highly unlikely that two such modules would work adequately together in a single Perl application. .PP In general, the perl interpreter views itself as the center of the universe as far as the Perl program goes. \s-1XS\s0 code is viewed as a help-mate, to accomplish things that perl doesn't do, or doesn't do fast enough, but always subservient to perl. The closer \s-1XS\s0 code adheres to this model, the less likely conflicts will occur. .PP One area where there has been conflict is in regards to C locales. (See perllocale.) perl, with one exception and unless told otherwise, sets up the underlying locale the program is running in to that passed into it from the environment. As of v5.20, this underlying locale is completely hidden from pure perl code outside the lexical scope of \&\f(CW\*(C`use\ locale\*(C'\fR; except a couple of function calls in the \s-1POSIX\s0 module of necessity use it. But the underlying locale, with that one exception is exposed to \s-1XS\s0 code, affecting all C library routines whose behavior is locale-dependent. The exception is the \&\f(CW\*(C`LC_NUMERIC\*(C'\fR locale category, and the reason it is an exception is that experience has shown that it can be problematic for \s-1XS\s0 code, whereas we have not had reports of problems with the other locale categories. And the reason for this one category being problematic is that the character used as a decimal point can vary. Many European languages use a comma, whereas English, and hence Perl are expecting a dot (U+002E: \s-1FULL STOP\s0). Many modules can handle only the radix character being a dot, and so perl attempts to make it so. Up through Perl v5.20, the attempt was merely to set \f(CW\*(C`LC_NUMERIC\*(C'\fR upon startup to the \f(CW"C"\fR locale. Any \&\fIsetlocale()\fR otherwise would change it; this caused some failures. Therefore, starting in v5.22, perl tries to keep \f(CW\*(C`LC_NUMERIC\*(C'\fR always set to \f(CW"C"\fR for \s-1XS\s0 code. .PP To summarize, here's what to expect and how to handle locales in \s-1XS\s0 code: .IP "Non-locale-aware \s-1XS\s0 code" 4 .IX Item "Non-locale-aware XS code" Keep in mind that even if you think your code is not locale-aware, it may call a C library function that is. Hopefully the man page for such a function will indicate that dependency, but the documentation is imperfect. .Sp The current locale is exposed to \s-1XS\s0 code except possibly \f(CW\*(C`LC_NUMERIC\*(C'\fR. There have not been reports of problems with these other categories. .Sp Up through v5.20, Perl initializes things on start-up so that \&\f(CW\*(C`LC_NUMERIC\*(C'\fR is set to the \*(L"C\*(R" locale. But if any code anywhere changes it, it will stay changed. This means that your module can't count on \f(CW\*(C`LC_NUMERIC\*(C'\fR being something in particular, and you can't expect floating point numbers (including version strings) to have dots in them. If you don't allow for a non-dot, your code could break if anyone anywhere changes the locale. For this reason, v5.22 is changing the behavior so that Perl tries to keep \f(CW\*(C`LC_NUMERIC\*(C'\fR in the \*(L"C\*(R" locale except around the operations internally where it should be something else. Misbehaving \s-1XS\s0 code will always be able to change the locale anyway, but the most common instance of this is checked for and handled. .IP "Locale-aware \s-1XS\s0 code" 4 .IX Item "Locale-aware XS code" If the locale from the user's environment is desired, there should be no need for \s-1XS\s0 code to set the locale except for \f(CW\*(C`LC_NUMERIC\*(C'\fR, as perl has already set it up. \s-1XS\s0 code should avoid changing the locale, as it can adversely affect other, unrelated, code and may not be thread safe. However, some alien libraries that may be called do set it, such as \&\f(CW\*(C`Gtk\*(C'\fR. This can cause problems for the perl core and other modules. Starting in v5.20.1, calling the function \&\fIsync_locale()\fR from \s-1XS\s0 should be sufficient to avoid most of these problems. Prior to this, you need a pure Perl segment that does this: .Sp .Vb 1 \& POSIX::setlocale(LC_ALL, POSIX::setlocale(LC_ALL)); .Ve .Sp Macros are provided for \s-1XS\s0 code to temporarily change to use the underlying \f(CW\*(C`LC_NUMERIC\*(C'\fR locale when necessary. An \s-1API\s0 is being developed for this, but has not yet been nailed down, but will be during the course of v5.21. Send email to for guidance. .SH "XS VERSION" .IX Header "XS VERSION" This document covers features supported by \f(CW\*(C`ExtUtils::ParseXS\*(C'\fR (also known as \f(CW\*(C`xsubpp\*(C'\fR) 3.13_01. .SH "AUTHOR" .IX Header "AUTHOR" Originally written by Dean Roehrich <\fIroehrich@cray.com\fR>. .PP Maintained since 1996 by The Perl Porters <\fIperlbug@perl.org\fR>.