Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
XS (Perl)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Example code== The following shows an XS module that exposes a function <code>concat()</code> to concatenate two strings (i.e., the equivalent of Perl’s <code>.</code> operator). <syntaxhighlight lang="c"> #define PERL_NO_GET_CONTEXT #include "EXTERN.h" #include "perl.h" #include "XSUB.h" SV* _do_sv_catsv (pTHX_ SV* one_sv, SV* two_sv ) { SV* one_copy = newSVsv(one_sv); sv_catsv(one_copy, two_sv); return one_copy; } </syntaxhighlight> <syntaxhighlight lang="c"> MODULE = Demo::XSModule PACKAGE = Demo::XSModule SV* concat (SV* one_sv, SV* two_sv) CODE: SV* to_return = _do_sv_catsv( aTHX_ one_sv, two_sv ); RETVAL = to_return; OUTPUT: RETVAL </syntaxhighlight> The first four lines (<code>#define</code> and <code>#include</code> statements) are standard boilerplate. After then follow any number of plain C functions that are callable locally. The section that starts with <code>MODULE = Demo::XSModule</code> defines the Perl interface to this code using the actual XS macro language. Note that the C code under the <code>CODE:</code> section calls the <code>_do_sv_catsv()</code> pure-C function that was defined in the prior section. Perl’s documentation explains the meaning and purpose of all of the “special” symbols (e.g., <code>aTHX_</code> and <code>RETVAL</code>) shown above. To make this module available to Perl it must be compiled. Build tools like [https://perldoc.perl.org/ExtUtils::MakeMaker ExtUtils::MakeMaker] can do this automatically. (To build manually: the [https://perldoc.perl.org/xsubpp xsubpp] tool parses an XS module and outputs C source code; that source code is then compiled to a shared library and placed in a directory where Perl can find it.) Perl code then uses a module like [https://perldoc.perl.org/XSLoader XSLoader] to load the compiled XS module. At this point Perl can call <code>Demo::XSModule::concat('foo', 'bar')</code> and receive back a string <code>foobar</code>, as if <code>concat()</code> were itself written in Perl. Note that, for building Perl interfaces to preexisting C libraries, the [[h2xs]]{{elucidate|date=January 2017}} can automate much of the creation of the XS file itself.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)