NAMEperlxs - XS language reference manual
DESCRIPTION
IntroductionXS 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 XS interface is combined with the library to create a new library which can then be either dynamically loaded or statically linked into perl. The XS interface description is written in the XS language and is the core component of the Perl extension interface. An XSUB forms the basic unit of the XS interface. After compilation by the xsubpp compiler, each XSUB amounts to a C function definition which will provide the glue between Perl calling conventions and C calling conventions. 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. 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. 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. XS comes to the rescue here: instead of writing this glue C code in long-hand, one can write a more concise short-hand description of what should be done by the glue, and let the XS compiler xsubpp handle the rest. The XS 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 XSUB
declaration is almost identical to a declaration of a C function (in K&R
style). In such circumstances, there is another tool called The XS compiler is called xsubpp. This compiler creates the constructs necessary to let an XSUB manipulate Perl values, and creates the glue necessary to let Perl call the XSUB. The compiler uses typemaps 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. A file in XS format starts with a C language section which goes until the
first See the perlxstut manpage for a tutorial on the whole extension creation process. Note: For some extensions, Dave Beazley's SWIG system may provide a significantly more convenient mechanism for creating the extension glue code. See http://www.swig.org/ for more information.
On The RoadMany of the examples which follow will concentrate on creating an interface
between Perl and the ONC+ RPC bind library functions. The bool_t rpcb_gettime(const char *host, time_t *timep); From C this function will be called with the following statements. #include <rpc/rpc.h> bool_t status; time_t timep; status = rpcb_gettime( "localhost", &timep ); If an XSUB is created to offer a direct translation between this function and Perl, then this XSUB will be used from Perl with the following code. The $status and $timep variables will contain the output of the function. use RPC; $status = rpcb_gettime( "localhost", $timep ); The following XS file shows an XS subroutine, or XSUB, which
demonstrates one possible interface to the #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include <rpc/rpc.h> MODULE = RPC PACKAGE = RPC bool_t rpcb_gettime(host,timep) char *host time_t &timep OUTPUT: timep 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 package RPC; require Exporter; require DynaLoader; @ISA = qw(Exporter DynaLoader); @EXPORT = qw( rpcb_gettime ); bootstrap RPC; 1; Throughout this document a variety of interfaces to the
The Anatomy of an XSUBThe simplest XSUBs consist of 3 parts: a description of the return value, the name of the XSUB routine and the names of its arguments, and a description of types or formats of the arguments. The following XSUB allows a Perl program to access a C library function called sin(). The XSUB will imitate the C function which takes a single argument and returns a single value. double sin(x) double x Optionally, one can merge the description of types and the list of argument names, rewriting this as double sin(double x) This makes this XSUB look similar to an ANSI C declaration. An optional semicolon is allowed after the argument list, as in double sin(double x); Parameters with C pointer types can have different semantic: C functions with similar declarations bool string_looks_as_a_number(char *s); bool make_char_uppercase(char *c); are used in absolutely incompatible manner. Parameters to these functions could be described xsubpp like this: char * s char &c Both these XS declarations correspond to the It is convenient to think that the indirection operator
The function name and the return type must be placed on separate lines and should be flush left-adjusted. INCORRECT CORRECT double sin(x) double double x sin(x) double x 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. CORRECT double sin(x) double x More complicated XSUBs may contain many other sections. Each section of an XSUB starts with the corresponding keyword, such as INIT: or CLEANUP:. However, the first two lines of an XSUB 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 INPUT: section unless explicitly marked with another keyword. (See The INPUT: Keyword.) An XSUB section continues until another section-start keyword is found.
The Argument StackThe Perl argument stack is used to store the values which are sent as parameters to the XSUB and to store the XSUB'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. XSUBs refer to their stack arguments with the macro ST(x), where x refers to a position in this XSUB's part of the stack. Position 0 for that function would be known to the XSUB as ST(0). The XSUB's incoming parameters and outgoing return values always begin at ST(0). For many simple cases the xsubpp 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.
The RETVAL VariableThe RETVAL variable is a special C variable that is declared automatically
for you. The C type of RETVAL matches the return type of the C library
function. The xsubpp compiler will declare this variable in each XSUB
with non- If the XSUB has a return type of If PPCODE: directive is not used, Older versions of this document recommended to use
The MODULE KeywordThe MODULE keyword is used to start the XS code and to specify the package of the functions which are being defined. All text preceding the first MODULE keyword is considered C code and is passed through to the output with POD stripped, but otherwise untouched. Every XS 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 MODULE statement in the XS source files. The value of MODULE should always remain constant within the same XS file, though this is not required. The following example will start the XS code and will place all functions in a package named RPC. MODULE = RPC
The PACKAGE KeywordWhen functions within an XS source file must be separated into packages the PACKAGE keyword should be used. This keyword is used with the MODULE keyword and must follow immediately after it when used. 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 ] 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.
The PREFIX KeywordThe PREFIX keyword designates prefixes which should be
removed from the Perl function names. If the C function is
This keyword should follow the PACKAGE keyword when used. If PACKAGE is not used then PREFIX should follow the MODULE keyword. MODULE = RPC PREFIX = rpc_ MODULE = RPC PACKAGE = RPCB PREFIX = rpcb_
The OUTPUT: KeywordThe OUTPUT: keyword indicates that certain function parameters should be
updated (new values made visible to Perl) when the XSUB terminates or that
certain values should be returned to the calling Perl function. For
simple functions which have no CODE: or PPCODE: section,
such as the This keyword will normally be used to complement the CODE: keyword. The RETVAL variable is not recognized as an output variable when the CODE: keyword is present. The OUTPUT: keyword is used in this situation to tell the compiler that RETVAL really is an output variable. The OUTPUT: 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. bool_t rpcb_gettime(host,timep) char *host time_t &timep OUTPUT: timep The OUTPUT: keyword will also allow an output parameter to be mapped to a matching piece of code rather than to a typemap. bool_t rpcb_gettime(host,timep) char *host time_t &timep OUTPUT: timep sv_setnv(ST(1), (double)timep); xsubpp emits an automatic
The NO_OUTPUT KeywordThe NO_OUTPUT can be placed as the first token of the XSUB. This keyword
indicates that while the C subroutine we provide an interface to has
a non- With this keyword present The RETVAL Variable 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. This keyword makes sense only if NO_OUTPUT int delete_file(char *name) POST_CALL: if (RETVAL != 0) croak("Error %d while deleting file '%s'", RETVAL, name); Here the generated XS function returns nothing on success, and will
The CODE: KeywordThis keyword is used in more complicated XSUBs which require special handling for the C function. The RETVAL variable is still declared, but it will not be returned unless it is specified in the OUTPUT: section. The following XSUB is for a C function which requires special handling of its parameters. The Perl usage is given first. $status = rpcb_gettime( "localhost", $timep ); The XSUB follows. bool_t rpcb_gettime(host,timep) char *host time_t timep CODE: RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL
The INIT: KeywordThe INIT: keyword allows initialization to be inserted into the XSUB before the compiler generates the call to the C function. Unlike the CODE: keyword above, this keyword does not affect the way the compiler handles RETVAL. bool_t rpcb_gettime(host,timep) char *host time_t &timep INIT: printf("# Host is %s\n", host ); OUTPUT: timep Another use for the INIT: section is to check for preconditions before making a call to the C function: 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");
The NO_INIT KeywordThe NO_INIT keyword is used to indicate that a function parameter is being used only as an output value. The xsubpp 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. NO_INIT 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. The following example shows a variation of the bool_t rpcb_gettime(host,timep) char *host time_t &timep = NO_INIT OUTPUT: timep
Initializing Function ParametersC function parameters are normally initialized with their values from
the argument stack (which in turn contains the parameters that were
passed to the XSUB from Perl). The typemaps contain the
code segments which are used to translate the Perl values to
the C parameters. The programmer, however, is allowed to
override the typemaps and supply alternate (or additional)
initialization code. Initialization code starts with the first
The following code demonstrates how to supply initialization code for
function parameters. The initialization code is eval'd within double
quotes by the compiler before it is added to the output so anything
which should be interpreted literally [mainly bool_t rpcb_gettime(host,timep) char *host = (char *)SvPV($arg,PL_na); time_t &timep = 0; OUTPUT: timep This should not be used to supply default values for parameters. One would normally use this when a function parameter must be processed by another library function before it can be used. Default parameters are covered in the next section. If the initialization begins with Here's a truly obscure example: bool_t rpcb_gettime(host,timep) time_t &timep ; /* \$v{timep}=@{[$v{timep}=$arg]} */ char *host + SvOK($v{timep}) ? SvPV($arg,PL_na) : NULL; OUTPUT: timep The construct
Default Parameter ValuesDefault values for XSUB arguments can be specified by placing an
assignment statement in the parameter list. The default value may
be a number, a string or the special string To allow the XSUB for $status = rpcb_gettime( $timep, $host ); $status = rpcb_gettime( $timep ); The XSUB will look like the code which follows. A CODE:
block is used to call the real bool_t rpcb_gettime(timep,host="localhost") char *host time_t timep = NO_INIT CODE: RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL
The PREINIT: KeywordThe PREINIT: keyword allows extra variables to be declared immediately before or after the declarations of the parameters from the INPUT: section are emitted. If a variable is declared inside a CODE: section it will follow any typemap
code that is emitted for the input parameters. This may result in the
declaration ending up after C code, which is C syntax error. Similar
errors may happen with an explicit In such cases, to force an additional variable to be declared together with declarations of other variables, place the declaration into a PREINIT: section. The PREINIT: keyword may be used one or more times within an XSUB. The following examples are equivalent, but if the code is using complex typemaps then the first example is safer. bool_t rpcb_gettime(timep) time_t timep = NO_INIT PREINIT: char *host = "localhost"; CODE: RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL For this particular case an INIT: keyword would generate the same C code as the PREINIT: keyword. Another correct, but error-prone example: bool_t rpcb_gettime(timep) time_t timep = NO_INIT CODE: char *host = "localhost"; RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL Another way to declare bool_t rpcb_gettime(timep) time_t timep = NO_INIT CODE: { char *host = "localhost"; RETVAL = rpcb_gettime( host, &timep ); } OUTPUT: timep RETVAL The ability to put additional declarations before the typemap entries are processed is very handy in the cases when typemap conversions manipulate some global state: MyObject mutate(o) PREINIT: MyState st = global_state; INPUT: MyObject o; CLEANUP: reset_to(global_state, st); Here we suppose that conversion to There is another way to trade clarity for compactness: INPUT sections allow
declaration of C variables which do not appear in the parameter list of
a subroutine. Thus the above code for MyObject mutate(o) MyState st = global_state; MyObject o; CLEANUP: reset_to(global_state, st); and the code for bool_t rpcb_gettime(timep) time_t timep = NO_INIT char *host = "localhost"; C_ARGS: host, &timep OUTPUT: timep RETVAL
The SCOPE: KeywordThe SCOPE: keyword allows scoping to be enabled for a particular XSUB. If enabled, the XSUB will invoke ENTER and LEAVE automatically. To support potentially complex type mappings, if a typemap entry used
by an XSUB contains a comment like To enable scoping: SCOPE: ENABLE To disable scoping: SCOPE: DISABLE
The INPUT: KeywordThe XSUB's parameters are usually evaluated immediately after entering the XSUB. The INPUT: keyword can be used to force those parameters to be evaluated a little later. The INPUT: keyword can be used multiple times within an XSUB and can be used to list one or more input variables. This keyword is used with the PREINIT: keyword. The following example shows how the input parameter bool_t rpcb_gettime(host,timep) char *host PREINIT: time_t tt; INPUT: time_t timep CODE: RETVAL = rpcb_gettime( host, &tt ); timep = tt; OUTPUT: timep RETVAL The next example shows each input parameter evaluated late. bool_t rpcb_gettime(host,timep) PREINIT: time_t tt; INPUT: char *host PREINIT: char *h; INPUT: time_t timep CODE: h = host; RETVAL = rpcb_gettime( h, &tt ); timep = tt; OUTPUT: timep RETVAL Since INPUT sections allow declaration of C variables which do not appear in the parameter list of a subroutine, this may be shortened to: bool_t rpcb_gettime(host,timep) time_t tt; char *host; char *h = host; time_t timep; CODE: RETVAL = rpcb_gettime( h, &tt ); timep = tt; OUTPUT: timep RETVAL (We used our knowledge that input conversion for
The IN/OUTLIST/IN_OUTLIST/OUT/IN_OUT KeywordsIn the list of parameters for an XSUB, one can precede parameter names
by the Parameters preceded by Parameters preceded by Parameters preceded by The return list of the generated Perl function consists of the C return value
from the function (unless the XSUB is of For example, an XSUB void day_month(OUTLIST day, IN unix_time, OUTLIST month) int day int unix_time int month should be used from Perl as my ($day, $month) = day_month(time); The C signature of the corresponding function should be void day_month(int *day, int unix_time, int *month); The void day_month(OUTLIST int day, int unix_time, OUTLIST int month) (here the optional The The void day_month(OUT int day, int unix_time, OUT int month); or void day_month(day, unix_time, month) int &day = NO_INIT int unix_time int &month = NO_INIT OUTPUT: day month However, the generated Perl function is called in very C-ish style: my ($day, $month); day_month($day, time, $month);
Variable-length Parameter ListsXSUBs can have variable-length parameter lists by specifying an ellipsis
The host parameter for the $status = rpcb_gettime( $timep, $host ); $status = rpcb_gettime( $timep ); The XS code, with ellipsis, follows. bool_t rpcb_gettime(timep, ...) time_t timep = NO_INIT PREINIT: char *host = "localhost"; STRLEN n_a; CODE: if( items > 1 ) host = (char *)SvPV(ST(1), n_a); RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL
The C_ARGS: KeywordThe C_ARGS: keyword allows creating of XSUBS which have different calling sequence from Perl than from C, without a need to write CODE: or PPCODE: section. The contents of the C_ARGS: paragraph is put as the argument to the called C function without any change. For example, suppose that a C function is declared as symbolic nth_derivative(int n, symbolic function, int flags); and that the default flags are kept in a global C variable
$second_deriv = $function->nth_derivative(2); To do this, declare the XSUB as symbolic nth_derivative(function, n) symbolic function int n C_ARGS: n, function, default_flags
The PPCODE: KeywordThe PPCODE: keyword is an alternate form of the CODE: keyword and is used to tell the xsubpp compiler that the programmer is supplying the code to control the argument stack for the XSUBs return values. Occasionally one will want an XSUB to return a list of values rather than a single value. In these cases one must use PPCODE: and then explicitly push the list of values on the stack. The PPCODE: and CODE: keywords should not be used together within the same XSUB. The actual difference between PPCODE: and CODE: sections is in the
initialization of The generated trailer for a CODE: section ensures that the number of return
values Perl will see is either 0 or 1 (depending on the Note that macros The following XSUB will call the C 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))); Notice that the programmer must supply the C code necessary
to have the real The The Now the ($status, $timep) = rpcb_gettime("localhost"); When handling output parameters with a PPCODE section, be sure to handle 'set' magic properly. See the perlguts manpage for details about 'set' magic.
Returning Undef And Empty ListsOccasionally the programmer will want to return simply
$timep = rpcb_gettime( "localhost" ); The following XSUB uses the 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); The next example demonstrates how one would place an explicit undef in the return value, should the need arise. 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); } else{ ST(0) = &PL_sv_undef; } To return an empty list one must use a PPCODE: block and then not push return values on the stack. 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. */ } Some people may be inclined to include an explicit Since int rpcb_gettime(host) char *host PREINIT: time_t timep; CODE: RETVAL = rpcb_gettime( host, &timep ); if (RETVAL == 0) XSRETURN_UNDEF; OUTPUT: RETVAL In fact, one can put this check into a POST_CALL: section as well. Together with PREINIT: simplifications, this leads to: int rpcb_gettime(host) char *host time_t timep; POST_CALL: if (RETVAL == 0) XSRETURN_UNDEF;
The REQUIRE: KeywordThe REQUIRE: keyword is used to indicate the minimum version of the xsubpp compiler needed to compile the XS module. An XS module which contains the following statement will compile with only xsubpp version 1.922 or greater: REQUIRE: 1.922
The CLEANUP: KeywordThis keyword can be used when an XSUB requires special cleanup procedures before it terminates. When the CLEANUP: keyword is used it must follow any CODE:, PPCODE:, or OUTPUT: blocks which are present in the XSUB. The code specified for the cleanup block will be added as the last statements in the XSUB.
The POST_CALL: KeywordThis keyword can be used when an XSUB requires special procedures executed after the C subroutine call is performed. When the POST_CALL: keyword is used it must precede OUTPUT: and CLEANUP: blocks which are present in the XSUB. The POST_CALL: block does not make a lot of sense when the C subroutine call is supplied by user by providing either CODE: or PPCODE: section.
The BOOT: KeywordThe BOOT: keyword is used to add code to the extension's bootstrap function. The bootstrap function is generated by the xsubpp compiler and normally holds the statements necessary to register any XSUBs with Perl. With the BOOT: keyword the programmer can tell the compiler to add extra statements to the bootstrap function. This keyword may be used any time after the first MODULE keyword and should appear on a line by itself. The first blank line after the keyword will terminate the code block. BOOT: # The following message will be printed when the # bootstrap function executes. printf("Hello from the bootstrap!\n");
The VERSIONCHECK: KeywordThe VERSIONCHECK: keyword corresponds to xsubpp's To enable version checking: VERSIONCHECK: ENABLE To disable version checking: VERSIONCHECK: DISABLE
The PROTOTYPES: KeywordThe PROTOTYPES: keyword corresponds to xsubpp's To enable prototypes: PROTOTYPES: ENABLE To disable prototypes: PROTOTYPES: DISABLE
The PROTOTYPE: KeywordThis keyword is similar to the PROTOTYPES: keyword above but can be used to force xsubpp to use a specific prototype for the XSUB. This keyword overrides all other prototype options and keywords but affects only the current XSUB. Consult Prototypes in the perlsub manpage for information about Perl prototypes. bool_t rpcb_gettime(timep, ...) time_t timep = NO_INIT PROTOTYPE: $;$ PREINIT: char *host = "localhost"; STRLEN n_a; CODE: if( items > 1 ) host = (char *)SvPV(ST(1), n_a); RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL
The ALIAS: KeywordThe ALIAS: keyword allows an XSUB 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 The following example will create aliases bool_t rpcb_gettime(host,timep) char *host time_t &timep ALIAS: FOO::gettime = 1 BAR::getit = 2 INIT: printf("# ix = %d\n", ix ); OUTPUT: timep
The INTERFACE: KeywordThis keyword declares the current XSUB 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 XSUB. For example, if you have 4 C functions multiply(), divide(), add(),
symbolic f(symbolic, symbolic); you can make them all to use the same XSUB using this: symbolic interface_s_ss(arg1, arg2) symbolic arg1 symbolic arg2 INTERFACE: multiply divide add subtract (This is the complete XSUB code for 4 Perl functions!) Four generated Perl function share names with corresponding C functions. The advantage of this approach comparing to ALIAS: keyword is that there
is no need to code a switch statement, each Perl function (which shares
the same XSUB) knows which C function it should call. Additionally, one
can attach an extra function CV *mycv = newXSproto("Symbolic::remainder", XS_Symbolic_interface_s_ss, __FILE__, "$$"); XSINTERFACE_FUNC_SET(mycv, remainder); say, from another XSUB. (This example supposes that there was no
INTERFACE_MACRO: section, otherwise one needs to use something else instead of
The INTERFACE_MACRO: KeywordThis keyword allows one to define an INTERFACE using a different way
to extract a function pointer from an XSUB. 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, The default value is Suppose that in the previous example functions pointers for
multiply(), divide(), add(), #define XSINTERFACE_FUNC_BYOFFSET(ret,cv,f) \ ((XSINTERFACE_CVT(ret,))fp[CvXSUBANY(cv).any_i32]) #define XSINTERFACE_FUNC_BYOFFSET_set(cv,f) \ CvXSUBANY(cv).any_i32 = CAT2( f, _off ) in C section, symbolic interface_s_ss(arg1, arg2) symbolic arg1 symbolic arg2 INTERFACE_MACRO: XSINTERFACE_FUNC_BYOFFSET XSINTERFACE_FUNC_BYOFFSET_set INTERFACE: multiply divide add subtract in XSUB section.
The INCLUDE: KeywordThis keyword can be used to pull other files into the XS module. The other files may have XS code. INCLUDE: can also be used to run a command to generate the XS code to be pulled into the module. The file Rpcb1.xsh contains our bool_t rpcb_gettime(host,timep) char *host time_t &timep OUTPUT: timep The XS module can use INCLUDE: to pull that file into it. INCLUDE: Rpcb1.xsh If the parameters to the INCLUDE: keyword are followed by a pipe ( INCLUDE: cat Rpcb1.xsh |
The CASE: KeywordThe CASE: keyword allows an XSUB to have multiple distinct parts with each part acting as a virtual XSUB. CASE: is greedy and if it is used then all other XS keywords must be contained within a CASE:. This means nothing may precede the first CASE: in the XSUB and anything following the last CASE: is included in that case. A CASE: might switch via a parameter of the XSUB, via the long rpcb_gettime(a,b) CASE: ix == 1 ALIAS: x_gettime = 1 INPUT: # 'a' is timep, 'b' is host char *b time_t a = NO_INIT CODE: RETVAL = rpcb_gettime( b, &a ); OUTPUT: a RETVAL CASE: # 'a' is host, 'b' is timep char *a time_t &b = NO_INIT OUTPUT: b RETVAL That function can be called with either of the following statements. Note the different argument lists. $status = rpcb_gettime( $host, $timep ); $status = x_gettime( $timep, $host );
The & Unary OperatorThe This is useful to avoid a CODE: block for a C function which takes a parameter
by reference. Typically, the parameter should be not a pointer type (an
The following XSUB will generate incorrect C code. The xsubpp compiler will
turn this into code which calls bool_t rpcb_gettime(host,timep) char *host time_t timep OUTPUT: timep That problem is corrected by using the bool_t rpcb_gettime(host,timep) char *host time_t &timep OUTPUT: timep
Inserting POD, Comments and C Preprocessor DirectivesC preprocessor directives are allowed within BOOT:, PREINIT: INIT:, CODE:,
PPCODE:, POST_CALL:, and CLEANUP: blocks, as well as outside the functions.
Comments are allowed anywhere after the MODULE keyword. The compiler will
pass the preprocessor directives through untouched and will remove the
commented lines. POD documentation is allowed at any point, both in the
C and XS language sections. POD must be terminated with a Comments can be added to XSUBs by placing a If you use preprocessor directives to choose one of two versions of a function, use #if ... version1 #else /* ... version2 */ #endif and not #if ... version1 #endif #if ... version2 #endif because otherwise xsubpp 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.
Using XS With C++If an XSUB name contains If the return type of the XSUB includes The next examples will use the following C++ class. class color { public: color(); ~color(); int blue(); void set_blue( int ); private: int c_blue; }; The XSUBs for the int color::blue() void color::set_blue( val ) int val Both Perl functions will expect an object as the first parameter. In the
generated C++ code the object is called RETVAL = THIS->blue(); THIS->set_blue( val ); You could also write a single get/set method using an optional argument: int color::blue( val = NO_INIT ) int val PROTOTYPE $;$ CODE: if (items > 1) THIS->set_blue( val ); RETVAL = THIS->blue(); OUTPUT: RETVAL If the function's name is DESTROY then the C++ void color::DESTROY() will look like this: color *THIS = ...; // Initialized as in typemap delete THIS; If the function's name is new then the C++ color * color::new() The generated C++ code will call RETVAL = new color(); The following is an example of a typemap that could be used for this C++ example. TYPEMAP color * O_OBJECT OUTPUT # The Perl object is blessed into 'CLASS', 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; }
Interface StrategyWhen designing an interface between Perl and a C library a straight
translation from C to XS (such as created by Identify the C functions with input/output or output parameters. The XSUBs for these functions may be able to return lists to Perl. 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 INIT: section to report the failure. For failures detectable after the C function returns one may want to use a POST_CALL: section to process the failure. In more complicated cases use CODE: or PPCODE: sections. 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 typedef int negative_is_failure; near the beginning of XS file, and create an OUTPUT typemap entry
for Identify which values are used by only the C and XSUB 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. 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 XS with the 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 If the same C type is used in several different contexts which require
different translations,
Perl Objects And C StructuresWhen dealing with C structures one should select either T_PTROBJ or T_PTRREF for the XS 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 XSUB will attempt to verify that the Perl object is of the expected type. The following XS code shows the struct netconfig *getnetconfigent(const char *netid); A 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\n"); free( netconf ); This example requires the following typemap entry. Consult the typemap section for more information about adding new typemaps for an extension. TYPEMAP Netconfig * T_PTROBJ This example will be used with the following Perl statements. use RPC; $netconf = getnetconfigent("udp"); When Perl destroys the object referenced by $netconf it will send the
object to the supplied XSUB DESTROY 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
The TypemapThe typemap is a collection of code fragments which are used by the xsubpp
compiler to map C function parameters and values to Perl values. The
typemap file may consist of three sections labelled The default typemap in the Most extensions which require a custom typemap will need only the TYPEMAP
section of the typemap file. The custom typemap used in the
TYPEMAP Netconfig *<tab>T_PTROBJ Here's a more complicated example: suppose that you wanted typedef struct netconfig * Net_Config; And then provide a typemap entry TYPEMAP Net_Config T_PTROBJ_SPECIAL INPUT T_PTROBJ_SPECIAL if (sv_derived_from($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")) { IV tmp = SvIV((SV*)SvRV($arg)); $var = ($type) tmp; } else croak(\"$var is not of type ${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\") OUTPUT T_PTROBJ_SPECIAL sv_setref_pv($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\", (void*)$var); The INPUT and OUTPUT sections substitute underscores for double-colons on the fly, giving the desired effect. This example demonstrates some of the power and versatility of the typemap facility.
EXAMPLESFile #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include <rpc/rpc.h> 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\n"); free( netconf ); File TYPEMAP Netconfig * T_PTROBJ File package RPC; require Exporter; require DynaLoader; @ISA = qw(Exporter DynaLoader); @EXPORT = qw(rpcb_gettime getnetconfigent); bootstrap RPC; 1; File use RPC; $netconf = getnetconfigent(); $a = rpcb_gettime(); print "time = $a\n"; print "netconf = $netconf\n"; $netconf = getnetconfigent("tcp"); $a = rpcb_gettime("poplar"); print "time = $a\n"; print "netconf = $netconf\n";
XS VERSIONThis document covers features supported by
AUTHOROriginally written by Dean Roehrich <roehrich@cray.com>. Maintained since 1996 by The Perl Porters <perlbug@perl.org>.
|