Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

XS: how to destroy HV* that was used internally?

by OlegG (Monk)
on Sep 18, 2014 at 07:10 UTC ( [id://1101000]=perlquestion: print w/replies, xml ) Need Help??

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

Suppose I have following class implemented with XS
#include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "ppport.h" typedef struct { HV* set; char foo; } My_Class; MODULE = My::Class PACKAGE = My::Class SV* new(char* class) PREINIT: My_Class *self; CODE: Newx(self, 1, My_Class); self->set = newHV(); self->foo = 0; RETVAL = newSV(0); sv_setref_pv(RETVAL, class, (void *)self); OUTPUT: RETVAL void DESTROY(My_Class *self) CODE: /* HOW TO DESTROY self->set HERE*/ Safefree(self);
Where I'll use self->set internally, which type is HV*. In the constructor (new) newHV() creates HV with reference count 1. So, as I understand, to be destroyed reference count should be decreased to 0. But as I found we have only SvREFCNT_dec() which argument may be SV* and not HV*.

So, what is a solution here?
May be I just need to call Safefree(self->set)?
Or get reference to self->set into SV* variable and call SvREFCNT_dec on it?

Replies are listed 'Best First'.
Re: XS: how to destroy HV* that was used internally?
by salva (Canon) on Sep 18, 2014 at 07:49 UTC
    SvREFCNT_dec((SV*)hv);

    All internal Perl data structures are derived from SV, so that you can do thinks like that.

      Thank you!
      Also found that for me it works without type casting. But, ok, I'll use it
      And after all I found similar question on stackoverflow with similar answer.

        That's because SvREFCNT_dec already casts for you. In fact, it casts in a way that will detect if the input was const, so doing SvREFCNT_dec((SV*)hv) instead of SvREFCNT_dec(hv) is actually harmful.

        If you ever use (SV*)x, consider using MUTABLE_SV(x) instead.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2024-04-19 17:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found