BUG in SWIG refcouting
Grzegorz Makarewicz
mak at mikroplan.com.pl
Wed Dec 20 05:56:48 EST 2000
Every SWIG version, which generates python code, has a bug.
This bug is in function which takes Python's self variable.
For SWIG-883 it is a SWIG_GetPtrObj function.
Below is the patched version:
SWIGSTATICRUNTIME(char *)
SWIG_GetPtrObj(PyObject *obj, void **ptr, char *type) {
PyObject *sobj = obj;
char *str;
if (!PyString_Check(obj)) {
sobj = PyObject_GetAttrString(obj,"this");
if (!sobj) return "";
//test by commenting NEXT line!
Py_DECREF(sobj);
}
str = PyString_AsString(sobj);
return SWIG_GetPtr(str,ptr,type);
}
How to check this?
Create the files:
1. swigbug.i which contains:
//
%module swigbug
%{
#include "swigbug.h"
%}
%include "swigbug.h"
// EOF
2. swigbug.h which contains:
class SwigBug {
public:
SwigBug(){}
~SwigBug(){}
};
//EOF
3. d_xrange.py which contains:
import sys
import swigbug
def demo():
bug=swigbug.SwigBug()
def main():
print 'xrange:'
rc0=sys.gettotalrefcount()
rc1=sys.gettotalrefcount()
for i in xrange(100):
demo()
rc1=sys.gettotalrefcount()
if rc1-rc0:
print 'loop:',i,rc0,'+',rc1-rc0
rc0=rc1
main()
# EOF
4. Compile the debug version of module swigbug and execute in the debug
version of Python
command line for swig: swig -python -dnone -c++ -shadow -o swigbugc.cpp
swigbug.i
5. Have you patched the file generated by SWIG?
NO - at the end of every loop you should see the message, that reference
counter is increased
YES - there are messages about increasing the reference counter for numbers
in range 86-99 (WHY???)
6. For curious: you could check what will you get if you change the loop
from:
for i in xrange(100)
to:
for i in [0 , 1 , ..., 100]:
or:
for i in range(100):
or:
while i<101:
Grzegorz Makarewicz
More information about the Python-list
mailing list