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

I have written a couple simple C functions I would like to be able to call from a perl program. I used h2xs to convert the header file into XS and everything worked fine, I was able to run make and make test. I started writing a few tests to make sure everything was working properly, but I ran into a problem, my program uses several C structs. For the most part h2xs seems to have done a good job of converting the structs. I can use all of the structs in Perl except for one which contains a pointer to an array of structs.

This is what my structs look like in C:

typedef struct { double longitude; double latitude; } vertex_t; typedef struct { vertex_t v1; vertex_t v2; } edge_t; typedef struct { int edge_count; edge_t *edges; } polygon_t;

So using the first two structs in Perl is intuitive I can create them using:

my $vertex1 = vertex_t->new(); my $vertex1_obj = $vertex1->_to_ptr(); $vertex1_obj->longitude(-123.1411461547873); $vertex1_obj->latitude(49.29515081299949); my $vertex2 = vertex_t->new(); my $vertex2_obj = $vertex2->_to_ptr(); $vertex2_obj->longitude(-123.1502664432874); $vertex2_obj->latitude(49.29191311233952); my $edge = edge_t->new(); my $edge_obj = $edge->_to_ptr(); $edge_obj->v1($vertex1); $edge_obj->v2($vertex2);

My problem is I cannot figure out how to create a polygon_t in perl, I can get this far:

my $polygon = polygon_t->new(); my $polygon_obj = $polygon->_to_ptr(); $polygon_obj->edge_count(8);

I think the XS generated for the polygon_t type probably has no idea that in my code I use edges_t *edges as an array of edge_t types not just a pointer to an edge_t type, because this works: $polygon_obj->edges($edge_obj) but what I really want to do is pass an array of edge objects from Perl. Can anyone tell me how to modify the XS to achieve this ?

Replies are listed 'Best First'.
Re: Need help with Perl XS and C Structs
by pileofrogs (Priest) on Feb 03, 2010 at 18:51 UTC