Mortals and refcounts in XS

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I'm currently writing my first from-scratch Perl/XS module and have some
problems with the perlxs and perlguts docs. The question is when exactly
to change reference counts or mortalize values.
My module implements a trie structure in C, storing arbitrary scalar
values under string keys. My idea so far was that I had to increment a
value's refcount when storing it in the trie to keep it from being GC'd
if it should go out of scope, and decrement it when I remove it. But
I've been using RETVAL as copied from some perlxstut example, which is
said to mortalize values it returns. So to avoid "Attempt to free
unreferenced scalar" errors I have to
a) increment refcounts before insertion
b) increment refcounts for values returned in a lookup
c) do nothing when returning a value that has been removed from the trie

This seems to work but it's kinda unintutitive and looks clumsy to me.
For example, here is the lookup XS code:

SV *lookup(self, key)
   btrie_nodep_t self;
   char *key;
      SV *value;
      bool_t isctrie = FALSE;
      if(btrie_lookup((btrie_trienodep_t*)&self,&isctrie,&key,&value)) {
         RETVAL = value;
      } else XSRETURN_UNDEF;
   } /* why the fuck do I need this brace?! */

(also, the code won't compile unless I insert an extra closing brace as
Any ideas how to do this better? To do it more efficiently than just
countering the mortalizing effect of RETVAL with SvREFCNT_inc I tried to
replace it with XPUSHs and a simple return:


but this puts a reference to seemingly random values on the stack. I'm
surely missing something here?

kind regards,

Re: Mortals and refcounts in XS

[A complimentary Cc of this posting was sent to
Matthias Bethke
Quoted text here. Click to load it

You are missing (at least) that you need to cut & paste THE REAL CODE
to have a hope to get meaningful replys.

Hope this helps,

Re: Mortals and refcounts in XS

begin followup to Ilya Zakharevich:
Quoted text here. Click to load it

Yup. Thanks.


Site Timeline