5

In my C code, I have the following structure :

typedef struct my_structure{
    char* str1;
    char* str2;
}MyStruct;

And a function that returns a MyStruct pointer :

MyStruct* foo();

Inside foo, I have allocated memory for MyStruct , str1 and str2, as follows:

MyStruct* obj = malloc(sizeof(MyStruct));

obj.str1 = malloc(256);
obj.str2 = malloc(256);

I want to call foo from python, java, C# and PHP and I don't want to have any memory leak in this process.

I am not sure if writing:

%newobject foo;
MyStruct* foo();

guarantees that the garbage collector will free memory for both the structure and the strings inside it.

I didn't want to obligate the caller to explicit free memory for str1 and str2 as I was looking for an automatic way of freeing memory. Is this possible?

Do I have to use "newfree" typemap in this case?

I would greatly appreciate if you could provide me an example showing the best way to accomplish this.

Thanks!

Fabio Cabral
  • 648
  • 6
  • 10

1 Answers1

5

typemap(newfree) frees the memory used by the returned %newobject immediately, such as when a char* return value is converted into a Python string and the allocated object is no longer needed. I think what you want is %extend the class wrapper that SWIG generates around your C structure to provide a destructor:

%newobject foo;

%extend MyStruct {
    ~MyStruct() {
       free($self->str1);
       free($self->str2);
    }
}

Please comment if this solves your issue. This is based on my own experimentation with what I could find in the SWIG documentation and worked correctly in the simple wrapper I generated.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • I have just finished the memory monitoring tests on Python and this solution worked perfectly. The GC was able to call the destructor and no memory was left allocated. I must now test it on Java, C# and PHP, but I am pretty sure it will work just fine as well. Thanks Mark. – Fabio Cabral Jan 02 '11 at 18:59
  • Thank you very much, I tried to get this working using newobject and newfree and everything kept crashing. – dom0 May 24 '12 at 18:17