Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

OO Inline::C - returning $self not working

by Anonymous Monk
on Mar 08, 2006 at 01:54 UTC ( [id://535081]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,

I'm trying to adapt the OO example of the Inline::C cookbook. I'd like to have setters that return $self. Some stuff sort of seems to be working, but returning $self isn't:
use strict; use warnings; my $parent = Node->new('Parent'); my $child = Node->new('Child'); # this DWIM... (prints 'Parent') print $child->set_parent($parent)->get_parent->get_name, "\n"; # ...but $child is now undef, (Can't call method ... ) $child->set_name('New name'); print $child->get_name, "\n"; ################################# package Node; use Inline C => q{ typedef struct { char* name; double branch_length; struct Node* parent; struct Node* previous_sister; struct Node* next_sister; struct Node* first_daughter; struct Node* last_daughter; } Node; SV* new(char* class, char* name) { Node* node = malloc(sizeof(Node)); SV* obj_ref = newSViv(0); SV* obj = newSVrv(obj_ref, class); node->name = strdup(name); sv_setiv(obj, (IV)node); SvREADONLY_on(obj); return obj_ref; } SV* set_name(SV* self, char* name) { ((Node*)SvIV(SvRV(self)))->name = strdup(name); return self; } char* get_name(SV* self) { return ((Node*)SvIV(SvRV(self)))->name; } SV* set_parent(SV* self, SV* parent) { ((Node*)SvIV(SvRV(self)))->parent = parent; return self; } SV* get_parent(SV* self) { return ((Node*)SvIV(SvRV(self)))->parent; } void DESTROY(SV* self) { Node* node = (Node*)SvIV(SvRV(self)); free(node->name); free(node); } };
...And I get:
% perl inline.pl Parent Can't call method "get_name" on an undefined value at inline.pl line 1 +0.
So what is the correct way to return self so it doesn't turn into undef?

(P.s.: I am user rvosa, but I'm away from my computer, forgot my password and lost the email address the reminder was sent to.)

Replies are listed 'Best First'.
Re: OO Inline::C - returning $self not working
by sfink (Deacon) on Mar 08, 2006 at 03:35 UTC
    The problem is the reference counts.

    XS implicitly decrements the reference count of any returned SV* (but not returned AV*'s or HV*'s, which is a bug that we're stuck with because it's part of the API and cannot be changed without breaking existing code.) Which magically works out, usually, because you'll be returning something you just created with newSViv(), and that sets the initial reference count to 1.

    In your case, you're returning a parameter, and nothing else is happening to its reference count. So by calling set_name(), you end up discarding a reference to one of your objects after the statement is done.

    It doesn't break immediately because it's a deferred reference count decrement -- XS mortalizes the returned SV*. The interpreter will remember how many times you mortalize something, and decrement the refcount that many times after the whole statement is complete.

    You have the same problem in get_parent(), although it's a bit obscured because you're declaring Node.parent to be of type 'struct Node*', but you're actually storing (and retrieving) an SV*.

    So to fix your code, do SvREFCNT_inc(self) on all of your set_* functions, and to the value you're returning from get_parent(). It still isn't quite correct, though, because you're keeping a reference to an SV* in Node.parent. You really should be maintaining the reference counts for what you store in there, too. I think it would be something like:

    SV* set_parent(SV* self, SV* parent) { Node* me = (Node*)SvIV(SvRV(self)); SvREFCNT_inc(parent); if (me->parent) SvREFCNT_dec(me->parent); me->parent = parent; SvREFCNT_inc(self); return self; }
    (Also note the order of inc/dec of the parent SVs. It seems odd, but consider what would happen if me->parent == parent.)

    Warning: I did test this, but refcounting in Perl still confuses me greatly. So however authoritative I may sound, believe me at your own risk!

      Hey, thanks, that sort of works. I now have the setters as:
      SV* set_parent(SV* self, SV* parent) { ((Node*)SvIV(SvRV(self)))->parent = parent; SvREFCNT_inc(self); return self; }
      ...and now $self sticks around. And for getters, (at least getters that return parents, siblings and children) I have:
      SV* get_parent(SV* self) { Node* me = (Node*)SvIV(SvRV(self)); SV* parent = me->parent; SvREFCNT_inc(parent); return parent; }
      ... which is what you were describing, right? This works (provided there is a me->parent).

      Your suggestion for increasing the refcount for parent and decreasing the refcount for me->parent in set_parent segfaults (isn't C fun?).

        I think im probably confused, but I dont see why SvREFCNT_inc(parent); would make sense at all. parent is a Node*, and SvREFCNT_inc operates on SV's only. It looks to me like you are getting a bit messed up with what is a node and what is an SV.

        ---
        $world=~s/war/peace/g

        Oh, right. That happened to me when I was playing with your example, too. It's because you don't initialize anything, so me->parent starts out as a garbage pointer, so dereferencing it with SvREFCNT_dec() seg faults. Fix it by using calloc() instead of malloc().

        Here's my version of your code:

        use strict; use warnings; my $parent = Node->new('Parent'); my $child = Node->new('Child'); # Should print 'Parent' print $child->set_parent($parent)->get_parent->get_name, "\n"; $child->set_name('New name'); # Should print 'New name' print $child->get_name, "\n"; # At end, should see # Freeing 0xnnnnnnn (New name) # Freeing 0xnnnnnnn (Parent) ################################# package Node; use Inline Config => CLEAN_AFTER_BUILD => 0, PRINT_INFO => 1; use Inline C => q{ typedef struct { char* name; double branch_length; SV* parent; struct Node* previous_sister; struct Node* next_sister; struct Node* first_daughter; struct Node* last_daughter; } Node; SV* new(char* class, char* name) { Node* node = calloc(sizeof(Node), 1); SV* obj_ref = newSViv(0); SV* obj = newSVrv(obj_ref, class); node->name = strdup(name); sv_setiv(obj, (IV)node); SvREADONLY_on(obj); return obj_ref; } SV* set_name(SV* self, char* name) { ((Node*)SvIV(SvRV(self)))->name = strdup(name); SvREFCNT_inc(self); return self; } char* get_name(SV* self) { return ((Node*)SvIV(SvRV(self)))->name; } SV* set_parent(SV* self, SV* parent) { Node* me = (Node*)SvIV(SvRV(self)); SvREFCNT_inc(parent); if (me->parent) SvREFCNT_dec(me->parent); me->parent = parent; SvREFCNT_inc(self); return self; } SV* get_parent(SV* self) { SV* parent = ((Node*)SvIV(SvRV(self)))->parent; SvREFCNT_inc(parent); return parent; } void DESTROY(SV* self) { Node* node = (Node*)SvIV(SvRV(self)); fprintf(stderr, "Freeing %p (%s)\n", self, node->name) +; free(node->name); free(node); } };

        demerphq: parent is declared as a Node*, but only actually used as an SV*.

        Thinking about it, it might work better to leave the definition of the parent field as you originally had it, but extract the actual parent Node* out of the passed-in SV* before storing it. Then set_parent() can be reduced to:

        SV* set_parent(SV* self, SV* parent) { Node* parent_node = (Node*)SvIV(SvRV(parent)); ((Node*)SvIV(SvRV(self)))->parent = parent_node; SvREFCNT_inc(self); return self; }
        (and correspondingly, get_parent() would have to wrap up the fetched parent in an SV.)

        This approach has one major problem, though -- you can no longer use DESTROY to free up the memory for the node, because there is no longer a single SV* that owns the memory to the node. So you'd either need to manage the memory externally, keep your own ref counts in the Node structure, or something. Hmm. So maybe polluting your structure with SV*'s really is the simplest way to deal with it.

        When I've been doing this stuff, I haven't used the DESTROY trick much. Mostly, I'm providing a temporary view into data structures that are managed by my main application. I could easily have many SV's that all point to the same object, and it doesn't matter. I guess I'm doing more of embedding Perl within my app than extending Perl with functionality from my app? To the script writer, it looks about the same.

Re: OO Inline::C - returning $self not working
by Andrew_Levenson (Hermit) on Mar 08, 2006 at 03:08 UTC
    I probably shouldn't even be attempting to offer anything, but I was just reading over your code and noticed: Don't you need to end (;) your comments? I don't think you had that done. --Even if i'm wrong and this sounds stupid, at least i'm learning. -keeps a positive attitude
      No - a comment begins with the '#' and ends at the end of the line. (A semi-colon would be seen to be part of the comment.)

      Cheers,
      Rob
        Thanks, but now that begs the question (from a newbie such as myself): If whitespace does not truly matter, how does the interpreter know when a line ends?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://535081]
Approved by GrandFather
Front-paged by Courage
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2024-04-16 13:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found