Writing C Modules with XS
// loop over args by pairs and fill in parameters
for(x = 0; x < items; x+=2) {
char *key = SvPV(ST(x), PL_na);
if (strEQ(key, "filename")) {
filename = SvPV(ST(x+1), PL_na);
} else if (strEQ(key, "default_type")) {
// ...
The preceding block uses the ST macro to access the SVs passed in as arguments. The
strEQ() function is used to compare the keys to the available parameter names. When
a match is found, the value is assigned to one of the variables initialized in the PREINIT
section. After that, a series of conditionals determines which gnome_mime_type function
to call:
// call the appropriate function based on arguments
if (read_file && default_type != NULL) {
RETVAL = gnome_mime_type_or_default_of_file(filename, default_type);
} else if (read_file) {
// ...
With the new named parameter style, the test cases will need adjusting:
# test some simple mime file_type recognitions
is(Gnome::MIME::file_type(filename => "foo.gif"), image/gif , "test .gif");
is(Gnome::MIME::file_type(filename => "foo.jpg"), image/jpeg , "test .jpg");
is(Gnome::MIME::file_type(filename => "foo.html"), text/html , "test .html");
# test defaulting
is(Gnome::MIME::file_type(filename => "", default_type => "text/html"),
"text/html", "test default");
# ...
Using Perl
The XSUB shown previously gets the job done, but at the cost of some long and rel
atively complicated C code. An easier way to get the same functionality is to divide
the module into an XS back end and a Perl front end. The XS layer will provide a
thin wrapper around the existing API, and the Perl front end will add the code
necessary to support a friendly interface.
22
223
3
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