generic refcounted object perl binding



Hi, everyone!

I'm asking a question about how to wrapping a refcounted class inside perl. I ask the question here because Gtk is such kind of system.

I have some experience on embedding perl in C++, but have little knowledge on perl XS, and I found perldoc perlxs really puzzled.

Firstly, I have an simple refcounted C++ base class like this:

class Referenced {
public:
    Referenced():refcnt(0) { }

    virtual ~Referenced() {}

    void refInc() { refcnt++; }

    void refDec() {
        if (--refcnt<=0) delete this;
    }

protected:
    int refcnt;
};

In my wrapper, I want to have following functions:
- able to construct my object within perl, like My::Class->new();
- able to construct my object in C++, and pass it to perl sub as argument;
- handle ref count correctly;

So, is these things correct for my XS:

Referenced::new(class)
    PREINIT:
        const char* class;
        Referenced* obj;
        SV* obj_wrap;
        SV* sv;

    CODE:
        // create object
        obj = new Referenced;
        obj->refInc();
        
        // store pointer as unsigned int?
        obj_wrap = newSV(0);
       &nb sp;sv_setuv(obj_wrap, (uv)obj);

        // we always wrap 2 layers SVs for a class? Should I do these things manually?
        sv = newSVrv(obj_wrap, class);
        RETVAL = sv;

    OUTPUT:
        RETVAL

// is this correct?
// I don't really understand when would Perl do automatic scalar conversion, and when should I manually do that.
Referenced::DESTROY(self)
    PREINIT:
        Referenced* self;
    CODE:
        self->refDec();
    


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]