swig/python memory leak question

danwald danny.crasto at gmail.com
Wed Jan 23 17:12:05 EST 2008


I am just getting into swig and trying to wrap my C++ library in
python. I have a newbee question.
If my C++ object has a method that allocates memory and returns a void
* to it, python complains about a memory leak.
For example
<code>
%module test
%{
#include "test.h"
%}

%include "typemaps.i"
%newobject tester::get;
%newobject tester::get_uchar;
%newobject tester::get_void;

class tester {
   public:
      tester() : length(rand()) { std::cerr<<"\ntester::tester() len =
"<<length;}
      ~tester() { std::cerr<<"\ntester::~tester()";}
      int  search(char *value);
      void insert(char *val);
      void remove(char *val);
      char *get(int n);
      u_char *get_uchar(int n);
      void *get_void(int n);
      int  length;

      static void print(tester *l);
};
</code>

I have left out the the header and impl file.
The functions I am referring to are the ones that return the pointers.
The char* pointer is fine.
However u_char* reports the error "wig/python detected a memory leak
of type 'u_char *', no destructor found." If I add
<code>
%apply char* {u_char*} there is no error.
</code>
However, I cant do the same for the void * as I have a function
dependency (python.opencv) that requires a void *.

So my question is, how can I provide a destructor for these data types
that takes care of the leak. An example would be really helpful
thanks,



More information about the Python-list mailing list