An alternative approach is to pack and unpack the array from the Perl side

Cool approach - it enables one to utilise the do_nothing() sub as it was presented in the original post.
For my own benefit, I turned it into an Inline::C demo:
use strict; use warnings; use Inline C => Config => BUILD_NOISY => 1, USING => 'ParseRegExp', ; use Inline C => <<'EOC'; double do_nothing(double x[], int sizeOfX) { int index; for(index=0; index<sizeOfX; index++) x[index] = 1; return x[0]; } void do_nothing_c(SV * sv) { STRLEN len; char * pv; pv = SvPV_force(sv, len); /* SvPV() also seems ok */ do_nothing((double *)pv, len / sizeof(double)); } EOC my @in = (2.3, 3.4, 4.5, 5.6, 6.7); my @ret = do_nothing(@in); print "@in\n@ret\n"; sub do_nothing { my $doubles = pack 'd*', @_; do_nothing_c($doubles); return unpack 'd*', $doubles; } __END__ Outputs: 2.3 3.4 4.5 5.6 6.7 1 1 1 1 1
I was initially a little concerned about there being both a Csub and a Perlsub named "do_nothing" but, of course, the Csub does not bind to Inline::C and the only sub named "do_nothing" that is visible from perl space is the Perlsub. Conversely, the only sub named "do_nothing" that is visible from XS space is the Csub.

The return value of the do_nothing() Csub is not being captured anywhere in this demo. For the purposes of this demo it might just as well have been coded as:
void do_nothing(double x[], int sizeOfX) { int index; for(index=0; index<sizeOfX; index++) x[index] = 1; }

Cheers,
Rob

In reply to Re^2: perl XS - passing array to C and getting it back by syphilis
in thread perl XS - passing array to C and getting it back by kopolov

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.