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

Hello-- I'm writing a perl extension in C. I want to send an array from the C function back to the main Perl section of the code. I've tried recasting my float array to a char * string, but i seem unable to get the packed array back out to Perl. Here is the code i have thus far (this is the XSUB function, as I don't think the perl code is the problem at this point, since the packed array seems to contain nothing:
MODULE = f PACKAGE = f #include "math.h" #define PI 3.1459 char * f(rows, cols, packedmatrix) int rows int cols char * packedmatrix CODE: float **M; float len1, len2, dotproduct; int k1; int k2; int k3; float theta; float product; char * packedangles; float angles[cols][cols]; M = (float**)packedmatrix; for (k1 = 0; k1<(cols-1); ++k1) { for (k2 = (k1+1); k2<(cols); ++k2) { dotproduct = 0; len1 = 0; len2 = 0; for (k3 = 0; k3 < rows; ++k3) { if ((M[k3][k1] != 999) && (M[k3][k2] != 999)) { dotproduct = dotproduct + (M[k3][k1])*(M[k3][k2]); len1 = len1 + pow((M[k3][k1]), 2); len2 = len2 + pow((M[k3][k2]), 2); } } theta = 180*(acos(dotproduct/sqrt(len1*len2)))/PI; angles[k1][k2]=theta; printf("The angle between columns %d and columns %d is %f\n\n", k +1, k2, theta); } packedangles = (char*)angles; printf("Packed angles: %s", packedangles); RETVAL = packedangles; } OUTPUT: RETVAL
Any help would be most most appreciated. Thanks! Evan

Replies are listed 'Best First'.
(tye)Re: Sending packed data from C to Perl
by tye (Sage) on Aug 07, 2001 at 00:14 UTC

    The output rule for char * translates to:

    • Use strlen() to find the first "\0"
    • Allocate a new scalar
    • Copy the string up-to and including the terminating "\0" into the new scalar
    which isn't much use for strings containing binary data.

    My preference for this type of thing is to have Perl allocate the space, pass a pointer to it into the C code, have the C code fill it in.

    You are already doing this with "packedMatrix". So you can just unpack that variable after the C code finishes. BTW, don't put packedMatrix in the OUTPUT: section or your packed string will get overwritten with a copy of the packed string upto the first "\0".

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