For my new
Data::Reuse module (now on CPAN), I'm looking for a way to create a hash entry in which both the value as well as the key point to the same SV, or more general: set the hash key to a specific SV.
From what I've been able to learn from looking at a bunch of XS code, and [hs]v.[ch], the following code should do the trick:
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include "ppport.h"
MODULE = Data::Reuse PACKAGE = Data::Reuse
void
key_as_sv( hv, key, val )
HV *hv
SV *key
SV *val
PROTOTYPE: \%$$
CODE:
SvREFCNT_inc(key);
SvREFCNT_inc(val);
STRLEN length = SvCUR(key);
hv_store( hv, SvPV( key, length ), length , val, 0 );
HE *he = hv_fetch_ent( hv, key, 0, 0 );
HeSVKEY_set( he, key );
which would then be called thus:
my %hash;
my $foo = 'foo';
Data::Reuse::key_as_sv( %hash, $foo, $foo );
print STDERR "found ".(keys %hash)." keys:\n";
print STDERR " $_: $hash{$_}\n" foreach keys %hash;
However, this produces the following output:
found 1 keys:
foo:
or, in other words, the value of the key is gone.
I guess my question to any XS savvy Perl Monk is:
- does it make sense to try to save memory this way?
- if so, why doesn't the above work?
Thanks in advance for any insights.
Liz
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.