Christian Cloutier <[EMAIL PROTECTED]> writes:
>How can I add an array (AV) to a hash (HV) as a hash entry using XS?
>
>For example:
>
>HV * ln_hash = NULL;
>AV * ln_array = NULL;
>SV * sv = NULL;
>
>ln_hash = (HV *) newHV();
>ln_array = (AV *) sv_2mortal((SV *)newAV());
>
>sv = newSVpv("Value 1", 0);
>av_store(ln_array, 0, sv);
>sv = newSVpv("Value 2", 0);
>av_store(ln_array, 1, sv);
>
>hv_store(ln_hash, "MyKey", 5, newRV_noinc((SV *)ln_array), 0);
Okay so far.
>
>XPUSHs((SV *) ln_hash);
To return a reference to a hash akin to
sub foo
{
my %hash;
...
return \%hash;
}
That should be
XPUSHs(newRV_noinc((SV *) ln_hash));
To do the equivalent of
sub foo
{
my %hash;
...
return %hash;
}
You would just return list of key/value pairs so you don't need the HV at all
you can just do:
PPCODE:
{
...
XPUSHs(sv_2mortal(newSVpv("MyKey",5)));
XPUSHs(sv_2mortal(newRV_noinc((SV *)ln_array)));
XSRETURN(2);
}
>
>Does not seem to work quite right...
>
>The dump (using Devel::Peek) gives me:
>
>SV = PVHV(0x1da6a78) at 0x1aff15c
> REFCNT = 1
> FLAGS = (SHAREKEYS)
> IV = 1
> NV = 0
> ARRAY = 0x1ae0080 (0:7, 1:1)
> hash quality = 150.0%
> KEYS = 1
> FILL = 1
> MAX = 7
> RITER = -1
> EITER = 0x0
> Elt "MyKey" HASH = 0x5e2ad58
> SV = RV(0x1ae9284) at 0x1aff258
> REFCNT = 1
> FLAGS = (TEMP,ROK)
> RV = 0x1aff210
> SV = PVAV(0x1afdd40) at 0x1aff210
> REFCNT = 1
> FLAGS = ()
> IV = 0
> NV = 0
> ARRAY = 0x1ae00c4
> FILL = 1
> MAX = 3
> ARYLEN = 0x0
> FLAGS = (REAL)
> Elt No. 0
> SV = PV(0x1afecd4) at 0x1aff228
> REFCNT = 1
> FLAGS = (POK,pPOK)
> PV = 0x1ae00dc "Value 1"\0
> CUR = 7
> LEN = 8
> Elt No. 1
> SV = PV(0x1afecec) at 0x1aff240
> REFCNT = 1
> FLAGS = (POK,pPOK)
> PV = 0x1ae00b4 "Value 2"\0
> CUR = 7
> LEN = 8
>
>But trying something like:
>
>my %hash = Foo::testfunc();
>
>foreach $k ( keys %hash ) {
> print "$k: @{ $hash{$k} }\n"
> }
>
>gives me error like: "Bizarre copy of HASH in sassign"
>
>There is definetely a better way of doing this or I'm probably doing
>something wrong... should I return a reference to my hash instead?
Yes.
>
>Any ideas?
>
>Thanks,
>
>Christian Cloutier
--
Nick Ing-Simmons
http://www.ni-s.u-net.com/