Class::XSAccessor - Generate fast XS accessors without runtime compilation
package MyClass;
use Class::XSAccessor
getters => {
get_foo => 'foo', # 'foo' is the hash key to access
get_bar => 'bar',
},
setters => {
set_foo => 'foo',
set_bar => 'bar',
},
accessors => {
foo => 'foo',
bar => 'bar',
},
predicates => {
has_foo => 'foo',
has_bar => 'bar',
},
# The imported methods are implemented in fast XS.
# normal class code here.
Class::XSAccessor implements fast read, write and read/write accessors in XS.
Additionally, it can provide predicates such as has_foo() for testing
whether the attribute foo is defined in the object.
It only works with objects that are implemented as ordinary hashes.
Class::XSAccessor::Array implements the same interface for objects
that use arrays for their internal representation.
The XS methods were between 1.6 and 2.5 times faster than typical
pure-perl accessors in some simple benchmarking.
The lower factor applies to the potentially slightly obscure
sub set_foo_pp {$_[0]->{foo} = $_[1]}, so if you usually
write clear code, a factor of two speed-up is a good estimate.
The method names may be fully qualified. In the example of the
synopsis, you could have written MyClass::get_foo instead
of get_foo.
By default, the setters return the new value that was set
and the accessors (mutators) do the same. You can change this behaviour
with the chained option, see below. The predicates obviously return a boolean.
In addition to specifying the types and names of accessors, you can add options which modify behaviour. The options are specified as key/value pairs just as the accessor declaration. Example:
use Class::XSAccessor
getters => {
get_foo => 'foo',
},
replace => 1;
The list of available options is:
Set this to a true value to prevent Class::XSAccessor from
complaining about replacing existing subroutines.
Set this to a true value to change the return value of setters
and mutators (when called with an argument).
If chained is enabled, the setters and accessors/mutators will
return the object. Mutators called without an argument still
return the value of the associated attribute.
As with the other options, chained affects all methods generated
in the same use Class::XSAccessor ... statement.
Probably wouldn't work if your objects are tied hashes. But that's a strange thing to do anyway.
Scary code exploiting strange XS features.
If you think writing an accessor in XS should be a laughably simple exercise, then please contemplate how you could instantiate a new XS accessor for a new hash key that's only known at run-time. Note that compiling C code at run-time a la Inline::C is a no go.
Steffen Mueller, <smueller@cpan.org>
Chocolateboy, <chocolate@cpan.org>
Copyright (C) 2008 by Steffen Mueller
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8 or, at your option, any later version of Perl 5 you may have available.