Need to convert Perl unpack to Inline::C AV*

196 views Asked by At

I am struggling a bit to convert a Perl unpack to Inline::C

@array = unpack("C*", $buf);

This is what I have so far, but I am an Inline::C novice so I am having trouble of what to do next:

STRLEN len;
char* test = SvPVbyte(buf, len);
...
AV* arr = SvRV(?);

Can anyone provide a tip to how to do this?

2

There are 2 answers

0
hobbs On BEST ANSWER

The smart thing here is probably to avoid calling unpack, and do what unpack would do, which is simpler.

STRLEN len;
char *str = SvPVbyte(buf, len);
AV *arr = newAV();
char *ptr;

for (ptr = str; ptr < str + len ; ptr++) {
    SV *char_value = newSViv(*ptr);
    av_push(arr, char_value);
}

Or, of course, just write the loop and leave out the array if you don't need it :)

0
ikegami On

The body of the function could look like:

STRLEN len;
char*  buf;
AV*    av = newAV();

SvGETMAGIC(sv);
buf = SvPVbyte(sv, len);
while (len--)
    av_push(av, newSViv(*(buf++)));

You have two choices for the return value.

SV* my_unpack(SV* sv) {
    ...
    return newRV_noinc(av);  // Will get mortalized by typemap.
}

or

AV* my_unpack(SV* sv) {
    ...
    return sv_2mortal(av);  // Typemap will create a reference.
}