Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Sending packed arrays from Perl to C

by Evanovich (Scribe)
on Aug 06, 2001 at 09:02 UTC ( [id://102395]=perlquestion: print w/replies, xml ) Need Help??

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

Dear Monks (and especially Tye, who was very kind in helping me on this task earlier): I am trying to pass a large 2-D float array from Perl to C in order to perform some mathematical functions on it. At the suggestion of Tye, I was told to pack the Perl array and send it through, and then recast a matrix in C. I am not very experienced in C (or much in Perl for that matter, but more so), and thus I'm having some trouble printing the values in the test array I've made. Here is the code I've put together (at the bottom I used the Perl module Inline to put the XSUB together automatically):
#! /usr/bin/perl -w use strict; use Inline C; sub MyFunc(\@); my $ref1 = [1,2,3,4,5]; my $ref2 = [6,7,8,9,10]; my @matrix; for (0..$#{$ref1}) { $matrix[0]->[$_] = ${$ref1}[$_]; } $_ = 0; for (0..$#{$ref2}) { $matrix[1]->[$_] = ${$ref2}[$_]; } MyFunc(@matrix); sub MyFunc (\@) { my $avMatrix= shift(@_); my $packedMatrix= ""; my @recycleBin; my $width= @{$avMatrix->[0]}; for my $avRow(@$avMatrix) { $width= @$avRow if @$avRow<$width; my $packedRow= pack("f$width", @$avRow); push @recycleBin, \$packedRow; $packedMatrix = pack("p", $packedRow); } return getangles(0+@$avMatrix, $width, $packedMatrix); } __END__ __C__ int getangles(int rows, int cols, char* packedMatrix) { int **M = (int **)packedMatrix; printf("Here I want the first entry of the matrix: %d", M); }
This seems to return a long number, not the desired number "1." Any suggestions?

Replies are listed 'Best First'.
Re: Sending packed arrays from Perl to C
by nardo (Friar) on Aug 06, 2001 at 09:45 UTC
    You use integers in getangles so pack them as integers.
    # my $packedRow= pack("f$width", @$avRow); my $packedRow= pack("i$width", @$avRow);
    You want to add each row to packedMatrix rather than overwrite it each time.
    # $packedMatrix = pack("p", $packedRow); $packedMatrix .= pack("P", $packedRow);

    With these changes the code works on my machine.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://102395]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2024-04-25 17:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found