Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIG - Garbage Collection using %newobject

Tags:

c

swig

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!

like image 436
Fabio Cabral Avatar asked Jan 02 '11 00:01

Fabio Cabral


1 Answers

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.

like image 172
Mark Tolonen Avatar answered Oct 06 '22 19:10

Mark Tolonen