tags:

views:

296

answers:

2

I'm trying to create a Perl hash from within a C library. Here's what I've got so far:

static void add_string_to_perl_hash ( HV *hv, char * key, char *value ) {

SV *obj = sv_2mortal(newSVpv(value, 0));

hv_store(hv, (const char *)key, strlen (key), obj, 0);

SvREFCNT_inc(obj);

}

SV * do_get_test_hash () {

    static char *foo ="foo";
    static char *bar ="bar";

    HV *hv;

    hv = newHV();
    add_string_to_perl_hash ( hv, "foo",   foo);
    add_string_to_perl_hash ( hv, "bar",   bar);

    return sv_2mortal(newRV_noinc((SV*)hv));
}

Trying it out: I don't get anything that makes any sense to me: use testlib; use Data::Dumper;

print Dumper (testlib::do_get_test_hash());

$VAR1 = bless( do{(my $o = 5359872)}, '_p_SV' );

Ideas?

+2  A: 

I believe you must push the value you want to return onto the stack, not return it from the function, but I am used to XS rather than SWIG.

Chas. Owens
Does this imply I have to use assembler to push it onto the stack? (bleah!) Or is there some other mechanism?
Leonard
Hmmm. After reading more in perlguts and perlxstut, I realize you're talking about pushing it on to the Perl stack. I tried XPUSHs(sv_2mortal(newRV_noinc((SV *) hv))); But get a compile error for the line: proc/tools.c: In function `do_get_test_hash': proc/tools.c:306: error: `sp' undeclared (first use in this function)Not sure what this is about...
Leonard
+2  A: 

Hi, have a look at Example 6 of perlxstut. It creates a bunch of hashes and adds them to an array. At the end, it returns a reference to the array. It would work practically the same if you returned a hash.

tsee
Thanks. This had the details I needed.
Leonard