|Pathologically Eclectic Rubbish Lister|
When to (and not to) use sv_2mortal()by davido (Archbishop)
|on Oct 28, 2011 at 17:47 UTC||Need Help??|
davido has asked for the
wisdom of the Perl Monks concerning the following question:
Something I'm a little unclear on. I've read Inline::C, Inline::C-Cookbook, XS-ive Mortality. (or when to use sv_2mortal()), chapter 9 from Advanced Perl Programming, and several POD's, but I guess I'm just dense. ;)
sv_2mortal() is used to decrease the ref-count on an SV "soon but not quite yet". The canonical use is when pushing values onto the stack to use as a return-value from a sub; the stack will get killed "real soon now" anyway, at the time that the Inline::C sub passes its values back to Perl.
Where I'm unclear is with this operation:
Here I'm pushing elements onto an anonymous array, and then passing that array by reference back to Perl (well, that's what happens after Inline::C gets its hooks into it.)
In my mind I could see this two ways, and only one of them can be right. First (the theory under which this sub performs), av_push increases the ref-count, so sv_2mortal() is needed or else the ref-count would be two at the end of the push, where we only want it to be one.
The second way is that av_push() doesn't increase the reference count. If that's the case, it would seem that sv_2mortal is putting the sub-call at risk of having all the elements in the anonymous array garbage collected upon returning to Perl, since the ref-count of each element is scheduled to drop to zero at sub-return.
In support of my first theory: It actually works. But then I wonder if I'm just living on borrowed time.
A second question: The Inline::C-Cookbook shows an example of a C subroutine calling a Perl subroutine in a way where there's no need to check the Perl sub's return value. But how about an instance where I would like to call a Perl sub from within my inline C code, and I want to see its return value? I've been unable to find an example. I did look at perlapi, and perlxstut, but it seems that the Inline::C macros interfere with the raw XS macros when I attempt to set up to check the return value.
A little guidance in the form of a few lines of code illustrating a C subroutine (ala Inline::C) calling a Perl sub and getting an int from its rv would be helpful to me.