Hi

I am trying to create a Perl API on top of some nested structures in C. But I think it is difficult to create a "natural" Perl API, where the user of the Perl API doesn't have to worry about "dangling pointer" problems - something which is very far from a Perl programmers mind :-)

It would be nice if there was some kind of reference counting going on, when SWIG returns pointers to nested structures.

In Perl for example, it might even be possible to somehow use Perls own reference counting mechanism by storing a reference to the wrapped "parent structure" in the blessed object.

And unfortunately it doesn't even seem possible to implement some kind of reference counting mechanism yourself, when the "memberout" typemap is no longer part of SWIG?

An example of the problem is illustrated below in example.i and example.pl, where findFoo() will always return a wrapped dangling pointer and the expression "$foo->{x}" ends up accessing already freed memory.

Any good ideas on a simple approach to avoid this kind of problem?


example.i:
%module example

%nodefaultctor Foo;
%nodefaultdtor Foo;

%immutable f;

%inline %{
typedef struct Foo {
  int x;
} Foo;

typedef struct Bar {
  int y;
  Foo f;
} Bar;

void fillBar(Bar *bar);
%}

%{
/* Simulate for example purposes */
void fillBar(Bar *bar) {
  bar->f.x = 6 * bar->y;
}
%}

example.pl:
use example;

sub findFoo {
  my $y = shift;

  my $bar = new example::Bar;
  $bar->{y} = $y;
  example::fillBar($bar);

  return $bar->{f};
}

my $foo = findFoo(7);
print "And the answer is ", $foo->{x}, "\n";