in reply to Re: (tye)Re2: Passing References to Arrays into Perl Extensions in C
in thread Passing References to Arrays into Perl Extensions in C

Now, part of the "win" of writing everything that you possibly can in Perl, is that you end up with C interfaces that can be more efficient. You mentioned in chatter that your matrix is rather large. So, let's say that you want to use this C code on the same (or similar) matrix more than once. Then you might want to use something like this:

sub PackMatrix { my $avMatrix= shift(@_); my $nRows= 0 + @$avMatrix; my $nCols= 0 + @{ $avMatrix->[0] }; my $ptrSize= length(pack"p",""); my $ptrLen= $ptrSize*$nRows; my $rowLen= length(pack"f",0)*$nCols; my $dataLen= $rowLen*$nRows; my $packedMatrix; if( pack("p",$packedMatrix) != pack("I",0+\$packedMatrix) ) { die "This platform has strange pointers!"; } length($packedMatrix)= $ptrLen + $dataLen; $packedMatrix= "\0" x $ptrLen; for my $avRow ( @$avMatrix ) { die "Row has ",0+@$avRow," entries instead of $width!" unless $width == 0+@$avRow; $packedMatrix .= pack("f$width",@$avRow); } my $ptr= $ptrLen + \$packedMatrix; for my $i ( 0..$#$avMatrix ) { substr( $packedMatrix, $i*$ptrSize, $ptrSize )= pack "I", $ptr; $ptr += $rowLen; } return \$packedMatrix; }
Then you can pass this single string around (always by reference, never by value) and use it again and again. Sorry, I have to run now so I don't have time to explain this in detail. Feel free to ask questions. (:

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