Evanovich has asked for the wisdom of the Perl Monks concerning the following question:

Hi everyone. I'm having a lot of trouble writing a Perl extension in C that accepts a reference to an array and passes it into the extension to be used by the C subroutine. I noticed on the perldoc.com discussion of XSUBs, there was a "Coming Soon" notice on the part of the page that explains this question. Anyone know how this works?
  • Comment on Passing References to Arrays into Perl Extensions in C

Replies are listed 'Best First'.
(tye)Re: Passing References to Arrays into Perl Extensions in C
by tye (Sage) on Aug 03, 2001 at 09:25 UTC

    Make your life simple:

    sub MyFunc { my $arrRef= shift(@_); my $packedArr= pack("f*",@$arrRef); return MyFuncC( 0+@$arrRef, $packedArr ); }
    write in Perl what is easy to do in Perl and write in C only what is easy to write in C. Then you can declare your XS code like:
    int MyFuncC( count, packedArray ) int count; char * packedArray; CODE: RETVAL= CFunc( count, (float *)packedArray );
    Note that this changes depending on the data type of the array to be used by the C function. Provide more details if you have questions.

    Updated to work for floats.

            - tye (but my friends call me "Tye")
      Hi tye--- Thanks for your response. My reference is to a matrix of float values. Will char * still work? I don't think so.... I guess I should have made that clear in my question.

        Yes, "char *" will work fine. I updated my previous node to work with floats. The "char *" tells XS that you want a pointer to the string value of the scalar that was passed in. The pack produces a string that contains a C array of floats, so the address of that can just be typecasted to get a pointer to an array of floats.

                - tye (but my friends call me "Tye")