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));