|There's more than one way to do things|
The easy way to write XS code and work with Perl varaibles directly from C. (New resources on Class::HPLOO).by gmpassos (Priest)
|on Mar 07, 2005 at 21:16 UTC||Need Help??|
Recently I was working a lot with XS, rewriting Perl functions to C to get speed where I need, since I'm working into an image processing module. To make my life easy I have added some resources to my module Class::HPLOO, that I will share them to you now.
Everybody that have worked with XS knows that is not a friendly thing, specially if you need to receive in your C functions Perl variables and return complex structures like ARRAYs and HASHEs.
One thing that make life easier is Inline::C, but even with Inline we have the problem to work with the perlapi. Well, I'm not here to say that the perlapi is not good, I'm just saying that compared to a normal Perl code, work with Perl variables from C is not a easy thing.
To make the life of my developers easier I have added some extra resources to Class::HPLOO. Class::HPLOO is a framework that already make the declaration of Perl classes easier. With it we can declare a package with a syntax similar to Java declaration of classes:
The similar code with pure Perl of the class above is:
The code from here is already simplier than a normal Perl class what give to us time.
Now the XS part:
To enable XS directly from functions in the class declaration I have used Inline and this syntax:
But as we can see, the C code with all the perlapi functions is a mess, since I need to make many calls just to access and store values in the object (self).
To "fix" that I have added a pseudo syntax, defined at Class::HPLOO::InlineC. And the function stay clean:
Then I have added many other syntaxes for ARRAY, HASH, etc...:
The code above with pure C should be:
Well, who knows the perlapi will understand well what is writed in the code above, but if you have never used the perlapi and just knows the basics of C you will understand well the previous code with the new pseudo syntax.
Is easy to see what a new simple syntax can bring to the developer, since from a function of 10 lines with 16 calls we can write a clean function with 4 lines and 6 calls (1 new array, 2 fetch , 2 store , 1 ref returned). But note that the main idea is not 10 lines to 4 lines, but the work to write the functions, since until now I have used only simple FETCH and STORE operations as examples! So, we can see that any simple code that work with Perl variables using just pure XS is a hell!
Well, now I only can say enjoy! ;-P
Graciliano M. P.