Taking a closer look, I think there are also other problems with your code. In particular, you're not (Perl-)dereferencing (SvRV()) the arrayref you get from hv_fetch() as the value associated with the hash entry "permutation". Also, you're not checking that the SV** pointer which hv_fetch() returns is non-null before (C-)dereferencing it...

Somewhat simplified, the sequence of steps should look something like this (I'm using Inline::C here for ease of demo):

#!/usr/bin/perl -l use Inline C => <<'EOC'; int get(SV* self, int index) { HV* h = (HV*) SvRV(self); char* key = "permutation"; SV** aref = hv_fetch(h, key, strlen(key), FALSE); if (aref == NULL) { /* ... */ exit(-1); } AV* a = (AV*) SvRV(*aref); SV** res = av_fetch(a, index, FALSE); if (res == NULL) { /* ... */ exit(-1); } IV i = SvIV(*res); return i; } EOC my $obj = bless { permutation => [2,42,2,2,2,2,2,2,2,2,2] }, "Whatever +"; print get($obj, 1); # prints 42

In real (production) code, you should also verify that you in fact have the appropriate types (using SvROK(), SvIOK(), etc.) before treating them as such.

(As for chromatic's note below, the mapping of the Perl integer to the C int index is being taken care of by Inline::C in this example.)


In reply to Re^3: simple XS by almut
in thread simple XS by spx2

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.