tags:

views:

111

answers:

3

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;
A: 

If your Agent.xs contains:

class Agent {
public:
  Agent() {
    // constructor stuff
  }

doesn't XS call that constructor automatically when you say Agent->new?

wallenborn
Nope. But have a look at ExtUtils::XSpp. That can do it.
tsee
+3  A: 

I got the answer from XS Mechanics.

Thanks For your help

Avinash
+2  A: 

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