rutgeraldo has asked for the wisdom of the Perl Monks concerning the following question:
Dear monks,
I am trying to construct self-referential objects (tree/DAG nodes) using Inline::C. These are the requirements:
#!/usr/bin/perl package Node; use strict; use warnings; use Inline C => <<'__EOI__'; // XXX no children for now typedef struct Node { struct Node* parent; SV* sv; } Node; Node* new(const char * classname) { Node *self; // allocate and initialize struct Newx(self, 1, Node); self->parent = NULL; // create perl object and ref SV* perlref = newSViv((IV)self); SV* obj_ref = newRV_noinc(perlref); sv_bless(obj_ref, gv_stashpv(classname, TRUE)); SvREADONLY_on(perlref); // store pointer to object in struct self->sv = obj_ref; return self; } // should NOT alter refcount Node* set_parent(Node* self, Node* parent) { self->parent = parent; return self; } Node* get_parent(Node* self) { return self->parent; } // XXX get/set children deferred void destroy_node(Node* self) { Safefree(self); } __EOI__ sub DESTROY { my $self = shift; warn "destroying $self"; $self->destroy_node; } package main; use Devel::Peek; $|++; my $node = Node->new; my $parent = Node->new; print "NODE: "; Dump($node); print "---\n"; print "PARENT: "; Dump($parent); print "---\n"; $node->set_parent($parent); print "FROM FIELD: "; print Dump($node->get_parent); print "---\n";
Here is my typemap:
TYPEMAP Node * NODE INPUT NODE $var = ($type)SvIV(SvRV($arg)); OUTPUT NODE $arg = $var->sv;
When I run this, the following output is produced:
NODE: SV = IV(0x7fcc7b8041b8) at 0x7fcc7b8041c8 REFCNT = 1 FLAGS = (PADMY,ROK) RV = 0x7fcc79803e98 SV = PVMG(0x7fcc790023b0) at 0x7fcc79803e98 REFCNT = 1 FLAGS = (OBJECT,IOK,READONLY,pIOK) IV = 140516178002128 NV = 0 PV = 0 STASH = 0x7fcc7a004e70 "Node" --- PARENT: SV = IV(0x7fcc7a008838) at 0x7fcc7a008848 REFCNT = 1 FLAGS = (PADMY,ROK) RV = 0x7fcc79803ce8 SV = PVMG(0x7fcc79002770) at 0x7fcc79803ce8 REFCNT = 1 FLAGS = (OBJECT,IOK,READONLY,pIOK) IV = 140516178002208 NV = 0 PV = 0 STASH = 0x7fcc7a004e70 "Node" --- FROM FIELD: SV = UNKNOWN(0xff) (0x7fcc7a004630) at 0x7fcc79803fd0 REFCNT = 0 FLAGS = (TEMP) Attempt to free unreferenced scalar: SV 0x7fcc79803fd0, Perl interpret +er: 0x7fcc79800000 at ref.pl line 72. --- destroying Node=SCALAR(0x7ff391803ce8) at ref.pl line 51. destroying Node=SCALAR(0x7ff391803e98) at ref.pl line 51.
My conclusions are as follows:
Apologies for the long "first" post. I used to be user "rvosa" but forgot my password and lost my email address. Thanks!
|
|---|