Tutorial/One.pm

filter: Statementstmt 100% 3 / 3 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 100% 3 / 3 SCAR 0
CC
0
Cov
0%
CRAP 0
« Tutorial.pm ↑ Summary Tutorial/Two.pm »
1 package XS::Tutorial::One;
2 1 require XSLoader;
3  
4 1 XSLoader::load();
5 1 1;
6  
7 =head1 NAME
8  
9 XS::Tutorial::One - how to pass to and return basic values from C functions
10  
11 =head2 Introduction
12  
13 eXtendable Subroutines (XS) are subroutines written in C that are callable from
14 Perl code. There are two common reasons you'd want to use XS: there is a C
15 library you'd like to use with Perl, or you want to make a subroutine faster
16 by processing it in C instead of Perl.
17  
18 This tutorial will walk you through all the components needed to get up and
19 running with a basic XS example. There will be a lot of new terms and concepts:
20  
21 If you want to write XS, you have to learn it. Learning XS is very difficult
22 Steven W. McDougall
23  
24 Try not to get discouraged if things don't click right away: I promise you that
25 learning XS can be hugely rewarding: you'll develop the power to write lightning
26 fast code; get a better understanding of how Perl internals work, and be able to
27 integrate any C library you choose and use it from Perl.
28  
29 =head2 Components
30  
31 There are three basic components needed to write an xsub. The first is a Perl
32 module that will provide the namespace for any XS functions. This is all that's
33 needed:
34  
35 package XS::Tutorial::One;
36 require XSLoader;
37  
38 XSLoader::load();
39 1;
40  
41 This file should be saved as F<lib/XS/Tutorial/One.pm>. C<XSLoader::load> by
42 default searches for XS code that matches the package name it is called from*.
43  
44 Let's create a main distribution module too:
45  
46 package XS::Tutorial;
47 BEGIN { our $VERSION = 0.01 }
48 1;
49  
50 =encoding utf8
51  
52 =head1 NAME
53  
54 XS::Tutorial - documentation with examples for learning Perl XS
55  
56 =cut
57  
58 That file should be saved as F<lib/XS/Tutorial.pm>.
59  
60 The next thing we need is a .xs file which defines the xsubs to be loaded by
61 C<XS::Tutorial::One>:
62  
63 #define PERL_NO_GET_CONTEXT // we'll define thread context if necessary (faster)
64 #include "EXTERN.h" // globals/constant import locations
65 #include "perl.h" // Perl symbols, structures and constants definition
66 #include "XSUB.h" // xsubpp functions and macros
67 #include <stdlib.h> // rand()
68  
69 // additional c code goes here
70  
71 MODULE = XS::Tutorial::One PACKAGE = XS::Tutorial::One
72 PROTOTYPES: ENABLE
73  
74 # XS code goes here
75  
76 # XS comments begin with " #" to avoid them being interpreted as pre-processor
77 # directives
78  
79 unsigned int
80 rand()
81  
82 This file should be saved as F<lib/XS/Tutorial/One.xs>. The top half of the file
83 is pure C code. The line beginning C<MODULE = XS::Tutorial::One> indicates the
84 start of the XS code. This section will be parsed and compiled into C code by
85 C<xsubpp>.
86  
87 The C<MODULE> and C<PACKAGE> directives define the Perl module and package which
88 will load any xsubs we define. The line C<PROTOTYPES: ENABLE> tells C<xsubpp>
89 to define subroutine prototypes for any xsubs we create. This is usually what
90 you want: prototypes can help Perl catch compile time errors.
91  
92 The last two lines of the file are an xsub:
93  
94 unsigned int
95 rand()
96  
97 The first line defines the return type. The second line does two things: it
98 indicates the name of the C function to be called I<and> it defines the
99 signature of the xsub.
100  
101 In this case we're calling C<rand> and accepting no parameters. This isn't
102 Perl's built-in rand function, I<this> rand comes from stdlib.h.
103  
104 The final thing we need is a F<Makefile.PL> script - as XS code is compiled, we
105 need a tool to build it before we can use it:
106  
107 use 5.008005;
108 use ExtUtils::MakeMaker 7.12; # for XSMULTI option
109  
110 WriteMakefile(
111 NAME => 'XS::Tutorial',
112 VERSION_FROM => 'lib/XS/Tutorial.pm',
113 PREREQ_PM => { 'ExtUtils::MakeMaker' => '7.12' },
114 ABSTRACT_FROM => 'lib/XS/Tutorial.pm',
115 AUTHOR => 'David Farrell',
116 CCFLAGS => '-Wall -std=c99',
117 OPTIMIZE => '-O3',
118 LICENSE => 'freebsd',
119 XSMULTI => 1,
120 );
121  
122 The ExtUtils::MakeMaker L<docs|https://metacpan.org/pod/ExtUtils::MakeMaker> explain these options.
123  
124 But let's talk about C<XSMULTI>. This is a relatively new feature which allows
125 you to have separate .xs files for modules. By default EUMM assumes the xs
126 file matches the distribution name. In this case that would mean having a single
127 Tutorial.xs file, with multiple xs C<MODULE> and C<PACKAGE> declarations in it.
128 By using C<XSMULTI>, we can have multiple XS files, one for each module in the
129 distribution instead.
130  
131 *Actually it searches for compiled C code but the effect is the same.
132  
133 =head2 Building
134  
135 Now we should have four files:
136  
137 lib/XS/Tutorial.pm
138 lib/XS/Tutorial/One.pm
139 lib/XS/Tutorial/One.xs
140 Makefile.PL
141  
142 The following commands will build the distribution:
143  
144 $ perl Makefile.PL
145 $ make
146  
147 =head2 A minor essay to understand xsubpp generated C
148  
149 C<make> creates a bunch of files, but take a look at F<lib/XS/Tutorial/One.c>.
150 This is the output of C<xsubpp>. If you look closely enough, you can find the
151 lines of C code from F<lib/XS/Tutorial/One.xs> in there. But checkout what
152 happened to our C<rand> xsub:
153  
154 XS_EUPXS(XS_XS__Tutorial__One_rand); /* prototype to pass -Wmissing-prototypes */
155 XS_EUPXS(XS_XS__Tutorial__One_rand)
156 {
157 dVAR; dXSARGS;
158 if (items != 0)
159 croak_xs_usage(cv, "");
160 {
161 unsigned int RETVAL;
162 dXSTARG;
163  
164 RETVAL = rand();
165 XSprePUSH; PUSHu((UV)RETVAL);
166 }
167 XSRETURN(1);
168 }
169  
170 C<xsubpp> has replaced our XS code with some rather ugly C macros! These macros
171 are part of the Perl interpreter's C API. Many are documented in L<perlapi|http://perldoc.perl.org/perlapi.html>
172 and they are usually defined in C<XSUB.h> or C<perl.h> in the Perl source code.
173  
174 So what are these macros doing? At a high level, C<dVAR> and C<dXSARGS> setup
175 the global pointer stack and some local variables. C<items> is a count of the
176 arguments supplied to the xsub. As C<rand> is a void function, if this isn't
177 zero, it croaks. C<croak_xs_usage> takes a coderef and an args string. In this
178 context C<cv> is the xsub, and there are no args so the string is empty.
179  
180 Next the code declares C<RETVAL>, the return value of the xsub. C<dXTARG>
181 initializes the C<TARG> pointer. Next C<rand()> is called its return value
182 assigned to C<RETVAL>. C<XSprePUSH> moves the stack pointer back one,
183 and C<PUSHu> copies C<RETVAL> into C<TARG> and pushes it onto the global stack
184 pointer. C<XSRETURN> returns from the xsub, indicating how many arguments it
185 added to the stack, which in this case, is one.
186  
187 Writing XS, you usually don't need to study the generated C code, but it's
188 helpful to have an awareness of the process.
189  
190 =head2 Installing
191  
192 Now the code is compiled, install it with:
193  
194 $ make install
195  
196 If you're using system Perl, you may need to use C<sudo> to install. Now we can
197 test the module using a one liner:
198  
199 $ perl -MXS::Tutorial::One -E 'say XS::Tutorial::One::rand()'
200 1804289383
201  
202 It works! Did you try running it twice though?
203  
204 $ perl -MXS::Tutorial::One -E 'say XS::Tutorial::One::rand()'
205 1804289383
206  
207 We get the same pseudorandom sequence each time... We need to call C<srand> to
208 seed the sequence. That function is already provided by C<stdlib.h>, so all we
209 need to do is append the following text to F<lib/XS/Tutorial/One.xs>:
210  
211 void
212 srand(seed)
213 unsigned int seed
214  
215 This xsub is different to the first one: its return type is C<void> which
216 means it returns nothing. It also includes a parameter called C<seed> in its
217 signature, and the last line defines it as an unsigned int.
218  
219 Rebuild and install the distribution:
220  
221 $ make && make install
222  
223 Now we can seed the pseudorandom sequence by calling C<srand> before C<rand>:
224  
225 $ perl -MXS::Tutorial::One -E 'XS::Tutorial::One::srand(777);\
226 say XS::Tutorial::One::rand()'
227 947371799
228  
229 We used a lucky (777) seed number, and C<rand> emitted a different number, yay!
230  
231 =head2 Did we beat Perl?
232  
233 As you know by now, xsubs are often faster than pure Perl code. We've built two
234 xsubs for C<rand> and C<srand>, which are also available as built-in functions
235 in Perl. Do you think the xsubs are faster? Here's a benchmark from my machine:
236  
237 Rate xs_rand bi_rand
238 xs_rand 15691577/s -- -64%
239 bi_rand 43095739/s 175% --
240  
241 Oh no! Despite our C<rand> xsub directly calling the C C<stdlib> function, it's
242 miles slower than Perl's built-in C<rand>. This isn't because xsubs are slow,
243 rather that Perl's built-in functions are really fast.
244  
245 =head2 Tests
246  
247 Instead of running one liners to check our code works, we can write unit tests.
248 Here's a basic script:
249  
250 #!/usr/bin/perl
251 use Test::More;
252  
253 BEGIN { use_ok 'XS::Tutorial::One' }
254  
255 ok my $rand = XS::Tutorial::One::rand(), 'rand()';
256 like $rand, qr/^\d+$/, 'rand() returns a number';
257  
258 ok !defined XS::Tutorial::One::srand(5), 'srand()';
259 ok $rand ne XS::Tutorial::One::rand(), 'after srand, rand returns different number';
260 done_testing;
261  
262 Save this file as F<t/one.t>. Assuming you built and installed the distribution
263 already, you can just do:
264  
265 $ perl t/one.t
266 ok 1 - use XS::Tutorial::One;
267 ok 2 - rand()
268 ok 3 - rand() returns a number
269 ok 4 - srand()
270 ok 5 - after srand, rand returns different number
271 1..5
272  
273 Now when building the distribution in the future, you should do:
274  
275 $ perl Makefile.PL && make && make test
276  
277 This will rebuild and test the distribution. Because XS code is compiled,
278 writing tests and using that one liner, you can quickly cycle through coding
279 and testing.
280  
281 Don't forget to add Test::More to the C<PREREQ_PM> entry in F<Makefile.PL>. When
282 you don't have a specific minimum version, you can just use 0:
283  
284 PREREQ_PM => { 'Test::More' => 0, 'ExtUtils::MakeMaker' => '7.12' },
285  
286 =head2 Cleanup
287  
288 Building distributions generates a lot of temporary files. ExtUtils::MakeMaker
289 provides a clean routine:
290  
291 $ make clean
292  
293 This will delete all the build files and reset the working directory to normal.
294  
295 =head2 References
296  
297 =over 4
298  
299 =item * XS Mechanics by Steven W. McDougall is my second favorite :) XS L<tutorial|http://world.std.com/~swmcd/steven/perl/pm/xs/intro/>
300  
301 =item * L<perlxs|http://perldoc.perl.org/perlxs.html> defines the keywords recognized by L<xsubpp|https://metacpan.org/pod/distribution/ExtUtils-ParseXS/lib/ExtUtils/xsubpp>
302  
303 =item * L<perlapi|http://perldoc.perl.org/perlapi.html> : C macros used to interact with Perl data structures (and the interpreter)
304  
305 =item * The L<stdlib.h|http://pubs.opengroup.org/onlinepubs/9699919799/> man page defines the C standard library functions and types
306  
307 =item * For writing Makefile.PL files: ExtUtils::MakeMaker L<docs|https://metacpan.org/pod/ExtUtils::MakeMaker> are invaluable
308  
309 =item * Perl's built-in L<rand|http://perldoc.perl.org/functions/rand.html> and <srand|http://perldoc.perl.org/functions/srand.html> functions
310  
311 =back
312  
313 =cut
« Tutorial.pm ↑ Summary Tutorial/Two.pm »