Wednesday, June 26, 2002

An Illustration of Perl Objects with C APIs An Illustration of Perl Objects with C APIs
To illustrate the use of C API's with Perl objects, a toy PPM-format image class is created and then extended (ToyPPM.pm and ExtendedToyPPM.pm). This child class runs just as fast as if it were part of a big C-language extension library, instead of being small and independent, depending only on ToyPPM.pm having provided a C API, and on Inline::C, to make use of it.
The image data is maintained in the PPM string itself, as sequence of (height x width x 3) one-byte integer color samples. These samples are exposed as a seemingly normal perl array, implemented by a Tie::Array/perltie-based helper subclass, created from a simple specification, by a generator of array-like classes. This sample array is then "folded" into an apparently normal 3D array of array of arrays, to provide a very natural interface to the image data (though a quite slow one).
ToyPPM.pm also provides a C API, namely a method which returns a string of C code. It defines macros which obtain a pointer to the string's memory, and provide direct and rapid access to the image bytes. This method was created by the same generator, also from a simple specification.

0 Comments:

Post a Comment

<< Home