Writing C Modules with XS
After adding this XSUB to the end of MIME.xs, I'll edit my test.pl to read
as follows:
use Test::More no_plan ;
BEGIN { use_ok( Gnome::MIME ); }
# test some simple mime type recognitions
is(Gnome::MIME::gnome_mime_type("foo.gif"), image/gif , "recognizes .gif");
is(Gnome::MIME::gnome_mime_type("foo.jpg"), image/jpeg , "recognizes .jpg");
is(Gnome::MIME::gnome_mime_type("foo.html"), text/html , "recognizes .html");
Now a normal perl Makefile.PL, make, and make test run will build and test the
new module.
XSUB Anatomy
As you can see in the preceding section, an XSUB resembles a C function signature
in K&R format. The first line contains the return type of the function. Then comes
a line containing the function name and a list of parameters. Finally, a line per
parameter specifies the type of each parameter. Here's an annotated version of the
previous example (note that XS doesn't actually allow comments inline with
XSUBs, so this won't compile):
char * # returns a string
gnome_mime_type(filename) # takes a single parameter named filename
char *filename # filename is a string
This is the simplest possible type of XSUB it maps a C function directly to a
Perl function with the same parameters and return type. The xsubpp compiler takes
this definition and produces C code in the generated MIME.c (see Listing 9 5). This
C code makes use of functions in the Perl API introduced in the previous chapter.
For example, to translate the incoming SV into a char *, MIME.c contains this line:
char * filename = (char *)SvPV(ST(0),PL_na);
The ST macro provides access to the argument array of an XSUB, but the rest of the
call should be familiar.
21
215
5
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved