in reply to How to keep C variables "alive" between invocations with Inline::C

Maybe something like the following? It is quite simple and avoids the difficulty of translating pointers between C and Perl.

#!/usr/bin/perl use strict; use warnings; use Inline 'C'; foreach (1..15) { my $tree = new_tree(); die "failed to allocate tree" if($tree < 0); print "node count of tree $tree is: " . node_count($tree), "\n"; } __END__ __C__ #define NMAX 10 struct tree { int size; } trees[NMAX]; int td = 0; int new_tree() { if(td < NMAX) { trees[td].size = td * 2; return(td++); } else { return(-1); } } int node_count(int td) { return(trees[td].size); }

You could allocate memory dynamically if that were appropriate, perhaps simplifying the trees structure to an array of pointers to allocated memory. With a little more sophistication, you could free tree descriptors, keep track of which ones were in use, etc.

  • Comment on Re: How to keep C variables "alive" between invocations with Inline::C
  • Download Code