Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to free a malloc'ed char* returned with SWIG

Tags:

python

c

swig

I'm using SWIG and my function returns a char *, which was malloc'ed. SWIG returns PyString_FromStringAndSize(my-char-str, len).

Is there a way to free this my-char-str without editing the C wrapper code?

like image 659
user1623076 Avatar asked Feb 20 '23 09:02

user1623076


1 Answers

Use the %newobject directive in your .i file. From the SWIG 2.0 documentation:

If you have a function that allocates memory like this,

char *foo() {
   char *result = (char *) malloc(...);
   ...
   return result;
}

then the SWIG generated wrappers will have a memory leak--the returned data will be copied into a string object and the old contents ignored.

To fix the memory leak, use the %newobject directive.

%newobject foo;
...
char *foo();
like image 67
Mark Tolonen Avatar answered Feb 22 '23 05:02

Mark Tolonen