How to create a Perl hash in C using SWIG?

I am trying to create a Perl hash from the C library. Here is what I have 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: I am not getting anything that makes sense to me:

use testlib;
use Data::Dumper;

print Dumper (testlib::do_get_test_hash());

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

Ideas?

+3
source share
2 answers

see example 6 perlxstut . It creates a bunch of hashes and adds them to the array. At the end, it returns a reference to the array. It will work almost the same if you returned the hash.

+2
source

I believe that you should push the value you want to return to the stack, and not return it from the function, but I'm used to XS, not SWIG.

+2
source

Source: https://habr.com/ru/post/1711379/


All Articles