|
From: Daniel M. <ang...@gm...> - 2010-02-15 02:50:44
|
I have started wrapping some C++ objects for use in python using swig and I
am having problems with object ownership.
Here is a rather contrived simplest case example of what is happening to me.
Given this C++ code:
/////////////////////////////
class Hold
{
public:
Hold(const char * label)
{
m_label = label;
}
void tell()
{
std::cout << "This is in held: " << m_label << std::endl;
}
protected:
const char * m_label;
};
class Container
{
public:
Container(Hold * obj)
{
m_obj = obj;
}
void doTell()
{
if (m_obj)
m_obj->tell();
}
protected:
Hold * m_obj;
};
/////////////////////////////
And if you then use this example module in python like so:
l = list()
def start():
h = Hold('h1')
c = Container(h)
print 'tell1'
c.doTell()
l.append(c)
start()
print 'tell2'
c = l.pop(0)
c.doTell()
tell1 is ok
tell2 is garbage
This is I assume because python doesn't know "Container" is holding a
reference to "Hold" so as soon as it leaves start it garbage collects it.
How do I tell python that Container is going to hold a reference for this
parameter?
While searching for an answer I found section "31.4.2 Memory management" in
the python swig documentation sort of talk about this with "thisown", it is
talking about returning new objects, I am trying to hold a reference to an
existing one
%ref %unref seem to be about reference counting the C++ objects themselves
if it was being held in a smart pointer not telling python at all
so I assume the answer lies in a typemap. I can use Py_INCREF to increment
the reference count in a special typemap as it comes in, but then I have no
way to decrement the reference count on containers destruction.
Maybe I am just missing something obvious, any help would be appreciated.
|