How to write Perl constructor in XS?

I am trying to write a new XS module for Perl. I tested following the instructions for writing an XS module and it works fine.

I can't figure out how to write a method newfor XS

I have a package called Agent. I want to have something like this:

my $agent_object = new Agent;
+3
source share
3 answers

I got a response from XS Mechanics .

Thank you for your help

+3
source

The following code implements a typical

sub new {
  my $class = shift;
  return bless {@_} => $class;
}

XS. Class:: XSAccessor. Class:: XSAccessor , -. .

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

If your Agent.xs contains:

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

Doesn't XS ​​call this constructor automatically when you say Agent-> new?

0
source

Source: https://habr.com/ru/post/1718899/


All Articles