Home > Enterprise >  which swig functions require %newobject to avoid a memory leak in python
which swig functions require %newobject to avoid a memory leak in python

Time:10-05

If we return value created by SWIG_NewObjectPtr without flags, it will have reference count of 1 and would never be garbage collected. In order to avoid it I have to use %newobject in .i file.

However, there are quite a few swig primitives that could be used to make the value returned into python. I suspect that some of them should be also annotated as %newobject.

Is there a list or should blindly annotate all functions returning anything into python? Is there a way to apply %newobject globally or per-file?

CodePudding user response:

For SWIG_NewPointerObj, Python will track the reference if needed. Set the own flag. If that return value isn't assigned to a variable its reference count would be decremented. %newobject isn't intended for Python objects.

%newobject is used to indicate that a function returns an C/C allocated object that isn't reference counted, such as return new char[50]; or return (char*)malloc(1000);. In the previous example SWIG will create a Python string by copying the data, but doesn't know to free the returned pointer without %newobject. You may also need to write a %typemap(newfree) if SWIG doesn't already have one for the type.

References:

  • Related