nikolaus has asked for the wisdom of the Perl Monks concerning the following question:
Some particulars:
buildB looks much like buildA. A::addBs looks like this:SV *buildA(A& a) { SV *tmpSv, a_sv; I32 count; int i; dSP; ENTER; SAVETMPS; PUSHMARK; tmpSv = sv_2mortal(newSVpv("A", 0)); XPUSHs(tmpSv); PUTBACK; count = call_method("new", G_SCALAR); // A::new { // my $proto = shift; // my $class = ref($proto) || $proto; // my $this = { }; // bless($this, $class); // $this->{B} = [ ]; // return $this; // } SPAGAIN; assert(1 == count); tmpSv = POPs; a_sv = newSVsv(tmpSv); // or use NEWSV/SvSetMagicSV PUTBACK; FREETMPS; LEAVE; std::vector<SV*> b_svs; for (i = 0; i < a.b_count; ++i) { tmpSv = buildB(a.b[i]); b_svs.push_back(tmpSv); } addBs(a_sv, b_svs); return a_sv; }
If I use newSVsv in buildA/buildB, then the SV* returned by buildA( ) seems to be &PL_sv_undef. If I use NEWSV/SvSetMagicSV, then I get the "Attempt to free unreferenced scalar" in the calling XS code:void addBs(SV *a_sv, std::vector<SV*> &b_svs) { SV *tmpSv; I32 count; std::vector<SV*>::iterator iter; dSP; ENTER; SAVETMPS; PUSHMARK(SP); tmpSv = sv_mortalcopy(a_sv); XPUSHs(tmpSv); for (iter = b_svs.begin( ); iter != b_svs.end( ); ++iter) { XPUSHs(sv_2mortal(*iter)); } PUTBACK; count = call_method("add", G_VOID|G_DISCARD); // A::add { // my $this = shift; // push(@{$this->{B}}, @_); // } SPAGAIN; assert(0 == count); FREETMPS; LEAVE; }
void get_a( ) PPCODE: A a = getAFromSomewhere( ); SV *a_sv = buildA(a); XPUSHs(sv_2mortal(a_sv));
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Correct way to return a reference in XS/embedded perl
by hawtin (Prior) on Mar 23, 2004 at 01:01 UTC | |
by nikolaus (Novice) on Mar 23, 2004 at 17:03 UTC | |
by hawtin (Prior) on Mar 24, 2004 at 03:51 UTC |