How do I write a Perl constructor in XS?
Question
I am trying to write new XS module for Perl. I have tested by following XS module writing instruction and it is working fine.
I am not able to understand how to I write new
method for XS
I have a package called Agent
. I want to be able to something like this:
my $agent_object = new Agent;
Solution
I got the answer from XS Mechanics.
Thanks For your help
OTHER TIPS
The following code implements a typical
sub new {
my $class = shift;
return bless {@_} => $class;
}
constructor in XS. It's copied verbatim from Class::XSAccessor. I would suggest you investigate Class::XSAccessor for cases when you are using an ordinary hash based object. No need to reinvent this wheel.
void
new(class, ...)
SV* class;
PREINIT:
unsigned int iStack;
HV* hash;
SV* obj;
const char* classname;
PPCODE:
if (sv_isobject(class)) {
classname = sv_reftype(SvRV(class), 1);
}
else {
if (!SvPOK(class))
croak("Need an object or class name as first argument to the constructor.");
classname = SvPV_nolen(class);
}
hash = (HV *)sv_2mortal((SV *)newHV());
obj = sv_bless( newRV((SV*)hash), gv_stashpv(classname, 1) );
if (items > 1) {
if (!(items % 2))
croak("Uneven number of argument to constructor.");
for (iStack = 1; iStack < items; iStack += 2) {
hv_store_ent(hash, ST(iStack), newSVsv(ST(iStack+1)), 0);
}
}
XPUSHs(sv_2mortal(obj));
If your Agent.xs contains:
class Agent {
public:
Agent() {
// constructor stuff
}
doesn't XS call that constructor automatically when you say Agent->new?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow