Swig - BigClass Example

Swig and Garbage Collection

This is a simple Python example to show the type of situation where the swigged C++ problem comes up.

This code works fine in pure python, but has issues if using swigged version of objects.

class SubClass(object):
    def __init__(self):
        self.x = 0

    def do_something(self):
        print "x = %s" %(self.x, )

class BigClass(object):
    def __init__(self):
        self._sub = SubClass()

    def sub(self):
        return self._sub

def afunction():
    big = BigClass()
    Asub = big.sub()

    # Give SubClass a real value
    Asub.x = 42

    return Asub

asub = afunction()

# This works fine in pure Python.
# Bad things happen here if using Swigged versions 
# of BigClass and SubClass